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
4,402,070
4,404,020
Fork(): Dont return from child until it's terminated
I'm having some troubles with fork() and that kind of things. I'm developing a shell, where the user can write commands that whill be executed as in a normal and common shell. I have a main function like this: void Shell::init() { string command; while (1) { cout << getPrompt() << " "; command =...
You are calling wait() incorrectly. It expects to be passed a pointer-to-int, in which the child's exit status will be stored: int status; wait(&status); Really, though, you should be using waitpid() to check for the specific child that you're after. You also need to loop around if waitpid() is interrupted by a sign...
4,402,184
4,403,382
Quick way to check a range of enum values
Is there a quick/oneline way of synatx weirdness that allows you to check if an enum has a value of the ones specified? Example: enum fruit_and_vegetables { apples, pears, tomatoes, cucumbers } int main() { fruit_and_vegetables something = apples; if( something = {apples, pears} ) // <-- this h...
Ah, this can be done fairly easily... template <typename T> pair<T, fruit_and_vegetables> operator||(T t, fruit_and_vegetables v) { return make_pair(t, v); } template <typename T> bool operator==(fruit_and vegetables lhs, pair<T, fruit_and_vegetables> rhs) { return lhs == rhs.second || lhs == rhs.first; } Thi...
4,402,216
4,402,277
Sending Programmatic Mouse Events to X
I am somewhat new to X development on Linux. I'm wondering what are best practices (or links to resources) for programmatically sending cursor events. Moving the cursor to a normalized (X,Y), creating right/left mouse clicks, etc. Ideally this would be something in C/C++. I have played around with the Qt QCursor but I'...
I think you can use XSendEvent. There's some sample code here which uses XQueryPointer to populate most of the event fields. If you just want to move the pointer, use XWarpPointer.
4,402,280
4,402,317
Trouble with C#<->C++ DLLImport "Attempted to read or write protected memory."
I have a C++ dll which has a function within it I am trying to call from a C# application. Here's the code in the C++ header file extern "C" _declspec(dllexport) int LabelStoringSSDsim(int devNum, UCHAR serial[40], UCHAR wwn[40], UCHAR ConfigID[5], UCHAR FrmRev[8], UCHAR DevName[40], int eCode); Here's...
Try changing [In] to [In, Out]. I'm also not sure about using both the ref and [In, Out] keywords together on a single argument. (Edit: Hans Passant has a good explanation of the differences between the two in his comment below.) See this MSDN article for more information, especially the passage, "By default, referen...
4,402,376
4,402,457
Problem understanding this use of template for function
I have used templates for types of parameters, but I came across this thing and I'm not really sure I understand what's going on or have ever read about it. template<char *name, int iteration, bool high> void test( short step ) { if(high) iteration++; change(name,iteration); } template void test<"John", 5, ...
Nothing is going on. The template is just being declared and then explicitly instantiated. It's not being called. In fact, I doubt it compiles. I don't think if (bool) is a valid expression. Another reason it doesn't compile is that a string literal cannot be a template parameter. I really wish it could be because ...
4,402,446
4,402,478
Passing a function pointer as template parameter
For educational purposes I am trying to write my own "ForEach" function: #include <iostream> #include <string> #include <vector> // // This works // template<class Container> void ForEach_v1(const Container & inContainer, void (*Functor)(const std::string &)) { typename Container::const_iterator it = inContainer....
You want inFunctor(*it); not Functor(*it);
4,402,558
4,419,491
How to serialize and deserialize rich text in QTextEdit?
Say I have a structure like this: class AAA { BBB bb_member; double dbl_member; .................... } class BBB { int int_member; QString QStr_member; ................. QTextEdit m_textEdit; } And for AAA I define this operators: QDataStream &operator<<(Q...
I have already compleated this task. I have saved the images in a QVector. Serialized the vector and the HTML code. Then deserialized the code and the QVector. Added all the images as a resource with this function: for(int i = 0; i < vectorOfImages.size(); i++ ) { QUrl url(QString("image_%1").arg(i)); textEdit-...
4,402,786
4,402,809
Easy template implementing
Suppose I've written class template declaration somewhere in collector.h: template <class T, int maxElements> class collector { T elements[maxElements]; int activeCount; public: collector(); void process(); void draw(); }; and implementing its three methods in collector.cpp: template <class T, ...
Put the code inside the class definition in the header file. [You'll probably wind up doing this anyway as soon as you try to build code that uses this class template. See here for background esp. the neglected answer from @Pavel Minaev.]
4,402,971
4,403,091
C# scripting from C++?
Is there any C# interpreter that can be used inside C++ and yet still allow .Net access? I want to use C# scripts for games and I'm not sure how to proceed with that.
You can write a simple class in C#, let's call it ScriptRunner that would take your C# code as input, compile it at runtime to produce a new assembly in memory, then it will use Reflection to load a specific Type from this new assembly, and will run some method with an expected name. Then, use COM Interop (for example)...
4,402,980
4,404,013
Time Converter - time(NULL) to WINDOWS time
Is there a tool that converts the time(NULL) value to the WINDOWS time. The time(NULL) will give time in seconds since Jan 1, 1970. Now if i enter that value to this tool it must give me the time in date and hours, minutes and seconds. In C++ we use the time(NULL) object a lot to send time.
If by Windows time you mean the 64-bit time used in NTFS, you can use the conversion: int64 wintime = 100000000uL * time(NULL) + 0x19db1ded53e8000uLL where    int64 is the type used by your compiler for 64-bit integers. NT time is based on the origin at 1601-01-01 00:00:00 utc and counts ten million units per second—a...
4,403,007
4,403,032
Type error in a template function
Probably another dumb question that results from my studying in bad C++ book (I intend to correct this). I was playing with sstream and tried the following function: template <class num> num fromString(const std::string& str) { std::istringstream ss(str); num temp; ss >> temp; return temp; } When I call it li...
No, the compiler cannot deduce template parameters from return type alone. You have to be specific as you were originally: int i = fromString<int>("123"); One of the reasons why the compiler cannot deduce in this case is because a number of types could be convertible to int. For instance: class Gizmo { public: ope...
4,403,253
4,403,269
How to run g++ from a terminal window on my Mac
I have a simple C++ program that I can compile (g++ from command line) and run from my work-computer but not from my home-computer. I don't know how they differ! They are both macbooks and I have installed iPhone SDK on both. On my home-computer: When I add /Developer/usr/bin to my PATH I can run g++ but it cannot incl...
When you installed Xcode and the iPhone SDK, did you check the box for Unix Development Support? I had a lot of problems with this sort of thing because I didn't do that, and the solution was to uninstall the SDK and start again with the box checked.
4,403,339
4,407,875
How to fix Gstreamer to capture microphone audio and buffer or dump as raw file, when i am talking it does not save anything
I am trying to capture the microphone audio and save it as a file. But its not working, i can only play the file while assign. How can i enable the microphone and buffer it or save or dump as raw .odd/vorbis ? #include <gst/gst.h> #include <glib.h> static gboolean bus_call (GstBus *bus, GstMessage *msg,...
what's the question actually? on linux with pulseaudio it's as simple as $ gst-launch pulsesrc ! filesink location=dump.raw $ gst-launch pulsesrc ! audioconvert ! vorbisenc ! oggmux ! filesink location=dump.ogg
4,403,350
4,403,370
Memory taken up by functions
I have a Voxel class which is being created half a million times. I have reduced the amount of data I am using, but it just occurred to me that I am not sure whether functions take up memory in a similar fashion as variables. How can I find out the amount of space a function takes in my program? More importantly, when ...
Don't panic. Code for most functions (whether inline or not) only occurs once in the linked binary. Template methods occur once per instantiation, because different template parameters result in different code. In this context, instantiation means the use in your build of a class or function template with a specif...
4,403,637
4,403,854
How to use g++ compiler under the IDE of MS visual studio
How can I use g++ compiler under the IDE of MS visual studio?
Running G++ from within Visual Studio may be the wrong approach. A good alternative is to use CMake as your primary build tool. It can generate makefiles that will build your project with MinGW G++ (or Linux/Unix G++), or it can generate project/solution files for Visual Studio. Build folders are normally separate from...
4,403,726
4,403,759
Learning C++: polymorphism and slicing
Consider the following example: #include <iostream> using namespace std; class Animal { public: virtual void makeSound() {cout << "rawr" << endl;} }; class Dog : public Animal { public: virtual void makeSound() {cout << "bark" << endl;} }; int main() { Animal animal; animal.makeSound(); Dog dog;...
This is a problem called "slicing." Dog() creates a Dog object. If you were to call Dog().makeSound(), it would print "bark" as you expect it to. The problem is that you are initializing the badDog, which is an object of type Animal, with this Dog. Since the Animal can only contain an Animal and not anything derived ...
4,403,816
4,426,234
IO Completion Ports and OpenSSL
I have some legacy code that uses OpenSSL for communication. Just like any other session it does a handshake using the SSL functions and then encrypted communication over TCP. We recently changed our code to use IO completion ports. The way it works is contrary to that of OpenSSL. Basically, I'm having a hard time migr...
In order to use OpenSSL for encryption, but do your own socket IO, what you basically do is create a memory BIO, that you read and write socket data into as that becomes available, and attach that to the SSL context. Each time you do a SSL_write call, you follow up with a call to the memory BIO to see if it has data in...
4,403,872
4,403,907
How do you initialise a vector of structures that contain vectors as members?
I'm using Boost::assign to initialise a vector of structures as follows: const std::vector<spriteInfo> Resources::hudObjectInfo = boost::assign::list_of ( spriteInfo(FALSE, SCORE_START_X, SCORE_START_Y, CENTER_ALIGN )) ( spriteInfo(FALSE, SCORE_START_X+NUM_DIFF, SCORE_START_Y, CENTER_ALIGN)) ... /* and so o...
This should do : struct spriteInfo { spriteInfo(bool i, float x, float y, int align, const std::vector<int> &v): invisible(i), x1(x), y1(y), alignment(align), something(v) {} bool invisible; float x1; float y1; int alignment; std::vector<int...
4,403,923
4,404,011
c++ assignment operator implementation in templated class
I'm building my own matrix class to solidify my c++ understanding. It's templated, so I can have an int matrix or a float, or boolean matrix. I wasn't going to implement a copy constructor or assignment operator or a destructor, because I'm not going to have any dynamic member elements but if I have: Matrix<float,3,4> ...
The problem you're having is that you have three types, but you only mention two. Fundamentally, Matrix<float,3,4> mat1; Matrix<int,45,45> mat2; mat1 = mat2; Can't work, because the result of the assignment should be Matrix<float, 45, 45>, but mat1 is of type Matrix<float, 3, 4>. This cannot possibly be changed. I...
4,403,986
4,404,259
C++: Which is the best method of checking for file existence on windows platform
Possible Duplicate: How can we check if a file Exists or not using Win32 program? Which is the best method for checking for file existence: Option1: GetFileAttributes("C:\\MyFile.txt"); // from winbase.h if(0xffffffff == GetFileAttributes("C:\\MyFile.txt")) { //File not found } Option2: std::string fileName("C:...
Note that GetFileAttributes() may fail for other reasons than lack of existence (for example permissions issues). I would add a check on the error code for robustness: GetFileAttributes("C:\\MyFile.txt"); // from winbase.h if(INVALID_FILE_ATTRIBUTES == GetFileAttributes("C:\\MyFile.txt") && GetLastError()==ERROR_FILE_N...
4,404,012
4,404,106
RTTI in a function exported from a DLL
I have a Visual Studio 2008 C++ dll where I would like to accept a variable number of arguments and know the type of each one. For example: __declspec( dllexport ) void Foo( const char* object, const char* function, ... ) { printf( "%s::%s( ", object, function ); va_list list; va_start( list, function );...
A variadic argument solution is possible, but not the C way and not in the current version of the language. If your compiler implements variadic templates though, you could do it with them. You can mimic variadic templates with current version up to some arbitrary maximum (set by a variable if you use preprocessor ma...
4,404,138
4,404,173
operator overloading + sign, for class members
I have an issue, i need to add two class members using a operator overload. issue also is that the members i need to add are strings.. i tried using stringstream but i didnt seem to work, an infinite loop of errors occur. is there a very easy way to turn a string into a integer to add? or at least a way to add two stri...
Your operator+ does not take any parameters and therefore cannot work. A member operator+ has to have the following signature: class X { X operator+(const X &b); }; A free operator+ needs to look that way: X operator+(const X &a, const X &b); Well, that is one way to go. I suggest you get back to the books ;)
4,404,170
4,404,299
Is this use of global static initialization okay for a "busybox" style application?
Still working on my closed/open source hybrid talked about earlier in this question. The application in question is actually a busybox like application -- there are several programs bundled into a single program, and the actual program run is chosen based upon the first command entered. This allows the sub-programs to ...
I could come up with some clever programs with recursive template instantiation, but the reality is that what you've done is probably simpler than what I can come up with. It's rare that I suggest that global state is a smart idea, but on this one I may have to accept that I can't do better.
4,404,386
4,411,686
How do you extract bytes from a file into simple data types?
I've tried everything I can think of and can't get anything to work. I have a binary file I've written in VB.Net which basically consists of an integer, (in binary of course) that tells me the array size for the following data, then the floats as binary data. The file writes just fine from VB.Net, and I can read it bac...
OK, something really strange is going on with my data. I just looked at the raw byte values in both Visual c++ and objective-c, and they don't agree at all. I'm only reading the first four bytes of the file and looking at their values. I'm assuming at this point that I'm not reading them in correctly, but I don't know ...
4,404,387
4,404,657
Is C++ STL thread-safe for distinct containers (using STLport implementation)?
I'm using Android 2.2, which comes with a version of STLport. For some reason, it was configured to be non-thread safe. This was done using a #define _NOTHREADS in a configuration header file. When I constructed and initialized distinct non-shared containers (e.g. strings) from different pthreads, I was getting memor...
The SGI STL The SGI STL is the grandmother of all of the other STL implementations. See the SGI STL docs. The SGI implementation of STL is thread-safe only in the sense that simultaneous accesses to distinct containers are safe, and simultaneous read accesses to to shared containers are safe. If multiple thr...
4,404,431
4,434,398
How to store enum in SQLite database
I'm trying to store enum in SQLite database using QSql. I have following class: partydao.h: class PartyDao : public QObject { public: enum partyType { typeCompany, typePerson }; private: Q_OBJECT Q_ENUMS(partyType) Q_PROPERTY(partyType type READ type WRITE set_type) // other declarations }; Q_DECLARE_META...
I didn't find any way to use auto conversion of QVariants of user type. Therefore I've created singleton storing rules for conversion. struct DbConverter { virtual ~DbConverter() {} virtual QVariant toDbValue(const QVariant &value) = 0; virtual QVariant fromDbValue(const QVariant &value) = 0; }; class DbConver...
4,404,433
4,404,477
Where do you like to split long lines?
For manually wrapping long lines, what is your personal heuristic for choosing places to break a line? Assuming this line is too long, where might you break it and it what order of precedence? double var = GetContext()->CalculateValue(element, 10.0); Most people agree about separating parameters per line: double var ...
I like to make the splits in strength of binding order, closest to the end of the line first. So in your examples I would split at the = sign. If this still spilled over the margin I would split at the -> The idea of splitting a line is solely for the benefit of readers (since the compile could care less). I find that...
4,404,608
4,404,621
Vector of Type to Array of Type::Member?
I have a type like this: class Foo { public: int bar[3]; /*Possibly some other members in here*/ }; What is an effective way to get a std:vector<Foo> to an array of int? The array should be a sequential mapping of bar the the Foos of the vector. Is this enough? int* array = new int[foos.size() * 3]; int offset...
std::vector<int> ivect; std::transform(foovect.begin(), foovect.end(), std::back_inserter(ivect), [](Foo const& f) -> int { return f.bar; }); If you lack lambda support of course you'll have to make a functor to do the same thing. Boost.Bind would be a great place to start on that end. ^^^ Didn't understand the que...
4,404,705
4,406,575
Unexpected Non-NULL return
I am playing with TagLib (on Windows, built with MingW). I am trying to get TagLib to recognize when there is no ID3v1 or ID3v2 information in an MP3 file. According to the TagLib documentation, the ID3v2Tag() function in an MPEG File object should return a NULL pointer when there is no ID3v2 information in the file. U...
I examined TagLib's code briefly. I know nothing about it and never used it, but the code looks buggy to me. Here's why - In MPEG::File::read(), we are looking for a tag - d->ID3v2Location = findID3v2();. If it doesn't exist, it isn't added to the tags vector. This is the check - if(d->ID3v2Location >= 0). However, at ...
4,404,722
4,404,767
Problem with C++ program output
Example: Let’s say your user input is 6. Then the number of sequences that sum up to 6 is 11 (including 6 itself). This is shown clearly below: 6 5+1 4+1+1 3+1+1+1 2+1+1+1+1 1+1+1+1+1+1 2+2+1+1 3+2+1 4+2 2+2+2 3+3 You SHOULD NOT have any sequences that repeat. You cannot have 2+2+1+1 and 1+1+2+2 as two different com...
I guess it would be easier if you'd sum so that the first summand is always highest possible and you don't allow that of two adjacent summands the second one is greater than the first one. Just a thought...
4,404,725
4,404,753
Why do some includes need the .h and others not?
Why is map imported as #include <map>, but stdio imported as #include <stdio.h>?
All standard C++ headers don't want the .h in the end. I read somewhere that the concept is that they don't need to be actual files, even if I never saw an implementation do it in another manner edit: actually the compiler intrinsics should work considering the headers included but not actually including them as files;...
4,404,760
4,407,637
Processing files larger than 2 GB in C++ with STL
I am doing binary file processing and in my algorithm I would like to know the actual type of pos_type and off_type, for example when computing the size of the file or seeking to a given position (tellg and seekg). When computing the size of the file I just static_cast the pos_type to an int64_t and it seems to work fi...
Not all compilers have STL implementations with large file support. For example, the following program: #include <fstream> #include <iostream> #include <limits> int main() { using namespace std; cout << numeric_limits<streamoff>::max() << endl; } results in: VS2005 - 2147483647 VS2008 - 2147483647 VS2010 - ...
4,404,777
5,337,526
What is the correct way to access DLL functions in a SDI app?
I have a simple SDI app which works pretty well. Lately I decided to make use some of functions, exported by a DLL. All those DLL functions work with a static memory buffer (which the app must define and use in the function calls) . Fact is, some DLL functions should be called when specific things happen in the View. I...
Define "correct" :) First of all, I think you will be better off if you wrap all the calls to the DLL and put them in one place. Then it doesn't really matter which one calls the DLL (interface wise that is). However, it's good practice to let only one part of the system know about the DLL and use that interface. In th...
4,404,955
4,404,990
What does "new" use when a runtime library is not used?
In C for example, there is no malloc() without a runtime library (libc). And I think for example, on Windows malloc just calls HeapAlloc(). But in C++, the way to allocate dynamic memory is actually a keyword of the language; same for "delete". So therefore, how would "new" work if you compiled your code without a runt...
If new operator is not overloaded, it is generally the same as malloc function. It is platform dependent. The only difference, is that it automatically manage the initialization of the data. EDIT: On linux you can not compile without standard library. You got the following message: phong@colinux ~ $ g++ -nostdlib test....
4,404,978
4,405,038
Why my virtual method is not overridden?
class Base { public: Base() { cout<<"base class"<<endl; fun(); } virtual void fun(){cout<<"fun of base"<<endl;} }; class Derive:public Base { public: Derive() { cout<<"derive class"<<endl; fun(); } void fun(){ cout<<"fun of derive"<<endl;} }; void main() { Derive d; } The output is: base class fun of base derive cla...
When you call fun() in the base class constructor, the derived class has not yet been constructed (in C++, classes a constructed parent first) so the system doesn't have an instance of Derived yet and consequently no entry in the virtual function table for Derived::fun(). This is the reason why calls to virtual functio...
4,405,074
4,405,343
Differences between the C++ and the Java object model
In Java it is very easy to serialize objects. In C++ it is only safe(?) to memcpy objects as long as they are like C structs (no polymorpism). In C++, if the compiler is able to generate the default (trivial) copy constructor then why can't it generate code for automatic serialization? In Java, only static functions a...
In Java it is very easy to serialize objects. In C++ it is only safe(?) to memcpy objects as long as they are like C structs (no polymorpism). Java is an interpreted language (or more recently, as Billy comments, JIT compiled), so it has no choice but to carry around metadata baggage of every data type in the program...
4,405,243
4,424,070
Creating and Using a Simple .dylib
What's the most basic way to create and use a .dylib in Xcode? Here's what I have so far: File: MyLib.h #include <string> namespace MyLib { void SayHello(std::string Name); } File: MyLib.cpp #include <string> #include <iostream> #include "MyLib.h" void MyLib::SayHello(std::string Name) { std::cout << "Hello...
You don't include the library file, but the header (.h) So write #include "MyLib.h" You then have to tell the compiler for your program to link against the dylib file. If you are using Xcode you can simply drag the dylib file into your project.
4,405,340
4,405,359
Method to return pointer, pointing to array object declared in another header,
I'm getting a little stuck with two entwined problems. First, I want to have an array of pointers to objects on the heap. (objects that are declared in another header) Second, then I want to have a method return a pointer to one of those objects. My current code is the result of a bit of fumbling, and will fail becau...
Other than a few typos, this compiles fine: You need a semi-colon after defining the bar class. bar * foo:getBar(int y) should be: bar * foo::getBar(int y) 3. bar[i] = NULL; //set all pointers to NULL should be: barArray[i] = NULL; //set all pointers to NULL
4,405,488
4,405,648
C++ Inheritance Problem leads to segmentation fault
Here is some sample code to illustrate the problem I am having. #include <iostream> using namespace std; class Foo { public: Foo(int x) { m_x = x; } int getX() { return m_x; } private: int m_x; }; class Bar : public Foo { public: Bar(int x) : Foo(x) ...
My guess, from your edit, is that m_engine is a dangling pointer. That is, the memory pointed to by m_engine has been deleted. You still have the address where the memory was allocated stored in m_engine, but when you try to access that address in memory expecting a valid Foo, Bar, etc. object to be there, that portio...
4,405,630
4,405,644
initialize vector of pairs
I wanted to initialize a vector of pairs with something like this std::vector< std::pair<bool, bool> > myvector(initSequence.size(), X ); what shall I substitute in place of X, if I want to initialize every pair with (false, false)? Thank you
std::pair<bool,bool>(false, false) or std::make_pair(false, false)
4,405,634
4,405,688
Learning C++: returning references AND getting around slicing
I'm having a devil of a time understanding references. Consider the following code: class Animal { public: virtual void makeSound() {cout << "rawr" << endl;} }; class Dog : public Animal { public: virtual void makeSound() {cout << "bark" << endl;} }; Animal* pFunc() { return new Dog(); } Animal& rFunc()...
1) If you're creating new objects, you never want to return a reference (see your own comment on #3.) You can return a pointer (possibly wrapped by std::shared_ptr or std::auto_ptr). (You could also return by copy, but this is incompatible with using the new operator; it's also slightly incompatible with polymorphism.)...
4,405,721
4,405,911
C /C++ Lock-free (or nonblocking) Ring Buffer that OVERWRITES oldest data?
I'm trying to find a way to make a Lock Free OR Non-blocking way to make a Ring Buffer for single consumer / single consumer that will over-write the oldest data int the buffer. I've read a lot of lock-free algorithms that work when you "return false" if the buffer is full--ie, don't add; but I can't find even pseudo-c...
Start with a single producer/multiple consumer queue with appropriate progress guarantees. If the queue is full and the push would fail, pop one value. Then there will be space to push the new value.
4,405,806
4,405,823
find conditions about vectors of pairs
suppose I have a std::vector of pair. How can I use, efficiently, method std::find to see whether at least one element of the vector is not equal to (false, false)? Thanks
std::pair overloads operator==, so you can use std::find for the affirmative: bool b = std::find(v.begin(), v.end(), std::make_pair(false, false)) == v.end(); and you can use std::find_if for the negative: bool b = std::find_if(v.begin(), v.end(), std::bind2nd(std::not_equal_to<std::pair<bool, b...
4,405,872
4,406,016
Error: "Application has failed to start because its side-by-side configuration is incorrect"
I have created an MFC application using Visual Studio 2008 which is working fine on Windows XP. But when I try to execute the same EXE file in Windows Vista I am getting: Error: Application has failed to start because its side-by-side configuration is incorrect When I check the event viewer then below is what it says...
You have no CRT runtime DLL on the target machine. To avoid this you can install VC9 redistributables or you can link your program with the runtime statically (more info). This question could be helpful also.
4,405,887
4,405,905
When the C++ standard provides C headers bringing names into the global namespace, does that include overloads?
The final committee draft of the upcoming C++0x standard says: Every C header, each of which has a name of the form name.h, behaves as if each name placed in the standard library namespace by the corresponding cname header is placed within the global namespace scope. It is unspecified whether these names ...
Yes, all overloads should be brought into the global namespace. My understanding is that the math.h header is intended to look something like: // math.h: #include <cmath> using std::abs; // etc. So, yes: the behavior of your example program is different when compiled as a C program than when compiled as a C++ progr...
4,405,997
4,900,900
Display Lists and OpenGL states
This is strange. When I render my mesh, the fps is a stable 130 or so. When I put it into a display list, the fps DROPS to little more than 15. When I take out the few material and texturing commands, it goes back up to 130. Why is this? Why are the OpenGL state changing commands so pressing on FPS? I think I read some...
The most common mistake is putting the display list creation into the render loop. Make sure you are creating the display list somewhere during initialization and only rendering it in the render loop. Aside from that, you will just have to post a code sample for us to look at.
4,406,037
4,406,057
Why object file size changes for the same code in C and C++
I have written same lines of code in both C and C++ build environment of visual studio 2008 but C code's object file size is 5.5kb and C++ code file size is 6.17 kb. Why is this difference? Following is the code in both environments: #include <stdio.h> struct S { char c; }; void func() { int i; int j; ...
It links different C runtime libraries in each case. Check here for detailed explanation. For instance, libcmt.lib vs libcpmt.lib.
4,406,217
4,406,623
Ajax Push written in C/C++?
I have existing chat server code written in C/C++ that communicates over TCP/IP with client installed GUI. I'd like to also allow "web" access to this functionality, where users can simply go to my website, have it display a nice basic HTML5 driven GUI, and have them interact with my chat server code and other users. ...
I may have misunderstood your question, but this sounds like what you're looking for: http://www.webtoolkit.eu/wt
4,406,414
4,406,707
Problem with a recursive partition (number theory) function
Example: Let’s say your user input is 6. Then the number of sequences that sum up to 6 is 11 (including 6 itself). The problem I am having is that it works when the user enters 1 or 6, but if not it is way off and I can't figure out why. I can give more info on the subject if needed. #include <iostream> using namespa...
I read wiki article you pointed out, they give some instructions how to build recursive defined function. It looks different then your code. The code below works for me #include <iostream> using namespace std; int sum(int k, int n) { if(k == 1 || n == 1) return 1; if(k < n) return sum (k, k);...
4,406,415
4,406,424
How to change default arguments in c++
I know there an answer in following page,but i can't open it in my country... so, someone kind enough to copy and paste it here. Thanks in advance http://cpptruths.blogspot.com/2005/07/changing-c-function-default-arguments.html
Copy of http://cpptruths.blogspot.com/2005/07/changing-c-function-default-arguments.html In C++, default arguments of global scope functions can be changed easily. Typically we use a constant expression as a default argument. C++ supports static variables as well as a constant expression for a default argument. We can ...
4,406,839
4,407,041
What's new for C++ and STL in VS2010 SP1?
Just saw that VS2010 SP1 Beta is released. But the release notes are a bit lacking in details. Anyone know what kind of changes have been made to C++ and the STL? I can't install it so I would appreciate if someone would like to share.
There is written that there is nothing new in language and library, only bugfixes.
4,406,895
4,487,981
What std::locale names are available on common windows compilers?
The standard is pretty much silent on what constitutes a valid locale name; only that passing an invalid locale name results in std::runtime_error. What locale names are usable on common windows compilers such as MSVC, MinGW, and ICC?
I believe the information you need is here : locale "lang[_country_region[.code_page]]" | ".code_page" | "" | NULL This page provides links to : Language Strings Country/Region String Code Pages Although my answers covers setlocale instead of std::locale, this MSDN page seems to...
4,406,981
4,407,979
Open Source Qt projects deal with database connections
I have a Qt application which heavily uses MySql Database. Do you know any open source Qt project which uses MySql? I wonder how did they manage database connections? Comment to Harald Scheirich's Answer: 1-)QSqlDatabase::isOpen() doesn't work properly. http://bugreports.qt-project.org/browse/QTBUG-223 2-)Using QSqlD...
Use Google codesearch to search for QMYSQL.
4,407,181
4,415,966
Replacing legacy DirectDraw code
Yesterday I found source codes for my Tetris game developed many years ago in C++, Win32 API and DirectDraw 7. I tryed to build solution without any success because most recent DirectX SDK (June 2010) does not include DDraw.h and DDraw.lib any more. Is there any recommended approach (hopefully with examples) to upgrade...
If you use DirectDraw blit functionality then it will be quite a task to port it. In my opinion your best option is to port it to GDI. It may mean writing your own blit functions however. Failing that you could port to D3D though this will be quite a task and is really dependent on how you do your rendering. If all ...
4,407,229
5,521,444
Using new Windows features with fallback
I've been using dynamic libraries and GetProcAddress stuff for quite some time, but it always seems tedious, intellisense hostile, and ugly way to do things. Does anyone know a clean way to import new features while staying compatible with older OSes. Say I want to use a XML library which is a part of Vista. I call Loa...
Delay loading is the best way to avoid using LoadLibrary() and GetProcAddress() directly. Regarding the security issues mentioned, about the only thing you can do about that is use the delay load hooks to make sure (and optionally force) the desired DLL is being loaded during the dliNotePreLoadLibrary notification usi...
4,407,241
4,407,304
Is there a need to free memory in unmanaged code when it is loaded by managed code
There are 2 binaries. One is native/unmanaged C++ dll and other is managed c# exe. Now what I am doing is writing a function in c++ dll and allocated memory inside it using malloc. I exported this function to be used by my c# module. In C++ I did: char* FunctionHavingAllocatedMemory(int i){ char* p = (char*)malloc(100...
The garbage collector only works on the managed heap : the memory allocated in FunctionHavingAllocatedMemory is your responsibility to free.
4,407,493
4,417,073
Is there a robust C++ implementation of the Bentley-Ottmann algorithm?
The Bentley-Ottoman algorithm finds all crossings in a set of line segments. For a well known and important algorithm, it seems quite weird that a C++ implementation of Bentley-Ottmann algorithm — the implementation that can handle all the degenerated cases (i.e., no special assumption on the sweeping line and the numb...
CGAL has something in there with the same complexity as Bentley-Ottmann, O((n + k)*log(n)) where n is the number of segments and k is the number of intersections (not sure which algorithm they used): //! \file examples/Arrangement_on_surface_2/sweep_line.cpp // Computing intersection points among curves using the sweep...
4,407,500
4,407,629
Help me debug this - C++ Boost
I am noob to C++ Boost. Can anyone here help me to debug this program. #include <iostream> #include <boost/filesystem/operations.hpp> #include <boost/filesystem/fstream.hpp> using namespace boost::filesystem; using namespace std; void show_files( const path & directory, bool recurse_into_subdirs = true ) { if( exis...
There are two changes you need to make to get this working properly. First of all, the iterator returns an instance of basic_directory_entry, not a path. So first you need to query the path from the iterator. Also, newer versions of boost have dropped the native_ prefix from the accessor methods. Here's your code wi...
4,407,678
4,408,014
how to create variable shortcut
Suppose I need to create complex math formula, for example double f(double array1[100], double array2[100]) { double z = array1[21] * array2[3] + array[10]; double q = array1[21] * array1[30] / array1[10]; return array1[1] * z * q; } or more complex. My solution is to create intermediate variables like: do...
gcc-llvm with standard optimization: Results are identical ignoring instruction reordering define double @_Z1fPdS_(double* nocapture %array1, double* nocapture %array2) nounwind readonly { entry: %0 = getelementptr inbounds double* %array1, i64 21 ; <double*> [#uses=1] %1 = load double* %0, align 8 ...
4,407,767
4,407,842
Passing arguments by reference and address
Possible Duplicate: How to pass objects to functions in C++? When should I be passing arguments by reference and when passed by address? I mean Except the case of pass by const reference, is there any difference between the two.
I personally pass by pointer (address) when the pointer may be null, and pass by reference when it can't be null. There are plenty of other considerations (const/non-const, smart/weak pointers etc) but I think this is a good guideline and answers your question well.
4,407,960
4,408,426
Implicit casting for method handler?
Some code typedef void (*EventHandler) (EventObject* sender, EventArgs* args, void* closure); class Control { void AddHandler(int eventId, EventHandler handler, void* data) } class SubControl { static void mousemove_cb(EventObject* sender, MouseEventArgs* calldata, void* closure); } The error error C2664: 'Control::...
C++ template could solve this problem. Use this: struct Control { //Note this change! template<typename TEventHandler> void AddHandler(int eventId, TEventHandler handler, void* data); }; struct SubControl { static void mousemove_cb(EventObject* sender, MouseEventArgs* calldata, void* closure); SubC...
4,407,985
4,408,182
Why can I not convert a reverse iterator to a forward iterator?
Well, I know why, it's because there isn't a conversion, but why isn't there a conversion? Why can forward iterators be turned to reverse iterators but not the other way round? And more importantly, what can I do if I want to do this? Is there some adapter that allows you to iterate backwards using a forward iterator? ...
You could write a helper function. One particularity of reverse_iterator is that base() gives a forward iterator that is next from the value that the reverse iterator dereferences to. This is because a reverse iterator physically points to the element after the one it logically points to. So to have the forward iterat...
4,408,494
4,440,866
How to get list of files in use when installing MSI file with ExternalUI
I am writing program witch runs msi installations silent on background. Using MsiSetExternalUI and MsiSetInternalUI with INSTALLUILEVEL_NONE I can show my progress dialog and catch errors during install: INT CALLBACK ProgressHandler(LPVOID pvContext, UINT uiMessageType, LPCTSTR szMessage) { INSTALLMESSAGE iMessage ...
This thread in the wix-users mailing list suggests using MsiSetExternalUIRecord instead of MsiSetExternalUI allows you to retrieve the file names in the fields of the record (corresponding to [1], [2], and so forth). Just watch out for empty ones in the middle. This suggests that these values should be available in sz...
4,408,521
4,408,804
How will increasing each memory allocation size by a fixed number of bytes affect heap fragmentation?
I have operator new() replaced in my C++ program so that it allocates a slightly bigger block to store extra data. So the program performs exactly the same set of allocations except that now it requests several bytes more memory in each allocation. Otherwise its behavior is completely the same and it processes exactly ...
Unless your program uses some "edge" block sizes (say, near to a power of two), I don't see that block size (or a small difference in block size compared to the program with standard allocation) may affect fragmentation. With millions of allocation, a good allocator fills up the space and manages it efficiently. Think...
4,408,544
4,408,672
Using the composite design pattern to operate on objects of different type, is there a way to prevent an object from being operated on more than once?
I'd like to use the Composite design pattern in C++ to be able to create and operate on groups of objects. A problem I've encountered is that since leaves and composites are treated the same, and composites can be comprised of leaves and composites, it is quite possible for an object to be operated on more than once wh...
I don't know what you mean by idiomatic, but a solution would depend on how yo traverse the structure of composites. Here are some options if you use a visitor and remember the already visited components, ignore duplicates use a tick count and have the composite element ignore successive calls with the same tick count...
4,408,546
4,408,770
Dealing with sections of INI files with Boost.Program_options
I am trying to parse configuration INI files in Linux. I would like to use Boost and someone pointed me the program options library. The thing is that I can read lines having the syntax field=value, but how to deal with different sections i.e. lines having [Section_Name] in it? With the code below I have always an e...
As stated earlier by etarion, the identifier of the option must be prefixed by their enclosing section. Here is a simple modification on your code to demonstrate : int main() { std::stringstream s( "[Test]\n" "a = 1\n" "b = 2\n" "c = test option\n"); std::set<std::string> option...
4,408,710
4,413,450
Beginner CUDA - Simple var increment not working
I am working on a project with CUDA. To get the hang of it, I have the following code. #include <iostream> using namespace std; __global__ void inc(int *foo) { ++(*foo); } int main() { int count = 0, *cuda_count; cudaMalloc((void**)&cuda_count, sizeof(int)); cudaMemcpy(cuda_count, &count, sizeof(int), cudaMe...
I found the solution. I just had to use an atomic function, i.e a function that is executed without interference from other threads. In other words, no other thread can access a specific address until the operation is complete. Code: #include <iostream> using namespace std; __global__ void inc(int *foo) { atomicA...
4,408,901
4,408,923
When do I stop reading from a file?
Does some_file.good() return false after reading the last entry from the file, or after attempting to read beyond that? That is, should I write while (input.good()) { getline(input, line); // ...process } or getline(input, line); while (input.good()) { // ...process getline(input, line); } ?
Attempting to read beyond that... You could try: while(getline(input, line)) { // do stuff with line } Should add, that stream implements operator!, which checks the flags that you normally would. The return from getline is the input stream, but because of the operator, the flags are checked.
4,409,042
4,409,117
how to create self-extracting_archive ( programmatically )
So, how to do it? How to pack files to self-extracting_archive. What is algorithm?
You can create self-extracting archives for windows with 7-zip, if you want to create them programmatically you can use the SDK.
4,409,372
5,215,891
Copy a pointer to a static array
I'm developing an Android application with some native code (used to render with OpenGL ES 2.0). I have the following method signature: JNIEXPORT void JNICALL Java_com_xxxxxx_xxxx_ActivityRenderer_renderFrame (JNIEnv *env, jobject obj, jfloatArray vertices, jfloatArray normals, jfloatArray texCoor...
Let me know if I'm misinterpreting what you're asking, but it sounds like you need to brush up on your C++. Static arrays in C++ have a fixed size at compile-time. You probably want to look into using new[], or malloc() to achieve what you want.
4,409,442
4,410,102
Will C++0x RValue references or other features will have an impact on streams performance?
Lot of profiling shows that C++ streams are not the best way to performe file or text string manipulation when performance (speed) is required. Still, the standard streams are a good way to keep things type-safe. From what I've read, most of the problem is because streams implementations have to 1) create/copy a lot of...
You might be interested in some of the performance comparisons in my question here. Even the lowest level functions in the C++ standard library streams API are incredibly slow under common implementations, and looking through the source code of e.g. Visual C++'s stringbuf class, I don't see copying of small temporary ...
4,409,446
4,409,476
reading until user enters blank line
Suppose I want to read lines from the console and put those into a container until the user enters a blank line. I do not want that blank line ending up in my container, though. I can think of five different solutions: a) break from loop std::vector<std::string> container; for (; ;) { std::string line = get_input()...
I prefer (a). simple and reads quite naturally. (b) repeats the line that gets the input. (c) and (d) both use syntax that may be confusing to beginners (specifically, the comma not within a for statement or a definition, and assignment within a conditional). I'd probably prefer (c) over (d) though. (e) is... inefficie...
4,409,888
4,409,939
Benefits of splitting interface and implementation in C++
I'm using C++ and I'm considering putting my function implementation into .h. I know that .h file is for definitions and .cpp is for implementations but how splitting all files into headers and sources will benefit me. Well if my aim would be to create static or dynamic library than of course that would make a differen...
The obvious goal is to reduce coupling : as soon as you change a header file, anything that includes it must be recompiled. This can rapidly have a strong impact on compilation times (even in a small project).
4,409,928
4,413,166
Getting Chrono C++ library (Boost::sandbox) to work
i wanted to try out Chrono from the Boost sandbox. It seems to support a lot of stuff and should be stable. I have Boost in version 1.44 installed on my system (incl. boost_system lib which is needed) and took the sandbox version (the download-version is older and misses for example the ratio.hpp file). But it isn't co...
As described in the Installing Chrono documentation, you either need to build and link the Chrono library, or define BOOST_CHRONO_INLINED. I had problems building Chrono from the trunk checkout, but it's probably related to the type_traits incompatibility mentioned in the Chrono docs. I was able to build the example p...
4,410,079
4,410,332
C++ Vector, push_back from another thread crashing?
I have unexpected assertions faillures in my code using a checked STL implentation. After some research, I narrowed down the problem to a push_back in a vector called from a different thread than the one in which the vector was created. The simplest code to reproduce this problem is : class SomeClass { privat...
If you can guarantee that nobody is writing to or reading from the vector when you call push_back, there's no reason that it should fail. You could be dealing with higher-level memory corruption. You should verify that "this" points to a genuine instance of SomeClass, check it's other members, etc.
4,410,098
4,410,226
Problems with Eigen library and c++ linker
I try to link my c++ application against the "Eigen 2.0.15" library. Some details: My compiler is: gcc version 4.0.1 (Apple Inc. build 5493) My OS is: mac os 10.5 I compile the code with g++ -I/opt/local/include -I/opt/local/include/eigen2 -O2 -g ... Building target: LBRALL Invoking: MacOS X C++ Linker g++ -L/opt/loc...
Looking at the error messages, my guess you didn't instantiate Matrix, Transform and possibly other templates. That happened probably because the header files didn't contain implementation of those templates, or maybe there is a conditional compilation that is supposed to pull up implementation for them.
4,410,114
4,410,256
Using Boost::Xpressive to match a single character
I have a string that can be "/" "+" "." or a descriptive name I'm trying to figure out how to use regex to check if the string matches any of the 3 special characters above (/ + or .) After doing a bit of reading i decided boost::xpressive was the way to go but i still cannot figure it out. is Boost:xpressive suitable ...
Why not just use std::string::find_first_of() to do your own solution? Sounds like a lot of machinery for a fairly simple task. Edit Try this out if you're still stuck. #include <iostream> #include <boost/xpressive/xpressive.hpp> using namespace std; using namespace boost::xpressive; int main() { sregex re = sr...
4,410,142
4,672,075
Building large application on Solaris is hanging without any information
I am trying to compile a rather big application on Solaris. Compiling it on AIX caused a problem that the command line buffer was too small (ARG_MAX). On Solaris it compiles most of application successfullym but then it just hangs and without any error hangs an do nothing for at least an hour. I am running it on SunOS ...
Just for those who encounter this in future. The problem was optimization flag causes it to take a REALLY long time to compile. I am talking 1+ hour for one cpp file. This is big project. In addition there was an issue with Sys Admin on SUN box not giving me enough CPU share. Increasing that solved this problem, well ...
4,410,309
4,410,359
rs-232 serial connection through ethernet cable (tcp)
I have hardware device that is controlled through an rs-232 interface (Its an ultrasound pulser-receiver). I need to write a program to send the commands to the device from my computer. Unusually, however, the device does not have a serial port (DB-9 COM port) but rather has a RJ45 receptacle (an ethernet socket). T...
Actually it doesn't work physically. It just works mechanically. The physical electrical voltages and currents used by ethernet is very different from that used by serial ports. Not only that, the pinouts are also incompatible. Lucky for you ethernet uses magnetically coupled signals otherwise you would have fried eith...
4,410,532
4,460,545
Removing C++ Comment From Source Code
I have some c++ code with /* */ and // style comments. I want to have a way to remove them all automatically. Apparently, using an editor (e.g. ultraedit) with some regexp searching for /*, */ and // should do the job. But, on a closer look, a complete solution isn't that simple because the sequences /* or // may not...
May someone vote up my own answer to my own question. Thanks to Martin York's idea, I found that in Visual Studio, the solution looks very simple (subject to further testing). Just rename ALL preprocessor directives to something else, (something that is not valid c++ syntax is ok) and use the cl.exe with /P cl target....
4,410,629
4,410,669
Finding a Specific Digit of a Number
I'm trying to find the nth digit of an integer of an arbitrary length. I was going to convert the integer to a string and use the character at index n... char Digit = itoa(Number).at(n); ...But then I realized the itoa function isn't standard. Is there any other way to do this?
(number/intPower(10, n))%10 just define the function intPower.
4,410,790
4,411,372
C++: Creating a shared object rather than a shared pointer to an object
boost::shared_ptr really bothers me. Certainly, I understand the utility of such a thing, but I wish that I could use the shared_ptr<A> as an A*. Consider the following code class A { public: A() {} A(int x) {mX = x;} virtual void setX(int x) {mX = x;} virtual int getX() const {return mX;} private: ...
The whole point of shared_ptr is that it (and its copies) own the object that it points to. If you want to give an A to a container that manages its lifetime then you shouldn't be using a shared_ptr at all as it doesn't meet your needs; HelpfulContainer only knows how to be the sole owner of a dynamically created objec...
4,410,809
4,410,824
Stack memory allocation
It is being said that local variable will be allocated and deallocated automatically when function ends in C/C++. According to my understanding, when having been deallocated, the value held by local variable also be destroyed!!! Please correct me if i'm wrong Consider following code: void doSomething(int** num) { int...
You are correct. your cout may or may NOT print 10. It will invoke undefined behavior. To make a bit more of a note, try running the following code under your compiler with no optimizations enabled. #include <iostream> using namespace std; void doSomething(int** num) { int a = 10; *num = &a; } void doSomethi...
4,410,829
4,411,193
How can I launch programmatically (C++) an application from a Windows shortcut (.lnk file)?
how can I launch programmatically an application from a Windows shortcut (.lnk file)? I tried to use the API ShellExecute and it seems to work. Any caveat? Thank you. Here it is a snippet of my current code: #include <windows.h> #include <map> #include <string> #include <iostream> int main( int, char** ) { std::ma...
I am not sure what you are uncertain about, the behaviour you observe is documented. The ShellExecute "open" operation, will do whatever the shell does when you "open" the file referenced by the file argument (you can right-click a shortcut and select "Open" explicitly, but that is also the default operation for .lnk,...
4,410,841
4,410,884
Using template metaprogramming to wrap C-style variadic arguments
I have a Visual Studio 2008 C++ DLL that exports a function that accepts a variadic parameter like this: __declspec( dllexport ) void DLL_Foo( int count, ... ) { va_list list; va_start( list, count ); for( ; count; --count ) { const wchar_t* item = va_arg( list, const wchar_t* ); if( co...
This is only possible using C++0x features. If you cannot use its variadic templates, you cannot create a function … uh, that takes a variable number of templates. On the other hand, you can create multiple overloads of the same method, each with its own number of arguments (1 … some upper limit). That’s of course quit...
4,410,876
4,410,984
C++ - Array pointer as function parameter, filling out array and accessing it from UI thread
I haven't coded much in C++ since HS and I'm pretty rusty / not very experienced. I want to find all the running processes on a machine and fill a listbox control with their names. I created a C++ win form application, and on the form load event handler I have the following code - private: System::Void Form1_Load(Syst...
Strings and vectors are your friend in C++ :) #include <string> #include <vector> typedef std::vector<std::string> StringVector; StringVector ProcessMonitor::GetProcesses() { StringVector ret; // Array to hold process ID's DWORD aProcesses[1024], cbNeeded, cProcesses; // Iterator unsigned int i; // If no running pr...
4,411,225
4,411,259
How to copy values from one pointer to another
I have the following pointer: jfloat *verticesLocal; And I want make a new copy to: jfloat *vertices; I want to copy the values from verticesLocal to vertices. How can I do that? I've just tried the following command, but it doesn't work: memcpy(vertices, verticesLocal, numVerticesLocal * sizeof(jfloat)); I can't se...
malloc first, then do your memcpy.
4,411,320
4,411,563
C++: Creating a templated Shared<T> object rather than a shared_ptr<T> object
Per my previous question, I wish that a boost::shared_ptr<A> was actually a subclass of A (or perhaps A*) so that it could be used in methods that took A* as their argument. Consider the following class: class A { public: A(int x) {mX = x;} virtual void setX(int x) {mX = x;} virtual int getX() const {return...
There's a really, darn good reason why shared_ptr does not allow explicit casting to A* (there are better ways of doing it than inheriting, which would be impossible anyway). The whole purpose of shared_ptr, and other smart pointers, are to provide a small, encapsulated object that's sole purpose is to own a pointer a...
4,411,386
4,411,590
Dilemma about shared libraries on Unix
If I build a shared library (shared object) I can use it in two following ways: First way is to use a shared library like I would use a static library. #include "myLib.h" //... //afterwards I can use functions defined in mylib.h myFunction(); The second way of using shared l...
These two use modes are typically called implicit and explicit. As you correctly stated the difference in loading is that explicitly linked dynamic library is loaded when dlopen is executed and implicitly linked library is loaded at the time the application is loaded in memory. Each dlopen may take milliseconds to fini...
4,411,613
4,411,625
Simple parsing question
Possible Duplicate: Could anyone explain these undefined behaviors (i = i++ + ++i , i = i++, etc…) Undefined Behavior and Sequence Points (C++ FAQ entry) In C and C++ how is the expression x+++++y parsed? As x++ ++ +y or as x++ + ++y ?
x+++++y is parsed as x ++ ++ + y and not as x ++ + ++ y. According to Maximal Munch principle "the tokenizer should keep reading characters from the source file until adding one more character causes the current token to stop making sense" x++ ++ +y should not compile(In C and C++) because the post-increment operator +...
4,411,893
4,416,032
When does QVBoxLayout recalculate the layout?
I have a window with a a QVBoxLayout in it. The layout has some child widgets (defined in a .ui file). In my window class' constructor, I create and assign a menu to the layout. The position of the widgets is supposed to shift down, since the menu takes some vertical space. This does not occur immediately - if I query ...
Perhaps this: http://doc.qt.nokia.com/stable/qlayout.html#activate
4,412,303
4,412,329
How copy part of int array to another int array in C/C++?
please can you help me? How can I copy part of one int array to another int array? Example: typedef struct part { int * array; } PART; int array[] = {1,2,3,4,5,6,7,8,9}; PART out[] = new PART[3]; for (int i = 0; i < 3; i++) { memcpy((char *)array[i * 3], (char *)out[i].array, 3 * sizeof(int)); } But this don't w...
Ok you have 3 problems. You are casting an int to a char* (char *)array[i * 3] What you really mean is (char *)&array[i * 3]. ie take the address of the i*3th element. you are trying to copy data from an uninitialised array. you should allocate memory to out[i].array. You appear to have your memcpy the wrong way roun...
4,412,441
4,412,530
Getting Header into file using ISAPI Filter
I am trying to get the entire raw header into a file but everytime I attempt to write the contents I get a file full of ÌÌÌÌÌÌÌÌÌÌÌ. What am I doing wrong? DWORD CTryISAPIFilter::OnPreprocHeaders(CHttpFilterContext* httpContext, PHTTP_FILTER_PREPROC_HEADERS headerInformation) { char buffer[4096]; DWORD b...
Is headerInformation->GetHeader() returning success? If so, how much is it actually writing into buffer (presumably it tells you this in a value it places in bufferSize) I suspect that GetHeader() is failing, and nothing is being written to buffer because: you're getting all "ÌÌÌÌÌÌÌÌÌÌÌ" characters (which is what the...
4,412,619
4,412,644
"cannot be used as a function error"
I am writing a simple program that uses functions found in different .cpp files. All of my prototypes are contained in a header file. I pass some of the functions into other functions and am not sure if I am doing it correctly. The error I get is "'functionname' cannot be used as a function". The function it says canno...
You are using growthRate both as a variable name and a function name. The variable hides the function, and then you are trying to use the variable as if it was the function - that is not valid. Rename the local variable.
4,412,709
4,513,054
How do I tell lcov where to find my .cpp & .h files?
My source and build tree looks like this (see Makefile to put object files from source files different directories into a single, separate directory?) after a make (which builds and runs FooAndBarTests): src - Foo.cpp - Bar.cpp inc - Foo.h - Bar.h test - FooTest.cpp - BarTest.cpp - Main.cpp - Makefile - obj - Foo.gcd...
Use the -b option to lcov. The -b option specifies code base.
4,412,749
4,412,832
Are flexible array members valid in C++?
In C99, you can declare a flexible array member of a struct as such: struct blah { int foo[]; }; However, when someone here at work tried to compile some code using clang in C++, that syntax did not work. (It had been working with MSVC.) We had to convert it to: struct blah { int foo[0]; }; Looking through th...
C++ was first standardized in 1998, so it predates the addition of flexible array members to C (which was new in C99). There was a corrigendum to C++ in 2003, but that didn't add any relevant new features. The next revision of C++ (C++2b) is still under development, and it seems flexible array members still aren't adde...
4,412,796
4,432,724
Qt - QTableView - Clickable button in table row
I require a button/link within a table row of a QTableView. This is to open a dialog to allow that row to be edited more efficiently. After hours of looking on the web I am yet to find a decent example. I am aware that this is likely to be done using a QItemDelegate, but I am unsure how to have a functional widget with...
You could emulate the functionality of a link by underlining the clickable text, then capturing the cell click via the cellClicked(row, col) signal and check that col == editColumn. Then row would correspond to which item you are editing. For example, Data Name | Value 1 | Value 2 | Edit connect (tableWidget, SIGNAL(ce...
4,413,101
4,510,203
Equivalent of SF_NOTIFY_READ_RAW_DATA for IIS6
I really would like the raw Read data off of SF_NOTIFY_READ_RAW_DATA but it is no longer supported in IIS6 without enabling IIS5 isolation mode which I do not want to do. Is there an equivalent to this line of code that works for IIS6? DWORD CTryISAPIFilter::OnReadRawData(CHttpFilterContext* pCtxt,PHTTP_FILTER_RAW_D...
I solved it, basically IIS6 no longer supports that function because of the parallized way IIS6 handles data. In order to capture the request body you have to use http modules, however you can still capture all the responses by using the OnWriteRawData function.
4,413,123
4,413,222
C++ exceptions, GCC and "inline-functions" flag
I was reading articles about exception handling in C++. I found this topic on StackOverflow. There were to simple tests, I changed them a bit: C code: #include <stdio.h> #include <time.h> #define BIG 10000000000 long f( long n ) { long r = 0, i = 0; for ( i = 0; i < 1000; i++ ) { r += i; if ( ...
These programs are not equivalent. In the C version, you return your sentinel, but in the C++, you throw it. An exception does not necessarily return to the caller, and so some additional machinery is placed both at call sites and in the called function to arrange to unroll the stack. The closest thing in C to a C++...
4,413,170
4,413,228
C++ | Generating a pseudo number between 10-20
I am making a text-based C++ RPG and I am trying to figure out how to work out the amount of damage that the enemy hits you for. My idea is something like this. Damage done = randomIntBetween10and20*enemyLevel This way it doesn't always hit for a set amount each time and allows there to be Critical Strikes (For exampl...
You should omit the word "truly" from the title, because you probably don't mean it. You probably just want a pseudorandom number. True randomness is virtually impossible to achieve with a personal computer. The following snippet will give you a pseudorandom number in the range 10..19 inclusive: #include<cstdlib> #incl...