question_id int64 25 74.7M | answer_id int64 332 74.7M | title stringlengths 20 150 | question stringlengths 23 4.1k | answer stringlengths 20 4.1k |
|---|---|---|---|---|
706,921 | 2,723,270 | Problems with setting application icon | (I'm using Visual Studio 2008, though I remember having similar problems with older versions as well.)
I've tried several different methods (many of them mentioned in this other question), but I am still having some strange issues:
When including an icon as a resource, it does show up as the executable file's icon imm... | I've revisited this to see if I can close out my question. I have been unable to get the app's icon to show up in the alt-tab list just through embedding it in the executable; it will show up in the taskbar, as the file's icon in Explorer, and elsewhere just fine.
I figured I'd try something simpler for setting the ic... |
707,081 | 707,180 | Are operator overloadings in C++ more trouble than they're worth? | In my experience teaching C++, operator overloading is one of those topics that causes the most grief to students. Even looking at questions here at stackoverflow: for example, make the + operator external or a member? How to handle symmetry, etc., it seems like it's a lot of trouble.
When I moved from C++ to Java, I w... | Overloaded operators are like spice. A little can make something better; too much can make it unpalatable.
|
707,332 | 707,338 | Printing a custom number of header delimiters based on message length | Say I want to print:
============
Some message
============
And:
=======================
Other Message long one
=======================
The number of "=" changes based on the message length. What is the most efficient way to print this sort of a thing?
No boost, just STL please.
| std::string line(msg.length(), '=');
cout << line << "\n" << msg << "\n" << line << endl;
|
707,370 | 707,426 | Clean, efficient algorithm for wrapping integers in C++ | /**
* Returns a number between kLowerBound and kUpperBound
* e.g.: Wrap(-1, 0, 4); // Returns 4
* e.g.: Wrap(5, 0, 4); // Returns 0
*/
int Wrap(int const kX, int const kLowerBound, int const kUpperBound)
{
// Suggest an implementation?
}
| The sign of a % b is only defined if a and b are both non-negative.
int Wrap(int kX, int const kLowerBound, int const kUpperBound)
{
int range_size = kUpperBound - kLowerBound + 1;
if (kX < kLowerBound)
kX += range_size * ((kLowerBound - kX) / range_size + 1);
return kLowerBound + (kX - kLowerBoun... |
707,447 | 707,479 | Single XMLHTTPRequest object to make multiple requests | Does anyone know if there is a way to use a single XMLHTTPRequest object to send multiple asynchronous requests. I can do it with a single request and get a response back from my onreadystatechange() handler.
I'm wondering if there's a way to use the same object to send multiple parallel requests but I'm not seeing an... | Short answer: You can't.
Question you really need to ask yourself is why would you want that over multiple XMLHTTPRequest objects ? There's hardly a downside to instantiating a dozen or so objects.
|
707,492 | 707,862 | How do I paint with QPainter? | I have started learning Qt recently.
I did not get quite clear how can I paint using QPainter class. Let`s say I want just to place a few points in the window:
class PointDrawer: public QWidget {
Q_OBJECT
private:
QPainter p;
public:
PointDrawer(QWidget* obj=0): QWidget(obj), p(this) {}
virtual void p... | I think the problem is your QPainter initialization.
You could just create the QPainter like in hydroes' answer, it would look like this then:
class PointDrawer: public QWidget {
Q_OBJECT
public:
PointDrawer(QWidget* obj=0): QWidget(obj) {}
virtual void paintEvent(QPaintEvent*) {
QPainter p(this);
... |
707,497 | 707,876 | Set app to require elevation? | I'm working on the bootstrap application of a new installer for some of our products. So far, I've been relying on two things that I read about somewhere:
Applications whose name contains "setup" or "install" will run elevated by default.
Applications that run elevated will launch other applications in elevated mode.
... | When I couldn't find application manifest as a new item that could be added to my project, I went into the online help and found this:
configure the VS2008 in Configuration Properties - Linker - Manifest File - UAC Execution Level (requireAdministrator)
That did the trick.
|
708,089 | 708,101 | C++ using namespaces to avoid long paths | I am still learning C++, and I have never really created my own namespaces before. I was experimenting with them and while I got most things to work, there's one thing that I still can't seem to do. I would like to be able to call a static method within a class without typing something like NameOfClass::method. Here... | There is no way around it you need to specify the class name for static methods.
using namespace Test;
Then:
int answerToEverything = A::foo();
|
708,114 | 708,261 | Convert Byte Array into Bitset | I have a byte array generated by a random number generator. I want to put this into the STL bitset.
Unfortunately, it looks like Bitset only supports the following constructors:
A string of 1's and 0's like "10101011"
An unsigned long. (my byte array will be longer)
The only solution I can think of now is to read the... | Something like this?
#include <bitset>
#include <climits>
template<size_t numBytes>
std::bitset<numBytes * CHAR_BIT> bytesToBitset(uint8_t *data)
{
std::bitset<numBytes * CHAR_BIT> b;
for(int i = 0; i < numBytes; ++i)
{
uint8_t cur = data[i];
int offset = i * CHAR_BIT;
for(int bit... |
708,285 | 708,322 | Is there some sort of tool or helper to port an MFC/C++ app to OS X/Cocoa? | I have a significant codebase written in MFC and am tasked with creating a port for Mac OS X. I know that I'm going to have to roll up my sleeves at some point and do alot of grunt work to get everything working correctly, but are there any tools out there that might get me partway?
| I'm working on one.
From the GUI point of view, the new version of AppMaker is based around an import/generate model. Most of commercial work I've done with AppMaker has been the other way, porting Macintosh applications to Windows. However, there's no reason why the same principles can't be applied in reverse.
AppMak... |
708,460 | 708,493 | Compiler error with `<<` | I've been working on getting this program complete where it saves multiple structs to a file, can read them back and edit them, then save them all back to a file. I've been working on the logic of this not to mention lots of help from others and a ton of googling hours... now I am getting a compile error. Any help woul... | You have no operator<< defined that would specify how your InventoryItem should be printed to an output stream. You try to print it and the compiler doesn't know how. You need to define a function like this one:
std::ostream& operator<<(std::ostream &strm, const InventoryItem &i) {
return strm << i.Item << " (" << i.... |
708,742 | 708,945 | C++ std::transform side effect | I've implementation of UnaryOperation like this
struct Converter
{
Converter( std::size_t value ):
value_( value ), i_( 0 )
{}
std::string operator() ( const std::string& word )
{
return ( value_ & ( 1 << i_++ ) ) ?
word:
std::string( word.size(), ' ' );
}
... | Qute from standard:
25.2.3 Transform [lib.alg.transform]
Requires:
op and binary_op shall not have any side effects.
Side Effect ( wikipedia definition )
In your case we have next side effect:
Converter c( data );
c( some_const_value ) != c( some_const_value );
You don... |
708,807 | 709,028 | GCC/Make Build Time Optimizations | We have project which uses gcc and make files. Project also contains of one big subproject (SDK) and a lot of relatively small subprojects which use that SDK and some shared framework.
We use precompiled headers, but that helps only for re-compilation to be faster.
Is there any known techniques and tools to help with... | You can tackle the problem from two sides: refactor the code to reduce the complexity the compiler is seeing, or speed up the compiler execution.
Without touching the code, you can add more compilation power into it. Use ccache to avoid recompiling files you have already compiled and distcc to distribute the build time... |
708,872 | 708,874 | C++ runtime required? | Why do some C++ projects require a runtime package to be installed, while others do not?
EDIT:How to make a project to work without the runtime?
| Some will have been statically linked, while others will depend on a dynamic library, loaded at run-time. To link your own project statically, you need to change your project configuration - how you do this depends on the compiler/linker and/or IDE you are using.
|
708,948 | 708,957 | When will STL iterator be equal to zero? | I have a program which is like this
list<int>:: iterator n = alist.begin();
while(n!= (list<int>::iterator)0)
{
printf("Element is %d\n",*n);
n = alist.erase(n);
}
So here i am comparing iterator with zero.
but after deleting the last element the compiler is showing this error.
*** glibc detected *** ./new: f... | Why do you think the iterator will ever "be zero"? Iterators are not pointers or indexes. If you need to check if a container is empty, use the empty() member function.
|
709,146 | 709,161 | How do I clear the std::queue efficiently? | I am using std::queue for implementing JobQueue class. ( Basically this class process each job in FIFO manner).
In one scenario, I want to clear the queue in one shot( delete all jobs from the queue).
I don't see any clear method available in std::queue class.
How do I efficiently implement the clear method for JobQueu... | A common idiom for clearing standard containers is swapping with an empty version of the container:
void clear( std::queue<int> &q )
{
std::queue<int> empty;
std::swap( q, empty );
}
It is also the only way of actually clearing the memory held inside some containers (std::vector)
|
709,790 | 709,996 | How can I know the address of owner object in C++? | I would like to create in C++ a Notifier class that I will use in other objects to notify various holders when the object gets destroyed.
template <class Owner>
class Notifier<Owner> {
public:
Notifier(Owner* owner);
~Notifier(); // Notifies the owner that an object is destroyed
};
class Owner;
class Owned {
pub... | Or something like this :
Inherit from your notifier and add Owned as template parameter. Then you can have a owned method available inside the notifier :
template < class Owner , class Owned >
class Notifier
{
public:
Notifier(Owner* owner)
{}
Owned * owned()
{ return static_cast< Owned * >( this ); }
... |
709,795 | 710,300 | debug stack overflow in windows? | So I'm trying to debug this strange problem where a process ends without calling some destructors...
In the VS (2005) debugger, I hit 'Break all' and look around in the call stacks of the threads of the misteriously disappearing process, when I see this:
smells like SO http://img6.imageshack.us/img6/7628/95434880.jpg
T... | To control what Windows does in case of an access violation (SIGSEGV-equivalent), call SetErrorMode (pass it parameter 0 to force a popup in case of errors, allowing you to attach to it with a debugger.)
However, based on the stack trace you have already obtained, attaching with a debugger on fault may yield no addit... |
709,914 | 709,950 | Windows: Overwrite File In Use | I am trying to write a utility that will allow moving files in Windows, and when it finds a file in use, will set that file to be moved on reboot.
It seems that MoveFileEx (http://msdn.microsoft.com/en-us/library/aa365240(VS.85).aspx) is the right call for this, however I cannot figure out what error code I'm looking f... | You have to call CreateFile first to see if the file is in use.
To see if the file is in use:
If you get a valid file handle then you know the file does not have conflicting sharing permissions with a process that already has this file open.
If you specify no sharing access (0 to the dwShareMode parameter of the Cr... |
710,253 | 711,462 | How to load all files from a directory? | Like the title says; how do I load every file in a directory? I'm interested in both c++ and lua.
Edit:
For windows I'd be glad for some real working code and especially for lua. I can do with boost::filesystem for c++.
| For Lua, you want the module Lua Filesystem.
As observed by Nick, accessing the file system itself (as opposed to individual files) is outside the scope of the C and C++ standards. Since Lua itself is (with the exception of the dynamic loader used to implement require() for C modules) written in standard C, the core l... |
710,432 | 710,447 | "No appropriate default constructor available" error in Visual C++ | I don't get it. I've been staring at the code the code for three hours and I can't see the problem.
The class I'm creating, called TwoDayPackage is derived from a class called Package.
This is how I defined the constructor:
TwoDayPackage(string, string, string, string, int, string, string, string, string, int, floa... | Should use:
TwoDayPackage::TwoDayPackage(string sName, string sAddress, string sState, string sCountry, int sZIP, string rName, string rAddress, string rState, string rCountry, int rZIP, float weight, float cost, float flat)
:Package(sName, sAddress, sState, sCountry, sZIP, rName, rAddress, rState, rCountry, rZIP, we... |
710,604 | 36,564,745 | How do I set EOF on an istream without reading formatted input? | I'm doing a read in on a file character by character using istream::get(). How do I end this function with something to check if there's nothing left to read in formatted in the file (eg. only whitespace) and set the corresponding flags (EOF, bad, etc)?
| You can strip any amount of leading (or trailing, as it were) whitespace from a stream at any time by reading to std::ws. For instance, if we were reading a file from STDIN, we would do:
std::cin >> std::ws
Credit to this comment on another version of this question, asked four years later.
|
710,607 | 710,627 | Why do I get a segmentation fault when calling a virtual method in this code? | I'm still learning C++; I was trying out how polymorphism works and I got a segmentation fault when calling a virtual method.
(Note: I didn't mark the destructor as virtual, I was just trying out to see what happens.) Here's the code:
#include <iostream>
using namespace std;
class Base
{
protected:
char *name;
pub... | name - is unintialized in Base
also you have another problem:
Base c = Child("2");
I don't think it's what you want. Your code will create an instance of Base from casted Child. But I think you want work with Child instance based on Base interface; you should instead write:
Base *c = new Child("2");
also, to ... |
710,638 | 983,968 | Simple email program / library recommendations | I am needing to implement email notifications for a C++ project. Basically a user provides all the relevant information for their email account and on certain events this component would fire off an email. Ideally I would like to find a small cross platform open source command line project that I can exec from within... | I ended up using the Perl script sendEmail. A windows binary was available and building a new binary after modifying the Perl script was not too hard to do at all. The script also had no issues running in the LTE Ubuntu environments after the required Debian packages were installed.
|
710,807 | 710,832 | rules with temporary objects and args by reference | say I have a class:
class A
{
public:
A() {}
};
and a function:
void x(const A & s) {}
and I do:
x(A());
could someone please explain to me the rules regarding passing temporary objects by reference? In terms of what the compiler allows, where you need const, if an implicit copy happens, etc. From playing around, ... | There is a formal rule - the C++ Standard (section 13.3.3.1.4 if you are interested) states that a temporary can only be bound to a const reference - if you try to use a non-const reference the compiler must flag this as an error.
|
711,350 | 711,386 | Learning to work with audio in C++ | My degree was in audio engineering, but I'm fairly new to programming. I'd like to learn how to work with audio in a programming environment, partly so I can learn C++ better through interesting projects.
First off, is C++ the right language for this? Is there any reason I shouldn't be using it? I've heard of Soundfile... | It really depends on what kind of audio work you want to do, If you want to implement audio for a game, C++ is sure the right language. There are many libraries around, OpenAL is great, free and multiplatform. I also used DirectSound and Fmod with great sucess. Check them out, it all depends on your needs.
|
711,603 | 711,701 | Docking control bars/panes to CMDIFrameWndEx? | In one of our applications I've used some of the MFC classes to allow docking a sidebar window, approximately like so:
CDialogBar* bar = new CDialogBar;
bar->Create(this, IDD, WS_CHILD | WS_VISIBLE | CBRS_RIGHT | CBRS_TOOLTIPS, IDD));
bar->EnableDocking(CBRS_ALIGN_ANY);
EnableDocking(CBRS_ALIGN_RIGHT | CBRS_ALIGN_LEFT)... | If we both shoot in the dark, we double our chances of hitting something.
Looking at the documentation for CDockablePane (the parent class of CPaneDialog), I notice a method called EnableGripper. Try that.
|
711,669 | 4,027,195 | How can I call a .NET form from an MFC application? | We have a several large MFC applications which presently call a COM object to bring up a complex dialog. We would like to integrate the dialog into the applications -- we do not want to continue to use a COM object.
I'm investigating the possibility of building the dialog in .NET as a separate project (using Windows f... | I finally solved this problem with the help of a very good Microsoft support specialist. There were two problems, one was that the Boost library's threading is incompatible with C++/CLI in its default state. One solution is to compile with a different set of flags and then statically link it. The other is to use it ... |
711,770 | 712,275 | Fast implementation of Rolling hash | I need a Rolling hash to search for patterns in a file. (I am trying to use the Rabin-Karp string search algorithm).
I understand how a good Hash works and how a good Rolling Hash should work but I am unable to figure out how to efficiently implement the divide (or inverse multiplication) when rolling the hash. I also ... | Cipher's "prime base" idea should work decently - though the solution he posted looks a bit sketchy.
I don't think there's any need for inverse multiplication in this method.
Here's my solution:
Say the string we currently have hashed is "abc", and we want to append "d" and remove "a".
Just like Cipher, my basic hash a... |
711,779 | 712,221 | Template Meta-programming with Char Arrays as Parameters | I'm playing around with TMP in GCC 4.3.2's half-implementation of C++11, and I was wondering if there was a way to somehow do the following:
template <char x, char... c>
struct mystruct {
...
};
int main () {
mystruct<"asdf">::go();
}
It obviously won't let me do it just like that, and I thought I'd get lucky by... | Sadly, you still have to split it into separate characters, eg:
myTemplate<'s','t','r','i','n','g'>
In my humble opinion, this is a huge oversight in the new standard. Some other people agreed, and tried to implement the behavior in GCC with pretty good results. You can find that thread here.
Edit: Some weird proble... |
712,279 | 712,307 | What is the usefulness of `enable_shared_from_this`? | I ran across enable_shared_from_this while reading the Boost.Asio examples and after reading the documentation I am still lost for how this should correctly be used. Can someone please give me an example and explanation of when using this class makes sense.
| It enables you to get a valid shared_ptr instance to this, when all you have is this. Without it, you would have no way of getting a shared_ptr to this, unless you already had one as a member. This example from the boost documentation for enable_shared_from_this:
class Y: public enable_shared_from_this<Y>
{
public:
... |
712,282 | 712,292 | enqueue() method adds one element to the queue: how to implement in C++? | I'm having a hard time trying to implement this method since array subscripts in C++ start with zero. The method add one element to the queue. You can use f (front) and r (rear) pointers and a sequential list of size n. If you find that additional variables are needed fell free. Thanks.
Thats my try but I know its wron... | To implement a queue using plain arrays, just treat it circularly - so as soon as you run out of space in the array, wrap back around to 0. You'll need to keep a record of front and rear, as you note. As an example (where X represents an item in the queue):
// Rear is where to enqueue into, Front is where to dequeue fr... |
712,334 | 712,349 | Does the evil cast get trumped by the evil compiler? | This is not academic code or a hypothetical quesiton. The original problem was converting code from HP11 to HP1123 Itanium. Basically it boils down to a compile error on HP1123 Itanium. It has me really scratching my head when reproducing it on Windows for study. I have stripped all but the most basic aspects... Yo... | Looks like the compiler is optimizing
printf("IAMCONST %d \n",IAMCONST);
into
printf("IAMCONST %d \n",3);
since you said that IAMCONST is a const int.
But since you're taking the address of IAMCONST, it has to actually be located on the stack somewhere, and the constness can't be enforced, so the memory at that locat... |
712,623 | 712,633 | How do you use an exponent in c++ with a variable? | So I realize that #include is necessary, and that there is a pow(x,y) where x^y works...but when I attempted to use pow(2,(num-1)), it kicked back an error...
errorC2668: 'pow' : ambiguous call to overloaded function
the line of code I have for it is as follows
perfect = (pow(2,(num-1))) * (pow(2,num)-1);
Any recommen... | The compiler doesn't know which pow() function to call. The overloads listed here gives the following list:
float pow ( float base, float exponent );
double pow ( double base, double exponent );
long double pow ( long double base, long double exponent );
float pow ( float ba... |
712,691 | 712,712 | Registering implementation of a COM interface | I'm new to COM programming. I've got a COM object (and associated IClassFactory) all ready to go, but I can't quite figure out how to go about registering the resulting DLL for use by other programs. The number of GUIDs I need to sling around is also unclear to me.
The COM object I'm trying to register implements the... | I'm not sure from this post whether you are implementing or consuming the DLL that supports IAudioSessionEvents. If you're consuming this DLL, then you can register the component using the comment line utility regsvr32. To register use:
regsvr32
To unregister:
regsvr32 /u
regsvr32 should be on your path, so this co... |
712,737 | 713,204 | Callback Routine Not Getting Triggered | I've created a very simple one-button MFC dialog app that attempts to utilize a callback function. The app complies and runs just fine, but the callback routine never gets triggered.
What needs to be modified in order to get the callback to trigger properly?
You can download the test.zip file here (the test app is in ... | I've looked at your code and the I believe the Function called from the button is the problem
void CTestDlg::OnBnClickedButton1()
{
CAlarmClock clock;
REPEAT_PARMS rp;
ZeroMemory(&rp, sizeof(REPEAT_PARMS));
rp.bRepeatForever = TRUE;
rp.Type = Repeat_Interval;
rp.ss = 3;
clock.SetRepeatAla... |
712,975 | 734,293 | How to track memory leaks with umdh.exe in all heaps? | I have a c++ windows application that leaks memory per transaction. Using perfmon I can see the private bytes increase with every transaction, the memory usage is flat while the application is idle.
Following previous answers on stackoverflow I used umdh from the microsoft debugging tools to track down one memory leak... | Sorry to answer my own question, but I finally tracked the issue down to how I used Orbix.
It seams that the orbix libraries use their own heap on the windows platform. This means that most memory leak detection does not work for leaks in orbix, I tried boundschecker and umhd.exe.
To isolate this issue I found some co... |
712,998 | 13,615,449 | OpenCV with Network Cameras | I'm using openCV 1.1pre1 under Windows.
I have a network camera and I need to grab frames from openCV. That camera can stream a standard mpeg4 stream over RTSP or mjpeg over http.
I've seen many threads talking about using ffmpeg with openCV but I cannot make it work.
How I can grab frames from an IP camera with openCV... | rtsp protocol did not work for me.
mjpeg worked first try. I assume it is built into my camera (Dlink DCS 900).
Syntax found here:
http://answers.opencv.org/question/133/how-do-i-access-an-ip-camera/
I did not need to compile OpenCV with ffmpg support.
|
713,042 | 713,052 | Should "portable" C compile as C++? | I got a comment to an answer I posted on a C question, where the commenter suggested the code should be written to compile with a C++ compiler, since the original question mentioned the code should be "portable".
Is this a common interpretation of "portable C"? As I said in a further comment to that answer, it's totall... | No. My response Why artificially limit your code to C? has some examples of standards-compliant C99 not compiling as C++; earlier C had fewer differences, but C++ has stronger typing and different treatment of the (void) function argument list.
As to whether there is benefit to making C 'portable' to C++ - the particu... |
713,309 | 713,479 | C++ STL: Can arrays be used transparently with STL functions? | I was under the assumption that STL functions could be used only with STL data containers (like vector) until I saw this piece of code:
#include <functional>
#include <iostream>
#include <numeric>
using namespace std;
int main()
{
int a[] = {9, 8, 7};
cerr << "Sum: " << accumulate(&a[0], &a[3], 0, plus<int>())... | Well, you ask about an array. You can just easily get a pointer to its elements, so it basically boils down to the question whether pointers can be used transparently with STL functions. A pointer actually is the most powerful kind of an iterator. There are different kinds
Input iterator: Only forward and one-pass, an... |
713,698 | 713,717 | C++ namespaces advice | I'm just teaching myself C++ namespaces (coming from a C# background) and I'm really starting to think that even with all the things that C++ does better than most other languages, nested namespaces isn't one of them!
Am I right in thinking that in order to declare some nested namespaces I have to do the following:
n... | C++ namespaces were not intended to be a design mechanism - they are there simply to prevent name clashes. You really don't want or need to use nested namespaces in 99.99% of situations.
A good example of the correct use of namespaces in C++ is the C++ Standard Library. Everything in this quite large library is placed ... |
713,701 | 750,479 | Force-directed layout implementation in C++ | Are you aware of an open source implementation of force-directed layout in C++ used for GUIs? Preferably BSD/MIT/Apache or other (non-GPL) license.
| The excellent Boost.Graph library provides a wide range of algorithms, among which a few layout algorithms. I'd recommend using either Kamada-Kawai spring layout or Fruchterman-Reingold force-directed layout.
Boost licence is very permissive so don't worry about that.
|
713,704 | 713,735 | C++ as a first language | I've been self-learning C++ for about 4 months now. I'm enjoying it, and I think I'm doing quite well. However, an answer to a question of mine got me thinking that I might be setting myself up for a fall.
So, what do people here think about C++ as a first language to learn? And is it worth me just carrying on now that... | I don't understand why people still confuse "language" with "library". (Referring to the linked answer.) So what if C++ doesn't have a "native" concept of audio? There are lots of libraries out there, which you can readily use with C++, and which are probably better suited to your specific needs than any "catch-all" "s... |
713,797 | 713,820 | Naming functions, methods, pointers, variables, arrays etc in C++ | Allright, doing some project with few friends, and I need some standard for naming things in c++. Does anyone have any good naming scheme for c++ that is well thought-out and not made in like 10min.
Example, int* house should be named int* house_p, so that when someone reads the code, he doesn't need to scroll all the ... |
Example, int* house should be named
int* house_p, so that when someone
reads the code, he doesn't need to
scroll all the time wondering if a
thing is a pointer, array, matrix, or
whatever...
But what if its type changes - are you going to go through all your code and change the names of all the variables. A... |
714,142 | 714,228 | JPEG Quality when creating a JPEG in Carbon | I'm writing a Carbon application and we are creating JPEG files. I'm currently doing this by using Quartz CGImageDestinations and kCGImagePropertyJFIFDictionary. However, JFIF doesn't seem to have any entry for compression quality. Does anyone know how to set this?
thanks
| This is separate from the JFIF options, since some other formats (including TIFF) support lossy compression. The key you use is kCGImageDestinationLossyCompressionQuality, and you put this option and the JFIF-options dictionary into the same dictionary; you don't put it into the JFIF-options dictionary.
|
714,205 | 714,218 | How does the draggable crosshair in Process Explorer work? | There is a feature in Sysinternal's Process Explorer that allows a crosshair to be dragged from the application to a control in any other application you are running and highlights said control.
Does anyone know how this was achieved or if there is a .NET/C++ library out there that can be reused?
| Using Win32 API
GetCursorPos: to get the cursor position (maybe .NET has its own function to do that)
WindowFromPoint: to get the handle of the window from a specific point in the screen
more info
|
714,213 | 714,289 | c++ template casting | I'm a little lost in how to cast templates. I have a function foo which takes a parameter of type ParamVector<double>*. I would like to pass in a ParamVector<float>*, and I can't figure out how to overload the casting operator for my ParamVector class, and Google isn't helping me that much. Does anyone have an example ... | I'm not sure but maybe you need some like this:
template< typename TypeT >
struct ParamVector
{
template < typename NewTypeT >
operator ParamVector< NewTypeT >()
{
ParamVector< NewTypeT > result;
// do some converion things
return result;
}
template< typename NewTypeT >
... |
715,139 | 715,190 | Why would you cast the lhs of an assignment? | I came across some code that boils down to the following:
enum BAR { /* enum values omitted */ }
class Foo{
public:
void set(const BAR& bar);
private:
uint32_t bits;
};
void Foo::set(const BAR& bar)
{
(uint32_t&)bits = bits | bar;
}
I don't understand the point of the c-style cast in the assignment in Foo::set.... | In this case, I can't see any reason for the cast, as the thing being cast is of the same type as the cast. In general, it could be used to force a particular assignement operator to be used.
I will now repeat my mantra: If your code contains casts, there is probably something wrong with the code or the design and you ... |
715,530 | 715,544 | Unit testing and mocking small, value-like classes in C++ | I am trying to set up some unit tests for an existing c++ project.
Here's the setup:
I have chosen Google Mock, which includes Google Test. I have added another project (called Tests) to the Visual Studio Solution. The units to test are in another project called Main. The plan is to add each cpp file that I want to te... | Sometimes one can not simply mock things. In that case what you can do is have a comprehensive test for the class in question (CTimeValue) and make sure you run the tests for that class as a subsuite in your other test.
|
715,823 | 715,907 | Print bit representation of a string | How to print the bit representation of a string
std::string = "\x80";
void print (std::string &s) {
//How to implement this
}
| I'd vote for bitset:
void pbits(std::string const& s) {
for(std::size_t i=0; i<s.size(); i++)
std::cout << std::bitset<CHAR_BIT>(s[i]) << " ";
}
int main() {
pbits("\x80\x70");
}
|
715,919 | 715,936 | Member function vs. nonmember function? | What is your rule for which functions that operate on a class should be member functions vs. nonmember functions?
For example, I have a class which represents a maze using a matrix of bools. I am making a function called isConnected which verifies that 2 points in the maze are in the same region (i.e. it is possible to... | When to make it a member function:
when the function is logically coupled with the class (like your maze connectedness example)
when the function needs to access private or protected members, it's better to make it a member than a friend.
When to make it a standalone function
when it's a generic function that can be... |
715,920 | 716,119 | Qt: QGraphicsScene not updating when I would expect it to | Ok so I've got a QGraphicsScene in a class called eye. I call a function:
void eye::playSequence(int sequenceNum) {
for (int i=0; i<sequences[sequenceNum].numberOfSlides(); i++) {
presentSlide(sequenceNum, i);
time_t start;
time(&start);
bool cont=false;
while (!... | This is the kind of behaviour that is often seen in event driven GUI frameworks when one wants to do continuous animation. I'm going to guess that eye::playSequence is called from a button click or maybe from some point during the application startup code? In any case, here is what's going on.
Qt uses the main applicat... |
716,353 | 716,362 | Must new always be followed by delete? | I think we all understand the necessity of delete when reassigning a dynamically-allocated pointer in order to prevent memory leaks. However, I'm curious, to what extent does the C++ mandate the usage of delete? For example, take the following program
int main()
{
int* arr = new int[5];
return 0;
}
While for... | There is nothing that requires a delete[] in the standard - However, I would say it is a very good guideline to follow.
However, it is better practice to use a delete or delete[] with every new or new[] operation, even if the memory will be cleaned up by the program termination.
Many custom objects will have a destruct... |
716,658 | 716,726 | Overloading = in C++ | I'm trying to overload the assignment operator and would like to clear a few things up if that's ok.
I have a non member function, bool operator==( const MyClass& obj1, const myClass& obj2 ) defined oustide of my class.
I can't get at any of my private members for obvious reasons.
So what I think I need to do is to ove... | I am guessing that you want to compare the two objects. In that case, you can just overload the operator == in class "Class". You don't need assignment operator.
class Class
{
public:
Class(int i) : m_i(i){}
bool operator==( const Class& rhs)
{
return m_i == rhs.m_i;
... |
716,762 | 716,769 | C++ STL: Which method of iteration over a STL container is better? | This may seem frivolous to some of you, but which of the following 2 methods of iteration over a STL container is better? Why?
class Elem;
typedef vector<Elem> ElemVec;
ElemVec elemVec;
// Method 0
for (ElemVec::iterator i = elemVec.begin(); i != elemVec.end(); ++i)
{
Elem& e = *i;
// Do something
}
// Method... | The first version works with any container and so is more useful in template functions that take any container a s a parameter. It is also conceivably slightly more efficient, even for vectors.
The second version only works for vectors and other integer-indexed containers. It'd somewhat more idiomatic for those contain... |
716,810 | 716,846 | BOOST_FOREACH: What is the error on using this of a STL container? | Does anyone know why the following generates an error on VC9?
class Elem;
class ElemVec : public vector<Elem>
{
public:
void foo();
};
void ElemVec::foo()
{
BOOST_FOREACH(Elem& elem, *this)
{
// Do something with elem
}
return;
}
The error I get is:
error C2355: 'this' : can only b... | Which compiler/Boost version are you using? I can compile the following without any problem (VS2005/Boost 1.38):
#include <boost/foreach.hpp>
using namespace std;
struct xxx : std::vector<int>
{
void test()
{
BOOST_FOREACH(int x, *this)
{
}
}
};
int main(void) {
xxx x;
x.t... |
716,865 | 716,871 | C++ Boost: Any gotchas with BOOST_FOREACH? | This one is for Boost experts. Are there any gotchas or details that the programmer needs to be aware of before he goes in and replaces all his old C/C++ style loops with the lean-and-mean-looking BOOST_FOREACH?
(This question is partly derived from here.)
| Take a look at:
The Conditional Love article for an understanding of the rationale
The Pitfalls section of documentation
The Portability section just in case you are developing cross-platform products
The bugs page for BOOST_FOREACH
|
716,904 | 716,924 | Preparing for the next C++ standard | The spate of questions regarding BOOST_FOREACH prompts me to ask users of the Boost library what (if anything) they are doing to prepare their code for portability to the proposed new C++ standard (aka C++0x). For example, do you write code like this if you use shared_ptr:
#ifdef CPPOX
#include <memory>
#else
#include ... | The simple answer is "do nothing". Boost is not going to remove the libraries that got adopted into 0x. So boost::shared_ptr will still exist. So you don't need to do anything to maintain portability.
Of course, once 0x is here, a lot of code can be simplified, cleaned up and optimized, but since it's not yet here, tha... |
717,004 | 717,050 | Exception handling aware of execution flow | Edit:
For personn interested in a cleaner way to implemenent that, have a look to that answer.
In my job I often need to use third-made API to access remote system.
For instance to create a request and send it to the remote system:
#include "external_lib.h"
void SendRequest(UserRequest user_request)
{
... | If there really are a lot of methods you need to call, you could cut down on the code using a reflection library, by creating just one method to do the calling and exception handling, and passing in the name of the method/property to call/set as an argument. You'd still have the same amount of try/catch calls, but the ... |
717,239 | 717,251 | io_service, why and how is it used? | Trying to learn asio, and I'm following the examples from the website.
Why is io_service needed and what does it do exactly? Why do I need to send it to almost every other functions while performing asynchronous operations, why can't it "create" itself after the first "binding".
| Asio's io_service is the facilitator for operating on asynchronous functions. Once an async operation is ready, it uses one of io_service's running threads to call you back. If no such thread exists it uses its own internal thread to call you.
Think of it as a queue containing operations. It guarantees you that those ... |
717,509 | 717,526 | Is it ok to mutate objects with std::for_each? | for_each accepts InputIterators :
//from c++ standard
template <class InputIterator, class Function>
Function for_each (InputIterator first, InputIterator last, Function f);
is it ok to change the object in Function f, like this :
struct AddOne
{
void operator()(int & x){x = x + 1;}
};
std::vector<int> vec(... | Read this article.
To be pedantic: for_each is a non-modifying sequence operation. The intent is not to modify the sequence. However, it is okay to modify the input sequence when using for_each.
|
717,618 | 717,758 | Simple server/client boost example not working | Learning boost, and compiled their daytime server client example. Since I cant use port 13 that is in the example I only changed the port numbers in the server and client example. Server runs fine, but the client doesnt connect it seems, and no error is given.
Input data for the client is "127.0.0.1".
Server:
#include ... | A few things would help to debug this for you:
What platform are you running
What compiler are your using, including version
What version of boost are you using
Also, one thing to check is whether the server is binding to 127.0.0.1 or the external interface. Try using the IP address of your external interface instea... |
717,622 | 717,639 | Static Lib Multiple Definition Link Error | So I'm trying to build a small 3D engine as an exercise on VC++ 8.0. I have a MathLib static lib and a Render static lib that is being linked by my TestBed exe. Right now Render has two classes: Color and DXManager3D. Color includes my Vector.h from MathLib just fine, no problems.
The second I try to include Vector.h ... | Is your Vector ctor defined in the header outside the class definition? Make it inline then i.e. change
class Vector {
public:
Vector();
// ...
};
Vector::Vector() {
// ...
}
to
class Vector {
public:
Vector() {}
// ...
};
or use an explicit inline qualification:
class Vector {
public:
Vecto... |
717,636 | 717,750 | Is there an OS independent way to poll TOTAL and/or USED video memory? | I'm looking for a way to poll for total video memory on board a graphics cars / integrated chipset.
I'm aware of WMI assisted polling under Windows, and as far as I understand that information is constructed on every boot by WMI. However, being an optimist, I am looking for a possible OS independent way to poll for to... | There's no simple cross-platform way to do it. You'll have to either code up a way to do it yourself for each platform, or use a third-party library such as SDL to do it for you. For example, with SDL, you can use video_mem member of the return value from SDL_GetVideoInfo() to get the total video memory available.
|
717,729 | 717,741 | Does extern "C" have any effect in C? | I just got some C code that uses extern "C" to declare external functions like this:
extern "C" void func();
Is this valid C? I'm getting an error at this line, but I'm not sure if it's because of this or something else.
| No, it's not valid C. It should only be used in C++ code to refer to functions defined in C code. The extern "C" should be surrounded in a ifdef __cplusplus/#endif block:
// For one function
#ifdef __cplusplus
extern "C"
#endif
void func();
// For more than one function
#ifdef __cplusplus
extern "C"
{
#endif
void f... |
717,759 | 717,764 | Linker error when compiling vshadow, part of the Volume Shadow Copy Service SDK | I am getting this linker error when trying to compile the c++ project for the VSS SDK
Error 1 error LNK2019: unresolved external symbol "long __stdcall ShouldBlockRevert(wchar_t const *,bool *)" (?ShouldBlockRevert@@YGJPB_WPA_N@Z) referenced in function "public: void __thiscall VssClient::RevertToSnapshot(struct _G... | According to this blog post:
As it happens, I ran dumpbin /exports on vssapi.lib, and found that it does export ShouldBlockRevert, but thanks to C++ name mangling the mangled name is different. Why is it different? Because in vssapi.lib, the first argument to ShouldBlockRevert isn’t wchar_t, it’s unsigned short. “So w... |
718,029 | 718,034 | Switch statement use | Should i use this form of switch statement:
switch(msg)
{
case WM_LBUTTONDOWN:
{
char szFileName[MAX_PATH];
HINSTANCE hInstance = GetModuleHandle(NULL);
GetModuleFileName(hInstance, (LPWCH)szFileName, MAX_PATH);
MessageBox(hwnd, (LPCWSTR)szFileName, L"This program... | There's nothing wrong with how you have it, but it's probably cleaner code to call a function so you can keep your functions a reasonable size.
|
718,447 | 789,025 | Adding external library into Qt Creator project | How can I add external library into a project built by Qt Creator RC1 (version 0.9.2)? For example, the win32 function EnumProcesses() requires Psapi.lib to be added in the project to build.
| The proper way to do this is like this:
LIBS += -L/path/to -lpsapi
This way it will work on all platforms supported by Qt. The idea is that you have to separate the directory from the library name (without the extension and without any 'lib' prefix). Of course, if you are including a Windows specific lib, this really ... |
718,451 | 718,471 | should I use the algorithm or hand-code it in this case? | Ok, someone tell me which would be better. I need to |= the elements of one vector with another. That is, I want to
void orTogether(vector<char>& v1, const vector<char>& v2)
{
typedef vector<char>::iterator iter;
for (iter i = v1.begin(), iter j = v2.begin() ; i != v1.end(); ++i, ++j)
*i |= *j;
}
I can... | The bottom one will compile to effectively the same as the first, your OR functor is going to be inlined for sure. So the second idiom is more flexible if you ever need to add more flexibility or debugging frameworks or whatever.
Since there's no benefit to the first, use the transform method. Once you get into that ... |
718,490 | 718,507 | Segmentation fault in strcpy | consider the program below
char str[5];
strcpy(str,"Hello12345678");
printf("%s",str);
When run this program gives segmentation fault.
But when strcpy is replaced with following, program runs fine.
strcpy(str,"Hello1234567");
So question is it should crash when trying to copy to str any other string of mo... | There are three types of standards behaviour you should be interested in.
1/ Defined behaviour. This will work on all complying implementations. Use this freely.
2/ Implementation-defined behaviour. As stated, it depends on the implementation but at least it's still defined. Implementations are required to document wha... |
718,503 | 718,513 | Stack corruption in C++ | In C++, in which way the stack may get corrupted. One way I guess is to overwriting the stack variables by accessing an array beyond its boundaries. Is there any other way that it can get corrupted?
|
You could have a random/undefined pointer that ends up pointing to the stack, and write though that.
An assembly function could incorrectly setup/modify/restore the stack
Cosmic waves could flips bits in the stack.
Radioactive elements in the chip's casing could flip bits.
Anything in the kernel could go wrong and acc... |
718,676 | 718,745 | Using Boost MPI for sending files? | Can I use the Boost MPI to send files to other computers? My worry is that it is optimized for very small messages and not larger (I need to send 700 MB or more in one go). The reason is that I will probably use mpi for other parts of the program anyway so I thought it would be a pretty clean solution to not mix and ma... | Keep in mind that Boost MPI requires that you already have an MPI implementation on the systems you want to send files with (OpenMPI, MPICH2, MVAPICH2, etc). You'll need to get one of these to go along with Boost MPI.
Also keep in mind that MPI is designed for high performance clusters, and most MPI implementations as... |
718,866 | 718,875 | Method to find "cleanest" subset of data i.e. subset with lowest variability | I am trying to find a trend in several datasets. The trends involve finding the best fit line, but if i imagine the procedure would not be too different for any other model (just possibly more time consuming).
There are 3 conceivable scenarios:
All good data where all the data fits a single trend with a low variabilit... | The RANSAC algorithm is one approach to what you're looking for if I understand you right. http://en.wikipedia.org/wiki/RANSAC
|
718,896 | 718,902 | How is the sizeof operator implemented in c++? | Can someone point me the to the implementation of sizeof operator in C++ and also some description about its implementation.
sizeof is one of the operator that cannot be overloaded.
So it means we cannot change its default behavior?
| sizeof is not a real operator in C++. It is merely special syntax which inserts a constant equal to the size of the argument. sizeof doesn't need or have any runtime support.
Edit: do you want to know how to determine the size of a class/structure looking at its definition? The rules for this are part of the ABI, and c... |
718,972 | 719,007 | Storing a COM pointer in a struct | My program is crashing every time I try to store a COM pointer into a struct, and then later try to use the original pointer. I don't have debug access to tell exactly what's wrong.
pRend->cp = cpRT;
ID2D1SolidColorBrush *scBrush;
ERF(cpRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::CornflowerBlue), &scBrush));
... | As it turns out, I managed to stop the crashing by allocating pRend with malloc. This is not a problem because I will call free when I don't need it anymore. I'm interested in why calling malloc fixes this though. I'm used to just doing Datatype * var; and then just using var. Is that bad?
|
719,043 | 719,491 | Call member function on each element in a container | This question is a matter of style, since you can always write a for loop or something similar; however, is there a less obtrusive STL or BOOST equivalent to writing:
for (container<type>::iterator iter = cointainer.begin();
iter != cointainer.end();
iter++)
iter->func();
?
Something like (imagined) this:
c... | I found out that boost bind seems to be well suited for the task, plus you can pass additional arguments to the method:
#include <iostream>
#include <functional>
#include <boost/bind.hpp>
#include <vector>
#include <algorithm>
struct Foo {
Foo(int value) : value_(value) {
}
void func(int value) {
... |
719,124 | 719,316 | Knowing C++, how long does it take to learn Java? | I am a competent C++ developer. I understand and use polymorphism, templates, the STL, and I have a solid grasp of how streams work. For all practical purposes, I've done no Java development. I'm sure some of you were in a similar situation at one point when you had to learn Java. How long did it take you to become... | I think that learning the language is not difficult. In fact, I used to be a full time C++ developer, and at some point I started writing Java code. But the thing is that I don't remember ever learning Java, so I guess I just figured it as I went. I've been doing full time Java for a long time now.
If you are well fam... |
719,364 | 719,499 | Which GUI framework is used by the "Spybot Search & Destroy" application? | I want to replicate the look and feel of Spybot Search & Destroy in my own applications. Is there a publicly-available framework, toolkit, or library to aid in this task?
| AFAICR it's written in Delphi. With C++ Builder you can use Delphi libraries from C++.
|
719,645 | 719,676 | How does 2 or more processes interact with the keyboard? | I have been thinking a lot over keyboard handling. How does it work? I can't seem to google me to a good explaining.
I know that a keyboard interrupt is made every time a key is pressed. The processor halts whatever it is processing and load the keyboard data from the keyboard buffer, storing it in a system level buffe... | Except in rare situations, your keyboard and display are managed by a Window Manager: X11, Gnome, KDE, Carbon, Cocoa or Windows.
It works like this.
The keyboard driver is part of the OS.
The window manager is a privileged process, which acquires the device during startup. The window manager "owns" the device. Exclus... |
719,650 | 719,709 | open source dev environment for C++: what's better? | I want to do some coding in my spare time, but the thing is, I don't want to spend the money on this.
Would the following set of development tools be The Right Thing, or is there something I'm forgetting?
Eclipse for C++
SVN for source control
Qt for UI development (since it's C++, and I believe it's now opened by Nok... | Microsoft Visual C++ Express is free and easily the best IDE for Windows. Furthermore, you can use it to work on cross-platform code - it more depends on writing standards-adhering code and using portable libraries.
If you want to write cross-platform code, I recommend a cross-platform build tool. I use CMake, which ge... |
720,004 | 720,016 | How do I call unmanaged C/C++ code from a C# ASP.NET webpage | I have an ASP.NET website that uses C# and I'd like to call functions from an unmanaged C/C++ DLL. How do I do it?
| Check out P/Invoke.
Calling Win32 DLLs in C# with P/Invoke
If it's a COM dll, then you can use COM Interop
|
720,049 | 720,059 | Initialization and Assignment | I have some 'legacy' code (which I can't change, but need to add on to) that looks something like this:
template<typename T> T Foo(T& target)
{
//Assign to 'target', but never read from it before that.
//Also, 'target' is going to be a POD-type.
target = T();
return target;
}
int main()
{
float v... | Well.. If you do the code:
T value;
then value will get it's constructor called on it. The template honestly just looks like the constructor is just getting called twice.
Also, if T is just plain old data, then there is no lethal problem that could occur...
What exactly are you worried about occurring?
|
720,344 | 720,352 | Concatenating strings | I want to join a vector<string> into a single string, separated by spaces. For example,
sample
string
for
this
example
should become "sample string for this example".
What is the simplest way to do this?
| #include <iterator>
#include <iostream>
#include <sstream>
#include <vector>
#include <algorithm>
std::vector<std::string> v;
...
std::stringstream ss;
std::copy(v.begin(), v.end(), std::ostream_iterator<std::string>(ss, " "));
std::string result = ss.str();
if (!result.empty()) {
result.resize(result.length() - ... |
720,440 | 720,450 | Visual C++ error C2143: syntax error: missing ')' before 'constant' | I'm getting an error in Visual C++ that is giving me a really hard time.
The error is error c2143 reading: syntax error: missing ')' before 'constant'
My code line is:
coefficient[i] = (1 - (2 * depth)) + ((t - floor( t + 0.5 ) + 1 ) 2 * depth);
I have #include at the beginning of the file which should define the fl... | I'm not quite sure if this is the same error that the compiler is giving you, but you have to put a '*' sign in front of the second '2' so that this:
coefficient[i] = (1 - (2 * depth)) + ((t - floor( t + 0.5 ) + 1 ) 2 * depth);
Becomes this:
coefficient[i] = (1 - (2 * depth)) + ((t - floor( t + 0.5 ) + 1 ) * 2 * depth... |
720,507 | 720,520 | How can i estimate memory usage of std::map? | For example, I have a std::map with known sizeof(A) and sizeof(B), while map has N entries inside. How would you estimate its memory usage?
I'd say it's something like
(sizeof(A) + sizeof(B)) * N * factor
But what is the factor? Different formula maybe?
Maybe it's easier to ask for upper bound?
| The estimate would be closer to
(sizeof(A) + sizeof(B) + ELEMENT_OVERHEAD) * N + CONTAINER_OVERHEAD
There is an overhead for each element you add, and there is also a fixed overhead for maintaining the data structure used for the data structure storing the map. This is typically a binary tree, such as a Red-Black Tr... |
720,707 | 720,738 | how to return two dimensional char array c++? | i ve created two dimensional array inside a function, i want to return that array, and pass it somewhere to other function..
char *createBoard( ){
char board[16][10];
int j =0;int i = 0;
for(i=0; i<16;i++){
for( j=0;j<10;j++){
board[i][j]=(char)201;
}
}
return board;
}... | Yeah see what you are doing there is returning a pointer to a object (the array called board) which was created on the stack. The array is destroyed when it goes out of scope so the pointer is no longer pointing to any valid object (a dangling pointer).
You need to make sure that the array is allocated on the heap inst... |
720,744 | 720,783 | Class with static members vs singleton | Isn’t a class with only static members a kind of singleton design pattern? Is there any disadvantage of having such a class? A detailed explanation would help.
| This kind of class is known as a monostate - it is somewhat different from a singleton.
Why use a monostate rather than a singleton? In their original paper on the pattern, Bell & Crawford suggest three reasonns (paraphrased by me):
More natural access syntax
singleton lacks a name
easier to inherit from
I must admit... |
720,817 | 723,240 | Boost, sending files over the network using tcp, prefered method? | In the boost examples in the documentation, tcp:iostream is used to very simply send streams over the network. In other examples write() is used to write data to the socket instead with a bit more code involved.
What is the difference between those 2 methods? Pros and cons? Is there something else that should be used i... | I've never used the boost API, so reader beware... ;)
The tcp::iostream appears to allow you to interact with the socket with a stream-like interface. This approach abstracts the complexities associated with socket programming, so it would be preferable especially if you are new to socket programming. It makes a lot... |
720,838 | 720,855 | CXX Test Framework for C++ | How effective is the CXX test framework, given that you are writing unit test cases around the code that you have written. Any bug in the code might as well get translated into a bug in the unit test code as well? Isn't it something like two negatives make a positive?
Also, the time and effort spent on CXX is at least... | CXX is not very active, and writing unit test generally involves a lot of efforts. But when the first refactoring comes in, you're very grateful of the spent effort.
I've used Boost.Test & CPPUNIT. I would prefer a little bit Boost.Test, but yes, you have to write your own projects, files etc.
If you know a tool to ge... |
721,129 | 721,137 | Spot the error in this file reading code (C++) | Can anyone please tell my why this method won't compile?
void Statistics::readFromFile(string filename)
{
string line;
ifstream myfile (filename);
if (myfile.is_open())
{
while (! myfile.eof() )
{
getline (myfile,line);
cout << line << endl;
}
myfi... | ifstream myfile (filename);
should be:
ifstream myfile (filename.c_str() );
Also, your read-loop logic is wrong. It should be:
while ( getline( myfile,line ) ){
cout << line << endl;
}
The eof() function that you are using is only meaningful after you have tried to read read something.
To see why this makes a dif... |
721,357 | 721,362 | Unexpected output of std::wcout << L"élève"; in Windows Shell | While testing some functions to convert strings between wchar_t and utf8 I met the following weird result with Visual C++ express 2008
std::wcout << L"élève" << std::endl;
prints out "ÚlÞve:" which is obviously not what is expected.
This is obviously a bug. How can that be ? How am I suppose to deal with such "featu... | The C++ compiler does not support Unicode in code files. You have to replace those characters with their escaped versions instead.
Try this:
std::wcout << L"\x00E9l\x00E8ve" << std::endl;
Also, your console must support Unicode as well.
UPDATE:
It's not going to produce the desired output in your console, because the ... |
721,548 | 721,665 | cross platform game development what to look for? | I am going to start a game in about 3 weeks and I would really like the game to run at least on another platform (linux, MacOS) but my team thinks that's a lot of work. I am up for it but wanted to know what are the things I should watch out for that won't port to linux (apart from Windows specific APIs like DirectXsou... | No, the _s functions are NOT implemented in the standard gcc library.
(At least, grepping the include files for 'sprintf_s' turns up nothing at all.)
It might be worth looking at cross platform libraries like boost and apr to do some of the heavy lifting work.
A sample of specific things to look for:
Input/Output (Dir... |
721,705 | 721,901 | How do I set the opacity of a vertex in OpenGL? | The following snippet draws a gray square.
glColor3b(50, 50, 50);
glBegin(GL_QUADS);
glVertex3f(-1.0, +1.0, 0.0); // top left
glVertex3f(-1.0, -1.0, 0.0); // bottom left
glVertex3f(+1.0, -1.0, 0.0); // bottom right
glVertex3f(+1.0, +1.0, 0.0); // top right
glEnd();
In my application, behind this single square exists ... | In the init function, use these two lines:
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
And in your render function, ensure that glColor4f is used instead of glColor3f, and set the 4th argument to the level of opacity required.
glColor4f(1.0, 1.0, 1.0, 0.5);
glBegin(GL_QUADS);
glVertex3f(-1.... |
721,802 | 721,856 | What disadvantages could I have using OpenGL for GUI design in a desktop application? | There are tons of GUI libraries for C/C++, but very few of them are based on the idea that opengl is a rather multiplatform graphics library. Is there any big disadvantage on using this OpenGL for building my own minimal GUI in a portable application?
Blender is doing that, and it seems that it works well for it.
EDIT:... | Here's an oddball one that bit a large physics experiment I worked on: because an OpenGL GUI bypasses some of the usual graphics abstraction layers, it may defeat remote viewing applications.
In the particular instance I'm thinking of we wanted to allow remote shift operations over VNC. Everything worked fine except fo... |
721,810 | 721,863 | What's an OCCI context and environment? | I'm exploring a piece of software making use of Oracle API and as far as I can see often object methods expect as an argument a "OCCI context" or a "OCCI environment" values.
An example is a constructor of an Account object:
Account( oracle::occi::Environment* env );
later overloaded with
Account( void* oraCtx );
I ... | OCCI Environment lets you define your own memory management functions which OCCI will later use.
When you create an environment, you pass the pointers to your own malloc, realloc and free:
static Environment * createEnvironment(Mode mode = DEFAULT,
void *ctxp = 0,
void *(*malocfp)(void *ctxp, size_t size) = 0,
... |
721,855 | 721,891 | accumulate the sum of elements in map, using value | Say I have a
struct SMyStruct
{
int MULT;
int VAL;
};
std::map<std::string, SMyStuct*> _idToMyStructMap;
Now I want to calculate total of all SMyStuct, where total is defined as MULT1 *VAL1 + MULT2 *VAL2 for each elements in the idToMyStructMap.
Seems like accumulate function is a natural choice. Please s... | typedef std::map< std::string, SMyStruct* > string_to_struct_t;
int add_to_totals( int total, const string_to_struct_t::value_type& data )
{
return total + data.second->MULT * data.second->VAL;
}
const int total = std::accumulate(
_idToMyStructMap.begin(),
_idToM... |
721,861 | 721,996 | In case of integer overflows what is the result of (unsigned int) * (int) ? unsigned or int? | In case of integer overflows what is the result of (unsigned int) * (int) ? unsigned or int? What type does the array index operator (operator[]) take for char*: int, unsigned int or something else?
I was auditing the following function, and suddenly this question arose. The function has a vulnerability at line 17.
// ... | To answer your question: the type of an expression multiplying an int and an unsigned int will be an unsigned int in C/C++.
To answer your implied question, one decent way to deal with possible overflow in integer arithmetic is to use the "IntSafe" set of routines from Microsoft:
http://blogs.msdn.com/michael_howard/a... |
721,998 | 987,892 | Why does my colored cube not work with GL_BLEND? | My cube isn't rendering as expected when I use GL_BLEND.
glEnable(GL_CULL_FACE);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE);
I'm also having a similar problem with drawing some semi-opaque vertices in front, which could well be related.
Related: Why do my semi-opaque vertices make background objects bright... | You could try disabling all lighting before drawing the cube:
glDisable(GL_LIGHTING);
|
722,257 | 722,309 | should I take arguments to inline functions by reference or value? | Is one of these faster?
inline int ProcessByValue(int i)
{
// process i somehow
}
inline int ProcessByReference(const int& i)
{
// process i somehow
}
I know that integral types should be passed by value. However, I am concerned that the compiler might inline ProcessByValue to contain a copy. Is there a rule ... | The parameter should be typed according to what makes sense for the function.
If the function takes a primitive type, pass by value would make sense. Some people I know would complain if it were passed by const ref (as it's 'unnecessary'), but I don't think I'd complain. If the function takes a user defined type and d... |
722,268 | 722,289 | Using map containing set as a value | Basically I have,
typedef map<std::string, set<double> > MAP_STRING_TO_SET;
What is the best way to update (add or remove value) the set with a new value without causing the set to be copied?
The only viable solution I see is to use map<std::string, set<double>* > -- something I don't want to do.
Thanks
| The set is only copied in initialization.
You are allowed to do something like
myMap[myString].insert(myDouble);
since map::operator[] returns a reference.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.