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
1,963,493
1,963,524
hash_map crashing in c++ stl
i am relatively experienced in Java coding but am new to C++. I have written the following C++ code as solution to the USACO training problem which I have reproduced at this url This code looks fine to me. However it crashes on the sample test case given. On isolating the error, I found that if the second for loop is n...
The reason it is crashing is that vick is giving 0 friends money which causes a divide by zero exception from the following line of code: int amt = money/friends; You should put in some special logic to handle the case when the person has 0 friends so gives $0 away. As was stated in the other comments, you should use s...
1,963,560
1,963,570
'Bracket initializing'. (C++)
I'm learning C++ at the moment, C++ Primer plus. But I just felt like checking out the cplusplus website and skip a little forward to file handling. I pretty much know the basics of file handling coming from java, php, visual basic. But I came across a pretty weird line. ostream os(&fb); fb represents a filebuf. I jus...
Perhaps you should read this and this
1,963,880
1,963,893
Blt'ing through memoryDC does not work
HDC hdcScreen = GetDC(NULL); HDC hdcWindow = GetDC(mWin); HDC hdcMem = CreateCompatibleDC(hdcScreen); if (!hdcScreen || !hdcWindow || !hdcMem){ MessageBox(NULL, "could not locate hdc's", "Viewer", MB_ICONERROR); } if (!StretchBlt(hdcMem, 0, 0, 300, 300, hdcScreen, 0, 0, 300, 300, SRCCOPY)){ MessageBox(NULL, "s...
You need to create a bitmap and select it into the memory DC using SelectObject.
1,963,926
1,963,977
When is a vtable created in C++?
When exactly does the compiler create a virtual function table? 1) when the class contains at least one virtual function. OR 2) when the immediate base class contains at least one virtual function. OR 3) when any parent class at any level of the hierarchy contains at least one virtual function. A related question to ...
Beyond "vtables are implementation-specific" (which they are), if a vtable is used: there will be unique vtables for each of your classes. Even though B::f and C::f are not declared virtual, because there is a matching signature on a virtual method from a base class (A in your code), B::f and C::f are both implicitly ...
1,963,988
2,010,280
shared memory, MPI and queuing systems
My unix/windows C++ app is already parallelized using MPI: the job is splitted in N cpus and each chunk is executed in parallel, quite efficient, very good speed scaling, the job is done right. But some of the data is repeated in each process, and for technical reasons this data cannot be easily splitted over MPI (...)...
One increasingly common approach in High Performance Computing (HPC) is hybrid MPI/OpenMP programs. I.e. you have N MPI processes, and each MPI process has M threads. This approach maps well to clusters consisting of shared memory multiprocessor nodes. Changing to such a hierarchical parallelization scheme obviously r...
1,963,992
1,964,001
Check Windows version
How I can check in C++ if Windows version installed on computer is Windows Vista and higher (Windows 7)?
Similar to other tests for checking the version of Windows NT: OSVERSIONINFO vi; memset (&vi, 0, sizeof vi); vi .dwOSVersionInfoSize = sizeof vi; GetVersionEx (&vi); if (vi.dwPlatformId == VER_PLATFORM_WIN32_NT && vi.dwMajorVersion >= 6)
1,964,149
1,966,168
SetCursorPos and GetCursorPos not working at login screen?
When I attempt to use SetCursorPos at the Windows Vista/7 login screen, true is returned which at first made me think it was working. However, when I call GetCursorPos it gives me: -858993460,-858993460 Any thoughts why? Is this a "security feature" or am I using it incorrectly? The code works fine on non-login (i.e. ...
Alternative solution: It is possible (but very tricky) to use mouse_event (which does work at login screen) instead of SetCursorPos. I don't have time to post code now, but if asked I may update this answer...
1,964,150
1,964,252
c++ test if 2 sets are disjoint
I know the STL has set_difference, but I need to just know if 2 sets are disjoint. I've profiled my code and this is slowing my app down quite a bit. Is there an easy way to see if 2 sets are disjoint, or do I need to just roll my own code? EDIT: I also tried set_intersection but it took the same time...
Modified hjhill's code to reduce complexity by a factor of O(log n) by getting rid of the count() call. template<class Set1, class Set2> bool is_disjoint(const Set1 &set1, const Set2 &set2) { if(set1.empty() || set2.empty()) return true; typename Set1::const_iterator it1 = set1.begin(), it1E...
1,964,256
1,964,273
How to make a C++ class compatible with stringstream objects?
I would like to be able to serialize my C++ classes using standard techniques like std::stringstream or boost::lexical_cast. For example if I have a Point object (2, 4) then I would like to serialize it to "(2, 4)", and also be able to construct a Point object from this string. I have some code already but with a few i...
To read an entire line, you can use the function std::getline: std::string text; getline(str, text);
1,964,463
1,964,561
How to interpret g++ warning
I've got a very strange g++ warning when tried to compile following code: #include <map> #include <set> class A { public: int x; int y; A(): x(0), y(0) {} A(int xx, int yy): x(xx), y(yy) {} bool operator< (const A &a) const { return (x < a.x || (!(a.x < x) && y < a.y)); } }; struct ...
gcc 4.4 has a bug where std::map breaks incorrectly warns about strict-aliasing rules. http://gcc.gnu.org/bugzilla/show_bug.cgi?id=39390 Your code is valid C++. Strict aliasing merely allows a subset of optimizations that are enabled by default when using -O3. Your solution is to compile with -fno-strict-aliasing or a...
1,964,478
1,964,490
Displaying exception debug information to users
I'm currently working on adding exceptions and exception handling to my OSS application. Exceptions have been the general idea from the start, but I wanted to find a good exception framework and in all honesty, understand C++ exception handling conventions and idioms a bit better before starting to use them. I have a l...
Wrapping all your code in one try/catch block is a-ok. It won't slow down the execution of anything inside it, for example. In fact, all my programs have (code similar to) this framework: int execute(int pArgc, char *pArgv[]) { // do stuff } int main(int pArgc, char *pArgv[]) { // maybe setup some debug stuff,...
1,964,595
1,964,613
Less CPU usage in C++: declaring as unsigned int or not?
What requires the most CPU: int foo = 3; or typecasting it to an unsigned int? unsigned int foo = 3;
My immediate thought is: it is not casting the int into unsigned int. So there is no difference in speed. hereis the link about the fast types. However it's more the algorithms which and functions which should be optimised rather than types.
1,964,708
1,964,759
I-Phone VM for Android
I'm considering opening up a project to create an i-phone virtual machine for android 2.0 (read motorola droid) before i do so i have some questions: Does one already exist that i just missed? Can the the Droid's Arm Cortex A8 down-clocked to 550MHz (thanks wikipedia) handle an I-Phone abstraction layer? Performance w...
Does one already exist that i just missed? No. Can the the Droid's Arm Cortex A8 down-clocked to 550MHz (thanks wikipedia) handle an Iphone? No, but the CPU is not strictly the issue. Performance wise the best thing to do is write the app in C++, but for the health of the system, would it be better to ...
1,964,722
1,964,823
One big pool or several type specific pools?
I'm working on a video game which requires high performance so I'm trying to setup a good memory strategy or a specific part of the game, the part that is the game "model", the game representation. I have an object containing a whole game representation, with different managers inside to keep the representation consist...
The correct answer is specific to your problem domain. But in the problem domains that I work, the first is usually the one we choose. I do realtime or near realtime code. Audio editing and playback mostly. In in that code, we generally cannot afford to allocate memory from the heap down in the playback engine. Mo...
1,964,751
1,964,794
rate my (C++) code: a recursive strstr sans any standard library string functions :)
So, the idea was a write a recursive function that compares two strings to see if string 'prefix' is contained in string 'other', without using any standard string functions, and using pointer arithmetic. below is what i came up with. i think it works, but was curious - how elegant is this, scale 1-10, any obvious funk...
It is 1AM and far to late for understanding code, however such a simple function should be really easy to comprehend and your code isn't. Static variables when writing functions are not a good idea because they make it incredibly hard to debug as the function ceases to become stateless. Try passing the values you need ...
1,964,821
1,964,847
strcmpi renamed to _strcmpi?
In MSVC++, there's a function strcmpi for case-insensitive C-string comparisons. When you try and use it, it goes, This POSIX function is deprecated beginning in Visual C++ 2005. Use the ISO C++ conformant _stricmp instead. What I don't see is why does ISO not want MSVC++ to use strcmpi, and why is _stricmp the pref...
ISO C reserves certain identifiers for future expansion (see here), including anything that starts with "str".
1,964,926
1,964,958
Converting C-Strings from Local Encoding to UTF8
I'm writing a small App in which i read some text from to console, which is then stored in a classic char* string. As it happens i need to pass it to an lib which only takes UTF-8 encoded Strings. Since the Windows console uses the local Encoding, i need to convert from local encoding to UTF-8. If i'm not mistaken i co...
Converting from UTF-16 to UTF-8 is purely a mechanical process, but converting from local encoding to UTF-16 or UTF-8 involves some large specialized lookup tables. The c-runtime just turns around and calls WideCharToMultiByte and MultiByteToWideChar for non-trivial cases. As for having to use UTF-16 as an intermediat...
1,965,029
1,965,036
one question about std::cin
int i,j; std::string s; std::cin>>i>>j>>s>>s>>i; std::cout<<i<<" "<<j<<" "<<s<<" "<<i; Question Referring to the sample code above, what's the displayed output if the input string given is: "5 10 Sample Word 15 20"? The answer is 15 10 Word 15 I have the question is what's the underline policy for cin to over writ...
std::cin >> i >> j >> s >> s >> i; is equivalent to: std::cin >> i; std::cin >> j; std::cin >> s; std::cin >> s; // overwrite previous s std::cin >> i; // overwrite previous i Every time you read from cin to a variable, the old contents of that variable is overwritten. So you are explicitly asking to overwrite s an...
1,965,067
1,965,105
Good c++ profiler for GCC
I tried to find a related question but all previous questions are about profilers for native c++ in windows. I googled a while and learned about gprof, but the output of gprof actually contained lot of obscure internal functions. Is there a good opensource c++ profiler with good documentation?
Valgrind I totally recommend this http://en.wikipedia.org/wiki/Valgrind
1,965,249
1,965,344
How to write a Java-enum-like class with multiple data fields in C++?
Coming from a Java background, I find C++'s enums very lame. I wanted to know how to write Java-like enums (the ones in which the enum values are objects, and can have attributes and methods) in C++. For example, translate the following Java code (a part of it, sufficient to demonstrate the technique) to C++ : public e...
One way to simulate Java enums is to create a class with a private constructor that instantiates copies of itself as static variables: class Planet { public: // Enum value DECLARATIONS - they are defined later static const Planet MERCURY; static const Planet VENUS; // ... private: dou...
1,965,328
1,965,446
Call different functions using Direct Parameter Access in C
I recently stumbled upon this page. And I was particularly interested about the section which dealt with Direct Parameter Access. I was just wondering if there is any way to execute just one of the functions depending on the value of n in the following line: printf("%n$p", func1, func2, func3 .. funcN); where func1,.....
No, you can't do this with printf as printf does not support invocation of function pointer parameters. But, you can write your own function that does this using stdarg: #include <stdarg.h> void invoke_and_print(unsigned int n, ...) { va_list ap; va_start(ap, n); int (*fp)(void) = NULL; while (n-- != ...
1,965,481
1,965,853
debug DLL in a different solution
I have an *.exe project that was written in one solution under vs2005 and i have a DLL file that the *.exe project is using. the problem is that the dll was written in adiffrent solution and when i try to make attach to the *.exe file (after i run it) from the dll solution in order to debug the dll , i get no symbols ...
First check the Output window, it will show whether or not it could find debugging symbols for the DLL when it got loaded. Next, switch to Debug + Windows + Modules, right-click your DLL and choose "Symbol load information". That shows where the debugger looked for .pdb files for the DLL. Ensure the .pdb is located ...
1,965,487
1,966,649
Does the restrict keyword provide significant benefits in gcc/g++?
Has anyone ever seen any numbers/analysis on whether or not use of the C/C++ restrict keyword in gcc/g++ actual provides any significant performance boost in reality (and not just in theory)? I've read various articles recommending / disparaging its use, but I haven't ran across any real numbers practically demonstrati...
The restrict keyword does a difference. I've seen improvements of factor 2 and more in some situations (image processing). Most of the time the difference is not that large though. About 10%. Here is a little example that illustrate the difference. I've written a very basic 4x4 vector * matrix transform as a test. No...
1,965,640
1,965,649
What is this C++ Syntax when declaring a class?
I occasionally run into this type of syntax when looking through open source code and was wondering what it's for, or what it's even called for that matter. I have crawled the internet many a times before but simple contrived examples never had it nor explained it. It looks like this class SomeIdentifier ClassName { ...
Generally this would be something like that #define SomeIdentifier __declspec(dllexport) It is for support of MS dlls where you must specify explicitly every class that is used in interface. And SomeIdentifier would be something like FOO_BAR_EXPORT
1,965,751
1,965,762
how do I read a huge .gz file (more than 5 gig uncompressed) in c
I have some .gz compressed files which is around 5-7gig uncompressed. These are flatfiles. I've written a program that takes a uncompressed file, and reads it line per line, which works perfectly. Now I want to be able to open the compressed files inmemory and run my little program. I've looked into zlib but I can't fi...
gzip -cd compressed.gz | yourprogram just go ahead and read it line by line from stdin as it is uncompressed. EDIT: Response to your remarks about performance. You're saying reading STDIN line by line is slow compared to reading an uncompressed file directly. The difference lies within terms of buffering. Normally pipe...
1,966,077
1,966,096
Calculate the factorial of an arbitrarily large number, showing all the digits
I was recently asked, in an interview, to describe a method to calculate the factorial of any arbitrarily large number; a method in which we obtain all the digits of the answer. I searched various places and asked in a few forums. But I would like to know if there is any way to accomplish this without using libraries l...
GNU Multiprecision library is a good one! But since you say using of external libraries are not allowed, only way I believe its possible is by taking an array of int and then multiplying numbers as you do with pen on paper! Here is the code I wrote some time back.. #include<iostream> #include<cstring> int max = 5000; ...
1,966,319
1,966,323
about const member function
I met two explanation of const member function class A{ public: ... void f() const {} ... } it means it could only access constant members; it means it does not modify any members; I think the second one is right. But why does the first one come out? Is there anything to be clarify? Thanks!
You can examine all class member values in a const member function, and in some cases you can even change the value of member variables. The first explanation is incorrect, I don't know where it comes from. The second explanation is correct, but with a few exceptions. There are some exceptions to this rule. You can al...
1,966,352
1,966,541
Build C/C++ library to link it into delphi application... How?
if I have a source of library written in C/C++ (lets say its libxml2), now I'd like to build it, and link it into the delphi application... I know it is possible, since Delphi Zlib does it ( http://www.dellapasqua.com/delphizlib/ ) ... But my question is, how to prepare those .obj files? Thanks in advance m.
You would need to use CodeGear's C++ compiler to produce compatible obj files for Delphi. Does your Delphi come with C++ Builder? Otherwise you could try the free (Borland) commandline version. Read more about this subject here.
1,966,362
1,967,183
SFINAE to check for inherited member functions
Using SFINAE, i can detect wether a given class has a certain member function. But what if i want to test for inherited member functions? The following does not work in VC8 and GCC4 (i.e. detects that A has a member function foo(), but not that B inherits one): #include <iostream> template<typename T, typename Sig> ...
Take a look at this thread: http://lists.boost.org/boost-users/2009/01/44538.php Derived from the code linked to in that discussion: #include <iostream> template <typename Type> class has_foo { class yes { char m;}; class no { yes m[2];}; struct BaseMixin { void foo(){} }; struct Base : ...
1,966,577
1,966,590
How to determine architecture in platform neutral way?
I have a C++ app that uses wxWidgets. Certain parts of the app differ for 32 and 64 bit hosts. Currently I use sizeof(void *), but is there a better way that uses conditional compilation and is platform neutral?
Typically people use #defines to determine bitness (the exact define will depend on the compiler). This is better than a runtime approach using sizeof(void*). As for platform neutral, well, some compilers are on multiple platforms..
1,966,687
1,966,712
Bogus IP Address from getaddrinfo & inet_ntop
I've been using getaddrinfo for looking up socket addresses for basic socket commands. Recently, though, the addresses it returns to me are for bogus IP addresses, which I have found using inet_ntop. I've tried my code, as well as that provided in Beej's Guide, and they both produce the same results. Here's the code: s...
Shouldn't you be passing ((sockaddr_in const *)info->ai_addr)->sin_addr to inet_ntop?
1,966,705
1,966,776
Qt, widget generated with inheritance?
I remember when messing around with Qt seeing something where it was like class MyForm : QDialog { } Instead of class MyForm { void SetupUi(QDialog* dialog); } How do you generate the inherited form?
It is the new and only way to setup your UI since Qt 4.0. Like it or not, you can always alter the generated code before building. Here's an article on porting .ui files to Qt 4.x - http://qt.nokia.com/doc/4.0/porting4-designer.html.
1,966,893
1,966,897
C++ variable types limits
here is a quite simple question(I think), is there a STL library method that provides the limit of a variable type (e.g integer) ? I know these limits differ on different computers but there must be a way to get them through a method, right? Also, would it be really hard to write a method to calculate the limit of a va...
Use std::numeric_limits: // numeric_limits example // from the page I linked #include <iostream> #include <limits> using namespace std; int main () { cout << boolalpha; cout << "Minimum value for int: " << numeric_limits<int>::min() << endl; cout << "Maximum value for int: " << numeric_limits<int>::max() << endl...
1,967,124
1,967,135
Finding a byte-pattern in some memory area
I want to search some memory range for a specific byte pattern. Therefore, my approach is to build a function void * FindPattern (std::vector<byte> pattern, byte wildcard, void * startAddress, void * endAddress); using the Boyer-Moore-Horspool algorithm to find the pattern in the memory range. The wildcard byte s...
The Wikipedia page on BMH has an implementation. I think that Boost xpressive is also based on (a variant of) BMH.
1,967,278
1,967,382
Shortening series of push_back's on a byte-vector
In my code, I want to use a byte-vector to store some data in memory. The problem is, that my current approach uses many lines of code: std::vector<byte> v; v.push_back(0x13); v.push_back(0x37); v.push_back(0xf0); v.push_back(0x0d); How can I shorten this procedure so that I have for example something like: std::vecto...
This solution gets the string length from the literal itself, meaning you don't need extra 5s and 4s lying around: const unsigned char src[] = "\xDE\xAD\xBE\xEF"; std::vector<unsigned char> pattern(src, src+sizeof(src)); Note that a null terminator (extra zero byte) is added to the array; sizeof(src) is 5 because it's...
1,967,283
1,968,145
Multiple inheritance on different template types
I'm working on event handling in C++ and to handle notification of events, I have a class EventGenerator which any class generating events can inherit from. EventGenerator has a method which other classes can use to add in callbacks and a method to call the callbacks once an event happens To handle notification of diff...
Beware of diamond inheritance heirarchies. Also note that overloading virtual functions is a bad thing. So if you have something like this: class Handler : public EventHandler<int>, public EventHandler<string> { ... }; Which changeEvent() function will be called? Don't count on it! If you are careful the above code sh...
1,967,391
1,967,400
Is there a way to _get_ the UnhandledExceptionFilter?
SetUnhandledExceptionFilter() lets me install a function that gets called in case of an unhandled exception. I'm looking for a way to get the currently installed function, so I can store&restore it. I can't seem to find a Get equivalent of the SetUnhandledExceptionFilter call, and am wondering if I'm missing someth...
SetUnhandledExceptionFilter actually returns the old unhandled exception filter, so you can check that way. Set a NULL filter, check the result, then set it again.
1,967,659
1,967,663
Passing on va_arg twice to a function result in same value
I'm trying to use va_arg to make a generic factory function in my GUI library. When passing va_arg twice in the same function they pass on the same value instead of two different: GUIObject* factory(enumGUIType type, GUIObject* parent, ...){ va_list vl; va_start(vl, parent); ... label->SetPosition(va_arg(vl...
The compiler is not guaranteed to evaluate arguments in order. Add some additional local variables and do the two assignments in sequence. See this other stack overflow posting. int v1 = va_arg(vl, int); int v2 = va_arg(vl, int); label->SetPosition(v1, v2); To get what you are observing: the exact same value twice --...
1,967,703
1,967,717
Error in linking to friend functions
I have a class 'Vector3' which is compiled successfully. It contains both non-friend and friend functions, for example, to overload * and << operators when Vector3 is the second operand. The problem is I can't link to any of the friend functions, be it operator overloaded or not. So I can confirm that the error is not ...
The definition of friend operator* uses fp_type while the friend declaration uses double as the first parameter. This will only work as intended if fp_type is a typedef-name for double. Are you sure fp_type actually stands for double? I can't see it from the code you posted. The problem with mag is rather obvious: you ...
1,967,762
1,967,772
Compiling c++ program under linux
I am trying to compile simple program under linux. These are the set of operations I performed. [mypc@localhost programs]$ vim heap.cpp [mypc@localhost programs]$ g++ -c heap.cpp [mypc@localhost programs]$ chmod 777 heap.* [mypc@localhost programs]$ g++ -c heap.cpp [mypc@localhost programs]$ ./heap.o bash: ./heap.o:...
The -c option tells the compiler to generate an object file, not the final binary. You still need to link your code. If you only have a single file, you can do a compile and link in one step: g++ heap.cpp -o heap As you get to bigger programs, you will want to separate compilation from linking. Let's say you want to...
1,967,882
1,967,960
is there a difference between malloced arrays and newed arrays
I'm normally programming in c++, but are using some clibrary functions for my char*. Some of the manpages like for 'getline', says that input should be a malloced array. Is it ok, to use 'new' instead? I can see for my small sample that it works, but could this at some point result in some strange undefined behavior? ...
The buffer passed to getline() MUST be malloced. The reason is that getline() may call realloc() on the buffer if more space is required. realloc() like free() should only be used with memory allocated by malloc(). This is because malloc() and new allocate memory from different storage areas: See: What is the differenc...
1,968,204
1,968,262
QMetaObject::invokeMethod returns true, but method is never called
I'm trying to run a method on the GUI thread using QMetaObject::invokeMethod, which returns true. But, if I use Qt::QueuedConnection my method never gets called (even if invokeMethod returns true). This is what I'm using: QMetaObject::invokeMethod(this, "draw_widgets", Qt::QueuedConnection) I don't get any error messa...
The "true" is telling you the message was successfully queued. That doesn't mean the queued message was ever processed... Let us say your program has 10 threads (Thread1-Thread10). You queue a message from Thread7. Which thread will it be queued to? And when will items on this queue be processed? The answer is t...
1,968,407
1,968,423
How to know defination of a struct in dll?
I need to use a third party DLL which I don't have header , lib or object file of it just DLL alone, I follow this article "Explicitly Linking to Classes in DLL's" in codeguru and able to user function, c++ class from that DLL but there some function call that need to pass or return a struct like this undecorated funct...
I'm afraid there is no way to solve your problem. Disassembling can give you examples of how this structure is used but only in the way providing offsets of members which is not very helpful. I think the best is to ask DLL author to send you header, or to google for it...
1,969,085
1,969,164
What is the difference between ANSI/ISO C++ and C++/CLI?
Created by Microsoft as the foundation of its .NET technology, the Common Language Infrastructure (CLI) is an ECMA standard (ECMA-335) that allows applications to be written in a variety of high-level programming languages and executed in different system environments. Programming languages that conform ...
"System environments" means things like Linux, Windows x86, Windows x64, etc. Notice how they use the term "architecture" interchangeably at the end of the paragraph. A native C++ program is one where you take standard (ANSI/ISO) C++ and you compile it into a .exe. Usually you will be compiling this for a specific env...
1,969,343
1,969,349
Cannot export template function
I have a class named "SimObject": namespace simBase { class __declspec(dllexport) SimObject: public SimSomething { public: template <class T> void updateParamValue( const std::string& name, T val ); } } I have another class named "ITerrainDrawable": namespace simTerrain { ...
C++ does not really support the separate compilation of template code - you need to put the definition of the template in a header file.
1,969,484
1,969,693
How to get details about the selected items using QTreeView?
I'm using QTreeView with QDirModel like this: QDirModel * model = new QDirModel; ui->treeView->setModel(model); ui->treeView->setSelectionMode(QTreeView::ExtendedSelection); ui->treeView->setSelectionBehavior(QTreeView::SelectRows); This works fine, however, I'm not sure how to get the details about the files I select...
you can use fileInfo method of the QDirModel to get file details for the given model index object, smth like this: QModelIndexList list = ui->treeView->selectionModel()->selectedIndexes(); QDirModel* model = (QDirModel*)ui->treeView->model(); int row = -1; foreach (QModelIndex index, list) { if (index.row()!=row &&...
1,969,579
1,982,200
Getting a handle to the process's main thread
I have created an additional thread in some small testing app and want to suspend the main thread from this additional thread. The additional thread is created via CreateRemoteThread from an external process. Since SuspendThread needs a HANDLE to the thread which should be suspended, I want to know how to get this HAND...
DWORD GetMainThreadId () { const std::tr1::shared_ptr<void> hThreadSnapshot( CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0), CloseHandle); if (hThreadSnapshot.get() == INVALID_HANDLE_VALUE) { throw std::runtime_error("GetMainThreadId failed"); } THREADENTRY32 tEntry; tEntry.dwSize = ...
1,969,620
1,969,637
c++ float to bool conversion
I'm looking at some 3rd party code and am unsure exactly what one line is doing. I can't post the exact code but it's along the lines of: bool function(float x) { float f = doCalculation(x); return x > 0 ? f : std::numeric_limits<float>::infinity(); } This obviously throws a warning from the compiler about converting ...
I think it is a mistake. That function should return a float. This seem logical to me. The conversion float to bool is the same as float != 0. However, strict comparing two floating points is not always as you'd expect, due to precision.
1,969,916
1,970,871
Static analysis tool to detect ABI breaks in C++
It's not very hard to break binary backwards-compatibility of a DSO/shared library with a C++ interface. That said, is there a static analysis tool, which can help detecting such ABI breaks, if it's given two different sets of header files: those of an earlier state of the DSO and those of the current state (and maybe ...
I assume that you are familiar with this tutorial: Binary Compatibility Issues with C++, if not read it! I've heard about this tool: http://ispras.linuxbase.org/index.php/ABI_compliance_checker, however never tested or used one, so have no opinion. Also this may interest you: Creating Library with backward compatible ...
1,969,955
2,126,040
How to turn Sequence of images into video using DirectShow filters?
How to turn Sequence of images into video using DirectShow filters? I have image A and image B and image C. I want to create a DirectShow graph (Using GraphEdit or with C\C++\C# for example) to create a video of 3 frames in duration where first frame is image A second image B and so on =) How to do it?
Take a look at the Push Source Filters Sample from MSDN: MSDN Push Source Filter sample
1,969,984
1,973,981
How to create a DirectShow graph which would wait for incoming images and add them as frames into video file?
How to create a DirectShow graph which would wait for incoming images and add them as frames into video file? Using GraphEdit or with C\C++\C# So I want to have a graph which would work and wait for images incoming into him in any way you think is most easy (for example We can have a folder from where DSfilter would be...
You need a source filter, multiplexor and file writer. The multiplexor and file writer are stock components, but the source filter will be a custom filter. Look at the app source example on www.gdcl.co.uk for an example of a custom source filter that you can feed with frames from your app. The graph will not be time-se...
1,970,041
1,970,301
Background Gradient with Magick++
How do I create gradients with ImageMagick in C++? I am trying to create a visual representation of a WAV file. I can create an Image with Magick++, draw in the waveform data and save the image as a .png file but it still looks a bit basic. I'd like to give the image background and waveform gradients but I don't know h...
I believe you would have to use the Pixel class and interpolate Colors to create your own gradient fill. The manual for Magick++ does not indicate that it has native functions for gradient fill. It may also be possible to use the core ImageMagick API for gradient fill. Here's some useful links: http://www.imagemagick....
1,970,164
1,970,228
Function pointers for winapi functions (stdcall/cdecl)
Please could someone give me a few tips for creating function pointers for MS winapi functions? I'm trying to create a pointer for DefWindowProc (DefWindowProcA/DefWindowProcW) but getting this error: LRESULT (*dwp)(HWND, UINT, WPARAM, LPARAM) = &DefWindowProc; error C2440: 'initializing' : cannot convert from 'LRESU...
Fix the calling convention mismatch like this: LRESULT (__stdcall * dwp)(HWND, UINT, WPARAM, LPARAM) = DefWindowProc; A typedef can make this more readable: typedef LRESULT (__stdcall * WindowProcedure)(HWND, UINT, WPARAM, LPARAM); ... WindowProcedure dwp = DefWindowProc; But, <windows.h> already has a typedef for th...
1,970,294
1,970,357
global variables in C++
So I have something like this #define HASHSIZE 1010081 static struct nlist *hashtab[HASHSIZE]; Now I want to be able to change the HASHSIZE of my hashtab, because I want to test different primes numbers and see which would give me less collisions. But Arrays do not take variable sizes so HASHSIZE has to be a constant...
Why don't you use std::vector instead of using arrays in C++? Eg: std::vector<nlist *> hashtab; hashtab.resize(<some_value>); But anyways you can do this if you are using g++ because g++ supports Variable Length Arrays(VLAs) as an extension. Eg: int HASHSIZE=<some_value> static struct nlist *hashtab[HASHSI...
1,970,315
1,980,385
c++ full transparency window but still read text for example
I'm trying to do something like Rainmeter do to its windows, that is use the full transparency in a window but we still read the text of each window. Anyone can explain me how this is done? how we set the full transparency in a window and show certain parts of this window (like text or other things). I can do this with...
In answer to your comment: To make part of the window transparent, call the UpdateLayerdWindow function and give it a partially transparent background image. You can also pass the ULW_COLORKEY instead of giving a partially transparent background image, and every part of the window that is the color you specify will bec...
1,970,316
1,970,475
How to handle "item not found" situations in a find function?
I'm frequently run into a situation where I need to report in some way that a finding an item has failed. Since there are many ways how to deal with such a situation I'm always unsure how to do it. Here are a few examples: class ItemCollection { public: // Return size of collection if not found. size_t getInde...
Your functions are more like std::string::find than any of the iterator-based functions in the algorithm header. It returns an index, not an iterator. I don't like that your function returns the collection size to emulate "one past the end." It requires the caller to know the collection size in order to check whether t...
1,970,384
1,970,416
Switch pointers in a function in the C programming language
How do you switch pointers in a function? void ChangePointers(int *p_intP1, int *p_intP2); int main() { int i = 100, j = 500; int *intP1, *intP2; /* pointers */ intP1 = &i; intP2 = &j; printf("%d\n", *intP1); /* prints 100 (i) */ printf("%d\n", *intP2); /* prints 500 (j) */ ChangePointers(intP1, intP2); printf("%...
In C, parameters are always passed by values. Although you are changing the values of the pointer variables inside the called function the changes are not reflected back to the calling function. Try doing this: void ChangePointers(int **p_intP1, int **p_intP2); /*Prototype*/ void ChangePointers(int **p_intP1, int **p_...
1,970,843
1,971,023
protobuf-net communicating with C++
I'm looking at protobuf-net for implementing various messaging formats, and I particularly like the contract-based approach as I don't have to mess with the proto compiler. one thing I couldn't quite find information on is, does this make it difficult to work cross-platform? there are a few C++ apps that would need to ...
Yes, in theory at least they should match at the binary level, but you might want to limit yourself to types that map simply to ".proto" - so avoid things like DateTime, inheritance ([ProtoInclude]), etc. This also has the advantage that you should be able to use: string proto = Serializer.GetProto<YourType>(); to get...
1,971,087
1,971,388
long integer multiplication
I am preparing the interview questions not for homework. There is one question about how to multiple very very long integer. Could anybody offer any source code in C++ to learn from? I am trying to reduce the gap between myself and others by learning other's solution to improve myself. Thanks so much! Sorry if you thi...
you can use GNU Multiple Precision Arithmetic Library for C++. If you just want an easy way to multiply huge numbers( Integers ), here you are: #include<iostream> #include<string> #include<sstream> #define SIZE 700 using namespace std; class Bignum{ int no[SIZE]; public: Bignum operator *(B...
1,971,183
1,971,196
when does c++ allocate/deallocate string literals
When is the string literal "hello" allocated and deallocated during the lifetime of the program in this example? init(char **s) { *s = "hello"; } int f() { char *s = 0; init(&s); printf("%s\n", s); return 0; }
The string literal is initialised into read-only memory segment by the compiler. There is no initialisation or removal done at run-time.
1,971,201
1,971,207
How to overload array index operator for wrapper class of 2D array?
#define ROW 3 #define COL 4 class Matrix { private: int mat[ROW][COL]; //..... //..... }; int main() { Matrix m; int a = m[0][1]; // reading m[0][2] = m[1][1]; // writing } I think directly it not possible to overload [][] . I think i have to do it indirectly but how to implement it?
The easier solution is to use the operator() as it allows multiple parameters. class M { public: int& operator()(int x,int y) {return at(x,y);} // .. Stuff to hold data and implement at() }; M a; a(1,2) = 4; The easy way is that the first operator[] returns an intermediate object that the second op...
1,971,202
1,971,218
Member access differences
can someone tell me what is the different between (*ptr).field and ptr->field? I know it connect somehow to static and dynamic linking, but i dont know what is it. can someone tell me the differnet and give me an example? edit: if i have this code: Point p; //point is a class that derive from class shape Shape ...
it has nothing to do with static or dynamic linking both expressions will return the value of ptr.field the ptr->field form is an abbreviated syntax for accessing a member directly from a pointer UPDATE: it occurred to me that your original intent was not linking but binding if this indeed was what you were aiming ...
1,971,271
1,971,335
VC choosing the wrong operator<< overload only at the first call. Bug?
I spent some time removing all the uninfluent code and here is my problem. --- File.h --- #include <fstream> #include <string> template <typename Element> class DataOutput : public std::basic_ofstream<Element> { public: DataOutput(const std::string &strPath, bool bAppend, bool bBinary) : std::basic_ofstream<El...
Looks like a compiler bug. You might want to try with the latest VC compiler (which at the moment is VC10 Beta2), and if it's not fixed, follow up with the VC team (you'll need a complete self contained repo). If it is fixed, you should just use the work around you found and move on with your life.
1,971,277
1,971,320
any possible explanations for this weird crash?
I have a core file I am examining. And I am just stumped at what can be the possible causes for this. Here is the behavoir: extern sampleclas* someobj; void func() { someobj->MemFuncCall("This is a sample str"); } My crash is inside MemFuncCall. But when I examine core file, someobj has an address, say abc(this ad...
It is possible. Maybe some kind of buffer overrun? Maybe the calling convention (or definition in general) is wrong for MemFuncCall (there is a mismatch between the header you compiled with and when MemFuncCall was compiled). Hard to say. But since this is single threaded I would try following technique. Usually memory...
1,971,311
1,971,326
What does it mean when the first "for" parameter is blank?
I have been looking through some code and I have seen several examples where the first element of a for cycle is omitted. An example: for ( ; hole*2 <= currentSize; hole = child) What does this mean? Thanks.
It just means that the user chose not to set a variable to their own starting value. for(int i = 0; i < x; i++) is equivalent to... int i = 0; for( ; i < x; i++) EDIT (in response to comments): These aren't exactly equivalent. the scope of the variable i is different. Sometimes the latter is used to break up the cod...
1,971,421
1,971,591
stl hash_map slower than simple hash function?
I was comparing a simple hash function that I wrote which just multiplies it by a prime mod another prime number (the table size) and it turns out that stl is slower by 100 times. This is the test method that I wrote: stdext:: hash_map<string, int> hashDict; for (int l = 0; l < size; ++l){ hashDict[arr[l]] = l; } l...
The VS2008 STL implementation uses the following hash function for strings: size_t _Val = 2166136261U; while(_Begin != _End) _Val = 16777619U * _Val ^ (size_t)*_Begin++; This is no less efficient than yours, certainly not 100x, and I doubt the Builder version is much different. The difference is either in measure...
1,971,707
1,971,822
How to find table size and memory consumption of STL hash_map?
I want to know how stl hash_map is implemented. How do I find out what the table size is and the memory space the map consumes? This is in C++.
There is no such thing as an "stl hash_map". There is an unordered_map in TR1, but I assume you're not using that or you would have said unordered_map. As someone pointed out, unordered_map has "bucket_count" to determine the number of buckets. You can iterate over each bucket, get it's size ("bucket_size(size_t bucket...
1,971,758
1,971,882
C++ context switch and mutex problem
Ok.. here is some background on the issue. I have some 'critical' code that i'm trying to protect with a mutex. It goes something like this Mutex.Lock() // critical code // some file IO Mutex.Unlock(). Now the issue is that my program seems to be 'stuck' due to this. Let me explain with an example. Thread_1 comes in; a...
As others have mentioned, you probably have a deadlock. Sidenote: You'll want to make sure that there aren't any uncaught exceptions thrown in the critical block of code. Otherwise the lock will never be released. You can use an RAII lock to overcome this issue: class SingleLock { public: SingleLock(Mutex &m) : m(m...
1,971,961
1,971,982
Is there anything wrong with this shuffling algorithm?
I have been doing a little recreational holiday computing. My mini-project was a simulation of the Italian game of "tomboli". A key building block was a simulation of the following process; The game is controlled by a man with a bag of 90 marbles, numbered 1 to 90. He draws marbles one by one randomly from the bag, eac...
You're using the Fisher-Yates shuffling algorithm.
1,972,003
2,391,089
How to compile C code with anonymous structs / unions?
I can do this in c++/g++: struct vec3 { union { struct { float x, y, z; }; float xyz[3]; }; }; Then, vec3 v; assert(&v.xyz[0] == &v.x); assert(&v.xyz[1] == &v.y); assert(&v.xyz[2] == &v.z); will work. How does one do this in c with gcc? I have typedef struct { union...
according to http://gcc.gnu.org/onlinedocs/gcc/Unnamed-Fields.html#Unnamed-Fields -fms-extensions will enable the feature you (and I) want.
1,972,058
1,972,070
What represents Math.IEEERemainder(x,y) in C++?
What represents Math.IEEERemainder(x,y) in C++?
Try the fmod function.
1,972,079
1,972,590
How to tell the controller what view to call?
I have a virtual function that is called handlePathChange() in my Controller class. It checks the current URL and should dispatch the right view for it. Here's the code I have so far: void Controller::handlePathChange() { if ( app->internalPathMatches(basePath) ) { string path = app->internalPathNextP...
I realize your post uses a c++ example, but if you don't mind reading some c#, this article by Scott Guthrie is a great overview of how the ASP.NET MVC framework implements its routing: http://weblogs.asp.net/scottgu/archive/2007/12/03/asp-net-mvc-framework-part-2-url-routing.aspx I think you will find that article ver...
1,972,086
1,972,192
need a cast syntax to access an old c api
I'm trying to write a glue function between two data types and I can't seem to get the compiler to be happy. On one side, I have a pointer to a chunk of data that is logically a n x 2 array, but is declared as: double* pData=new double[2*n]; On the other side, I have a c function that is declared as void Function(dou...
void Function(double data[][2], int n); double* pData = new double[2*n]; Function((double (*)[2])pData, n); Function parameters of the form T[] are identical to T* (not even T* const that some people expect). This is a special case for parameter types in both C and C++. So your double[][2] follows this rule, with T ...
1,972,099
1,972,123
Win API VirtualQueryEx Function,ERROR_BAD_LENGTH
Hi I try to call the VirtualQueryEx function to get some Information about Memory Protection, however my code gives me error 0x18 (ERROR_BAD_LENGTH) and i dont know whats wrong with my code; code snippet: PMEMORY_BASIC_INFORMATION alte; VirtualQueryEx(processhandle,(LPVOID) (address),alte,sizeof(PMEMORY_BASIC_INFORMATI...
alte needes to by declared as MEMORY_BASIC_INFORMATION not a pointer to one. MEMORY_BASIC_INFORMATION alte; VirtualQueryEx(processhandle,(LPVOID) (address),&alte,sizeof(MEMORY_BASIC_INFORMATION)); edit: Note its sizeof(MEMORY_BASIC_INFORMATION) not sizeof(PMEMORY_BASIC_INFORMATION). Actually, it's better to write thi...
1,972,186
1,972,294
Building my project with make
I'm working to improve the long languishing Linux build process for Bitfighter, and am having problems with make. My process is actually quite simple, and since make is (nearly) universal, I want to stick with it if I can. Below I've attached my current Makefile, which works, but clumsily so. I'm looking for ways to ...
Raw make doesn't really support any of these uses. make considers targets passed in on the command line to be different programs to be built, or different actions to take, and it has no concept of using two targets passed in to switch independent options for a single build. make also doesn't have any built in support f...
1,972,231
1,972,264
Question regarding libraries and framework
Sorry i'm a beginner,from what i know there are number of varieties of libraries and framework out there provided for the C++ language.My question is,when we create an application using the framework and libraries,do the users of the application need to install the framework or so so call the libraries on his/her PC??T...
It depends whether the library you are using is statically or dynamically linked. In the former case, it is part of the executable file that you distribute. In the latter case, it is an extra file (or set of files) with extensions such as .so or .dll, which you should distribute with your app.
1,972,239
1,972,272
Qt, Color Picker Dialog?
Is there a color picker dialog for Qt like the following? Also it needs to have a OnColorChanged signal which is called when ever the selected color changes. I want to give a live preview when they are changing the colors, that is why. Using google I could only find this one that was a triangle in side of a circle an...
QColorDialog does exactly what you want. (It is easy to find when you Ctrl-F through the list of Qt classes for "color")
1,972,403
1,972,424
stl::deque's insert(loc, val) - inconsistent behavior at end of deque vs other locations?
Using http://www.cppreference.com/wiki/stl/deque/insert as a reference, I was inserting values into a deque at certain locations. For example, if deque A was: a, b, d, e, g with an iterator pointing to d, i can: A.insert(iter, c); // insert val c before loc iter //deque is now a, b, c, d, e, g and the iter stil...
Performing an insert invalidates all existing iterators, so you will get unpredictable behavior (possibly a crash) by reusing the old iterator. Your workaround is the correct solution. Edit: Regarding your second question, you are missing braces after if (*iter == 'g'). In the future though, please put new questions in...
1,972,552
1,972,647
How to convert a static library project into a dll project in VS2005
When I create a project in vs2005. I can also create Win32->Win32Project. I can choose "console application" or "dll" or "static library" if I created a static library project. How can I convert it to dll project. I found in setting panel of the created project. General->Configuration Type, I can switch Static Library...
The way I've done this, and this may not be the "best" way, was to create a new project with the right settings (DLL in this case) and then create the stub methods with the wizards that I want to expose from the static library. Then you have two choices, you can leave the real code in the static library and just have...
1,972,722
1,972,859
Lua vs. XML for data storage
Many of us have been indoctrinated in using XML for storing data. It's benefits and drawbacks are generally known, and I surely don't want to discuss them here. However in the project I'm writing in C++, I'm also using Lua. I've been very surprised how well Lua can be used to store and handle data. Yet, this aspect of ...
This might not be the kind of answer you expected, but it might help you make your decision. Blizzard (WoW) uses XML to define UI. It's kinda like XAML in C#, just a lot less powerful and most addons just use XML to bootstrap the addon and then build UI in lua code. Also WoW actually stores addon "Saved Variables" in ....
1,972,735
1,972,746
C++ Programming Contests
I would like to test my C++ programming skill level by competing with others. What programming contests are there for C++?
There's Google Code Jam, but only once a year; TopCoder, with many more contests; and others listed here.
1,972,765
1,972,773
mmap problem, allocates huge amounts of memory
I got some huge files I need to parse, and people have been recommending mmap because this should avoid having to allocate the entire file in-memory. But looking at 'top' it does look like I'm opening the entire file into the memory, so I think I must be doing something wrong. 'top shows >2.1 gig' This is a code snippe...
No, what you're doing is mapping the file into memory. This is different to actually reading the file into memory. Were you to read it in, you would have to transfer the entire contents into memory. By mapping it, you let the operating system handle it. If you attempt to read or write to a location in that memory area,...
1,972,888
2,986,499
Large number of simultaneous long-running operations in Qt
I have some long-running operations that number in the hundreds. At the moment they are each on their own thread. My main goal in using threads is not to speed these operations up. The more important thing in this case is that they appear to run simultaneously. I'm aware of cooperative multitasking and fibers. Howe...
It's been 6 months, so I'm going to close this. Firstly I'll say that threads serve more than one purpose. One is speedup...and a lot of people are focusing on that in the era of multi-core machines. But another is concurrency, which can be desirable even if it slows the system down when taken as a whole. Yet conc...
1,972,953
1,972,967
using exit(1) to return from a function
linux gcc 4.4.1 C99 I am just wondering is there any advantage using the following techniques. I noticed with some code I was reading the exit number went up in value, as displayed in this code snippet. /* This would happen in 1 function */ if(test condition 1) { /* something went wrong */ exit(1); } if(test ...
exit() exits your entire program, and reports back the argument you pass it. This allows any programs that are running your program to figure out why it exited incorrectly. (1 could mean failure to connect to a database, 2 could mean unexpected arguments, etc). Return only returns out of the current function you're i...
1,973,471
2,089,723
vim - indentation of C++ constructor initialization list problem
I'm using vim 7.0. I want the following code be indented in the following way (initialization list in the same indentation as constructor): A::A() : a1(10), a2(10), a3(10) { } According to vim help this can be done by setting: set cino+=i0 But this setting yields (only a1 is indented correctly): A::A() : ...
According to documentation and a little experiment, the following could help: :set cino=i-s Seems to be indenting init list exactly as you wanted.
1,973,788
2,057,641
Tracking Lua tables in C
I have C++ objects and I have Lua objects/tables. (Also have SWIG C++ bindings.) What I need to be able to do is associate the two objects so that if I do say CObject* o1 = getObject(); o1->Update(); it will do the equivalent Lua: myluatable1.Update(); So far I can imagine that CObject::Update would have the followin...
I cant believe nobody noticed this! http://www.lua.org/pil/27.3.2.html A section of the Lua API for storing references to lua objects and tables and returning references for the purposes of being stored in C structures!!
1,973,815
1,973,879
Code compiles locally on g++ 4.4.1, but not on codepad.org (g++ 4.1.2)? (reference to reference problem)?)
I was writing a test case out to tackle a bigger problem in my application. I ended trying some code out on codepad and discovered that some code that compiled on my local machine (g++ 4.4.1, with -Wall) didn't compile on codepad (g++ 4.1.2), even though my local machine has a newer version of g++. Codepad calls this a...
A vector (or any STL container) of references is indeed a bad idea, as obvious when you simply look at requirements for element type T of any STL container (ISO C++03 23.1[lib.container.requirements]). It starts off by saying that "containers are objects that store other objects". We can stop right here, because a refe...
1,974,006
1,974,201
Calculate the gradient for an histogram in c++
I calculated the histogram(a simple 1d array) for an 3D grayscale Image. Now I would like to calculate the gradient for the this histogram at each point. So this would actually mean I have to calculate the gradient for a 1D function at certain points. However I do not have a function. So how can I calculate it with con...
I think you can calculate your gradient using the same approach used in image border detection (which is a gradient calculus). If your histogram is in a vector you can calculate an approximation of the gradient as*: for each point in the histogram compute gradient[x] = (hist[x+1] - hist[x]) This is a very simple...
1,974,301
1,974,308
Can you place a complex condition into a for loop?
while (status) for (int i = 0; i < 3; i++) Is the following syntactically correct: for (int i = 0; i < 3; i++ && status) I am trying to have the for loop break early if status is true.
Syntactically, you might want to use: for (int i = 0; i < 3 && status; i++) which is valid. Some consider it bad form though, as it leads to more complicated loops and annoyed maintenance programmers. Another alternative you might want to explore would be: for (int i = 0; i < 3; i++) { if (!status) { break; } }
1,974,487
1,974,494
Extreme big/small number programming
I am trying to do some extreme precise maths calculation of very big/small number. The very big number may have 10 - 50 digits and the very small number may have 10 - 50 decimal places. Can C++ do this? If not is there any other programming language that can handle this kind of number?
C++ can do it with a library, for example the GNU Multiple Precision Arithmetic library.
1,974,828
1,975,679
How do we tell if a C++ application is launched as a Windows service?
We have a console app which we launch from command prompt for debugging, but we also launch this as an NT service for production. Right now, the code has this logic: if (__argc <= 1) { assumeService(); } else { assumeForgound(); } Is there a better way to check how the process has been launched? We're an open sour...
Here's some code I created (seems to work nicely). Apologies for missing headers, #defines, etc. If you want to see the full version, look here. bool CArchMiscWindows::wasLaunchedAsService() { CString name; if (!getParentProcessName(name)) { LOG((CLOG_ERR "cannot determine if process was launched as se...
1,975,201
1,975,243
Generate all of the unique combinations of numbers that add up to a certain number
I am writing a program to try to solve a math problem. I need to generate a unique list of all of the numbers that add up to another number. For example, all of the unqiue combinations of 4 numbers that add up to 5 are: 5 0 0 0 4 1 0 0 3 2 0 0 3 1 1 0 2 2 1 0 2 1 1 1 This is easy to brute force in perl but I am wor...
This is called a partition problem and approaches are discussed here, here and here.
1,975,439
1,975,634
Capturing window output in another window
I am building a C++ (Qt) based application for controlling a flash based UI. Because the flash runtime leaks spectatular amounts of memory, we execute the UI as a .swf loaded in the standalone flash player separate from the command-and-control app written i C++. The C++ starts the flash player as an external process wi...
The Alt+Tab list shows top-level (no parent) windows that are visible and don't have the WS_EX_TOOLWINDOW extended style. So if you have two windows from two processes but you only want to see one in the Alt-Tab list (and on the task bar), then you have a few options: Add the WS_EX_TOOLWINDOW to one of the windows. R...
1,975,778
1,977,411
OpenGL antialiasing isn't working
I'm using the following code in order to antialias only the edges of my polygons: glHint(GL_POLYGON_SMOOTH_HINT, GL_NICEST); glEnable(GL_POLYGON_SMOOTH); But it doesn't work. I can force enable antialiasing by the nvidia control panel, and it does antialias my application polygons. With the code above, I even enabled ...
You need to ask for a visual/pixelformat with support for multisampling. This is an attribute in the attribute list you pass to glXChooseFBConfig when using GLX/XLib, and wglChoosePixelformatARB when using the Win32 API. See my post here: Getting smooth, big points in OpenGL
1,975,812
1,976,113
TI C2800 DSPs: troubleshooting linker problems between C++ and assembly code
I have a function sincos_Q15_asm() in assembly, in file sincos_p5sh.asm with directives as follows: .sect ".text" .global _sincos_Q15_asm .sym _sincos_Q15_asm,_sincos_Q15_asm, 36, 2, 0 .func 1 The function works fine when I test it by itself (assembly only), but when I try to link to it, I get a linker error: u...
D'oh! I figured it out -- I was using C++ and forgot to include the extern "C" declaration for my function: extern "C" { extern void sincos_Q15_asm(int16_t theta, int16_t* cs); }
1,975,916
1,975,961
Should C++ programmer avoid memset?
I heard a saying that c++ programmers should avoid memset, class ArrInit { //! int a[1024] = { 0 }; int a[1024]; public: ArrInit() { memset(a, 0, 1024 * sizeof(int)); } }; so considering the code above,if you do not use memset,how could you make a[1..1024] filled with zero?Whats wrong with memset in C++? ...
The issue is not so much using memset() on the built-in types, it is using them on class (aka non-POD) types. Doing so will almost always do the wrong thing and frequently do the fatal thing - it may, for example, trample over a virtual function table pointer.
1,975,951
1,976,175
Beneficial to limit scope of Qt objects?
Qt objects which are allocated with new are pretty much handled for you. Things will get cleaned up at some point (almost always when the parent gets destructed) because Qt objects have a nice parent child relationship. So my question is this: given that some widgets exist for the life of the application, is it conside...
In your first example, menu will be deleted when this (i.e. the MyMainWindow object) is... which is probably not what you want, since that means that if contextMenu() is called more than once, multiple unseen old QMenu objects will build up in memory, and might eventually use up a lot of RAM if the user never closes/de...
1,975,992
1,976,026
Accessing native C++ data from managed C++
I have an native C++ library which makes use of a large static buffer (it acquires data from a device). Let's say this buffer is defined like this: unsigned char LargeBuffer[1000000]; Now I would like to expose parts of this buffer to managed C++, e.g. when 1000 bytes of new data are stored by the library at LargeBuff...
Managed C++ can access the unmanaged memory just fine. You can just pass in the pointer and use it in managed c++. Now, if you want to then pass that data into other .NET languages, you'll need to copy that data over to managed memory structures or use unsafe code in C#
1,976,414
1,976,612
How do I use a class as a value to be used on set::find()? - C++
So I'm working on a project and I have to use the set library on class objects. Those objects have many attributes, ID being one of them. What I wanted to do was search for an object inside a "set" by its ID. The problem is set only has find and I don't know how to search for an ID this way since I'd have to use find(c...
You need to create a constructor for your class that takes int as its only argument. Doing so allows implicit conversion from int to your class, making it possible to call std::set::find(int), as requested. For example: #include <iostream> #include <set> class Foo { public: /* Normal constructor */ Foo(cons...
1,976,453
1,976,484
Format string into scientific notation
I have a string that looks like this: "0.4794255386042030002732879352156" which is approximately the sin(0.5). I would like to format the string to look a much nicer "4.794255386042e-1" How can I achieve this? Remember I am dealing with strings and not numbers (float, double). Also I need to round to keep the number ...
Something like this: #include<iostream> using namespace std; int main() { char *s = "0.4794255386042030002732879352156"; double d; sscanf(s,"%lf",&d); printf("%.12e\n",d); return EXIT_SUCCESS; } Output: # g++ a.cpp && ./a.out 4.794255386042e-01