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
6,921,091
6,921,098
error c2059: syntax error: '('
I don't understand this error it's written the exact same in the tutorial but my one generates an error. #include "drawEngine.h" #include <Windows.h> #include <iostream> using namespace std; DrawEngine::DrawEngine(int xSize, int ySize) { screenWidth = xSize; screenHeight = ySize; //set cursor visibility ...
I think you meant to write gotoxy(0, y) instead of goto(0, y). goto is a C++ keyword which jumps to a label, for example: home: goto home; // Loops forever Don't use it, though, it's too easy to create spaghetti code.
6,921,196
8,549,618
In Boost::Program_Options, how to set default value for wstring?
My code below did not work: wstring config_file; // Declare a group of options that will be // allowed only on command line po::options_description generic("Generic options"); generic.add_options() ("help,h", "produce help message") ("config,c", po::wvalue<wstring>(&config_file)->default_value(L"DXDrv.cfg"), "...
Long-winded explanation: This is because the underlying typed_value type in program_options tries to do a lexical cast from wchar to char in setting the m_default_value_as_text private member. For whatever reason, the basic_string type does not have the necessary functions to create the correct template types. Luckily...
6,921,295
6,921,467
Dual emission of constructor symbols
Today, I discovered a rather interesting thing about either g++ or nm...constructor definitions appear to have two entries in libraries. I have a header thing.hpp: class Thing { Thing(); Thing(int x); void foo(); }; And thing.cpp: #include "thing.hpp" Thing::Thing() { } Thing::Thing(int x) { } void Th...
We'll start by declaring that GCC follows the Itanium C++ ABI. According to the ABI, the mangled name for your Thing::foo() is easily parsed: _Z | N | 5Thing | 3foo | E | v prefix | nested | `Thing` | `foo`| end nested | parameters: `void` You can read the constructor names similarly, as below. Not...
6,921,395
6,943,795
Cannot get text with Unicode (including Chinese) characters to line up with MFC using a CRichEditCtrl
I have a CRichEditCtrl (actually I have a class that is a subclass of a CRichEditCtrl, a class that I defined) that is populated by many lines of text with both horizontal and vertical scroll bars. The purpose of this control is to display a string that is searched for in a larger text along with n characters to the ri...
See http://msdn.microsoft.com/en-us/library/bb787940(v=vs.85).aspx, in particular the cTabCount and rgxTabs members of the PARAFORMAT (or PARAFORMAT2) structure, which allow you to set tabstops.
6,921,695
6,925,256
How can I build a C++ project with multiple interdependent subdirectories?
I have a C++ project where I've used directories as more of an organizational element -- the way one might use packages in Java or directories in PHP. Directories are not intended to be self-sufficient elements, but rather just a way of organizing the whole of the project and keeping me from being overwhelmed by sourc...
Since the directory structure in your project is just there to keep your files organized, one approach is to have a CMakeLists.txt that automatically finds all sources files in the src directory and also adds all directories as include directories that have a header file in them. The following CMake file may serve as a...
6,922,093
6,927,782
gdbinit, pretty-printers, and relative directories?
In my ~/.gdbinit I would like to be able to reference the GDB python pretty-printers installed in my home directory via relative path: python import sys # 1, works sys.path.insert(0, '/home/<username>/.gdb_viz') # 2, doesn't work # sys.path.insert(0, '~/.gdb_viz') # 3, doesn't work # sys.path.insert(0, '.gdb_viz') from...
Not tested, but should work: python import sys, os sys.path.insert(0, os.getenv('HOME') + '/.gdb_viz')
6,922,696
6,922,751
OOP C++: Which pattern: 2 classes with the partly same methods
Problem description: I need to implement 2 classes like following: class A1 { common_method1(); common_method2(); foo1(); }; class A2 { common_method1(); common_method2(); foo2(); }; foo1() and foo2() has different logic. foo1() and foo2() may have different args and return values. common methods are the same O...
I think this is definitely a standard inheritance pattern. Create a base class Parent, which implements common_method1 and common_method2. Create classes A1 and A2 which inherit from Parent. If you need to do some special casing in one of the common_method1 or common_method2 methods in either A1 or A2, make the methods...
6,922,723
6,923,113
Anonymous enum classes
Is is possible to write a anonymous enum class and then comparing what it contains? Eg. enum class { APPLE, BANANA } fruitType; // ... if (fruitType == fruitType::APPLE) // ...
No, fruitType is a variable (despite Type in the name). You cannot use a variable name to access things about its type. The idea with enum class is that the values are not visible outside the definition unless you prefix them with the type name. If the type doesn't have a name, this will be difficult!
6,922,862
6,926,482
ISO C++ draft - 3.4.2/3 - Argument Dependant Name Lookup
A point from the ISO C++ draft (n3290): 3.4.2/3 Argument Dependant Name Lookup: Let X be the lookup set produced by unqualified lookup (3.4.1) and let Y be the lookup set produced by argument dependent lookup (defined as follows). If X contains a declaration of a class member (#1) or a block-scope function decl...
I think this code covers all the cases (also available at http://ideone.com/CbyJv). If you don't select C++0x in ideone, then case #2 is allowed (but gcc 4.5.2 catches it). #include <iostream> // ::f void f (int i) { std::cout << "::f\n" ; } // Simple case void OK1() { f (99) ; // Calls ::f } // Argument-dependend...
6,922,912
6,922,933
Linking error when upgrading from lua 4.0.1 to 5.1.4
I'm working on a really old source code (compiled in Red Hat). Before it had lua-4.0.1 so I just compiled the latest lua (lua-5.1.4) and installed it in the same directory as the old one. The implementation isn't very big so there wasn't much to change except a few function names and I had to include "lauxlib.h" to get...
Place -ldl at the end of the liner command. The order is important. The linker searches for libraries fulfilling an unreferenced symbol only in libs which are standing more right on the command line. Your new liblua.a now uses dlopen and friends, while the older didn't. Since -ldl is left of -llua, the linker does not...
6,922,949
6,923,139
Choosing which main function to use in Visual C++ 2010
I'm porting a C++ application from Unix and the original developer created several files with main() functions, then use Makefile to choose which main() to use. How do choose which file contains the main() function in Visual C++ 2010? Currently, when I compile I get a linker error due to duplicate main() symbols. The ...
Multiple main functions mean that the original code does not create a single executable, but rather a set of them. You should figure out what parts belong to each one of the executables (read the Makefile) and then create different projects inside the solution one for each one of the executables (do the same for the li...
6,923,299
6,923,359
What's the relationship between C++ template and duck typing?
To me, C++ template used the idea of duck typing, is this right? Does it mean all generic types referenced in template class or method are duck type?
To me, C++ template used the idea of duck typing, is this right? No, C++ templates are used to implement generic code. That is, if you have code that can work with more than one type, you don't have to duplicate it for each type. Things like std::vector and std::list are obvious examples of this in action. C++ templa...
6,923,340
6,923,386
Storing string with Japanese text and writing to a file
I want to store a Japanese text in a string and write it to a file. I am totally unfamiliar with encoding and there are a lot of data types like wchar_t and wstring in C++ which appear confusing to me. How can I do this? I am trying to create a well-formed XML file with some CDATA content being Japanese.
Ignore the complexities and pitfalls of wide strings altogether; and ensure that the data you are dealing with is encoded using UTF-8 instead. In C++, UTF-8-strings can be handled just like extended ASCII strings; unless you happen to actually manipulating them (chopping them up, counting characters, things like that)....
6,923,391
6,924,412
local mem on opencl hardware
I've been wondering, is there a way to estimate the mount of shared mem on the different GPGPU's without going out and buying the cards? I currently have a GTS 330M with 16K shared mem in my laptop and a GTX 480 with 16K + 32K = 48K shared mem. I would like to know if getting a tesla card would give me more shared m...
For NVIDIA hardware, the shared memory configuration of every CUDA/OpenCL capable card is described in Appendix F of the CUDA 4.0 programming guide. To answer your question about a Ferm Telsa card, it has the same shared memory configuration as your GTX 480 - 16kb or 48kb of shared memory, user selectable at runtime.
6,923,574
6,923,764
What can cause segmentation faults in C++?
I noticed there's not question with a list of common causes of segmentation faults in C++, so I thought I'd add it. Naturally it's community Wiki, since there's no one correct answer. I think this might be useful for newer programmers learning C++, feel free to close it if you disagree.
Segmentation fault is caused by bad accesses to memory, only if your OS has a MMU (Memory Management Unit). Otherwise, you won't get it but only strange behavior. The virtual memory (the entire memory accessible to you = 2^(sizeof(pointer_type)*8) (ie: 2^num_bits_in_pointer_type)) is mapped to physical memory in units ...
6,923,641
6,924,192
does boost::wait and boost::condition have to share the same mutex object
boost::condition_variable cond; boost::mutex mutex; //thread #1 for(;;) { D * d = nullptr; while( cb.pop(d) ) //cb is a circular buffer and manage is own mutex/lock internally { //...do something with d } boost::unique_lock<boost::_mutex> lock( mutex ); cond.wait( mutex ); } //thread...
You can have as many locks as you want, but you'll get race conditions unless both the pop and the push are protected by the same mutex as the wait and the notify (and the the lock is not freed between the decision to wait and the actual wait). The standard idiom is: // thread #1 // ... { boost::unique_lock<boos...
6,923,668
6,923,712
Is it possible to specify a function directly in a struct declaration in C++?
For example: struct Foo { int bar; int (*baz)(int); }; int testFunc(int x) { return x; } Foo list[] = { { 0, &testFunc }, { 1, 0 } // no func for this. }; In this example, I'd rather put the function directly into the list[] initializer rather than using a pointer to a function declared elsewhere...
If you mean something like: Foo list[] = { { 0, int (*)(int x) { return x;} }, { 1, 0 } // no func for this. }; then, no, it's not possible. You're talking about anonymous functions, something C++ doesn't yet support (as of August 2011). C++0x is adding support for lambda functions, which is pretty much the sa...
6,923,722
6,923,755
How do I call the base class constructor?
Lately, I have done much programming in Java. There, you call the class you inherited from with super(). (You all probably know that.) Now I have a class in C++, which has a default constructor which takes some arguments. Example: class BaseClass { public: BaseClass(char *name); .... If I inherit the class, it gi...
You do this in the initializer-list of the constructor of the subclass. class Foo : public BaseClass { public: Foo() : BaseClass("asdf") {} }; Base-class constructors that take arguments have to be called there before any members are initialized.
6,923,735
6,923,790
Breakpoints in VisualStudio
How do breakpoints in visual studio work? I'm asking this because I have some inline functions declared in the class header, and whenever I set a breakpoint in one of them, I think the IDE also puts breakpoints to wherever the function is called. Which of course makes sense, but how exactly is it done internally?
The function you are placing breakpoint in, are inline, and that's why debugger is smartly misplacing them somewhere else. It may be you are debugging a non-Debug build. Try Disabling all optimizations Make function non-inline Your question doesn't demand this, but you can read here how breakpoints are implemented.
6,923,961
6,924,146
source file and header in c++
I have a question about source file and header in c++. I have a header which is used to declare the functions. And I implement these functions in C++. Now I need to use these functions in other files. Should I include both source file and header file in order to use these functions?
The basic compilation model used by (C and) C++ is thus: You put declarations that are to be shared between source files into header files. The source files that need to access those declarations then include these header files. When compiling, the preprocessor will (recursively) replace #include directives with the...
6,924,113
6,924,169
How use nested enum of one class as a nested enum of another?
The code bellow will give compile error on line enum en = A::en; but it describes what I want to do (to make nested enum of A to be nested enum of B as well). #include <iostream> using namespace std; struct A { enum a_en{X = 0, Y = 1}; }; struct B { enum b_en = A::a_en; //syntax error }; int main() { cout <...
Put the enum in a base class that both A and B can inherit from.
6,924,195
6,924,332
Get DLL path at runtime
I want to get a dll's directory (or file) path from within its code. (not the program's .exe file path) I've tried a few methods I've found: GetCurrentDir - gets the current directory path. GetModuleFileName - gets the executable's path. So how can i find out in which dll the code is in ? I'm looking for something simi...
You can use the GetModuleHandleEx function and get the handle to a static function in your DLL. You'll find more information here. After that you can use GetModuleFileName to get the path from the handle you just obtained. More information on that call is here. A complete example: char path[MAX_PATH]; HMODULE hm = NU...
6,924,267
6,925,065
How to use Unicode font on Windows Mobile 6.x
I have a Window Mobile application that I'd like to display Arabic characters in. I have tried copying MS Arial Unicode to the Fonts folder and the Windows folder (and then restarting, of course!). I then marked the dialog font as MS Arial Unicode in the .rc file and (when that didn't work) also manually setting the fo...
Try calling AddFontResource() with the file you copied, and perform a reset.
6,924,583
6,925,255
Managing library dependencies using git
I have a project which is built for multiple OSes(Linux and Windows for now, maybe OS X) and processors. To this project I have a handful of library dependencies, which are manly external but I have a couple of internal ones, in source form which I compile(cross-compile) for each OS-processor combination possible in my...
An alternative, which would still follwo your project, would be to use git-annex, which would allow you track header files, while keeping binaries stored elsewhere. Then each git repo can be added as a submodule to your main project.
6,924,754
6,925,201
Return Type Covariance with Smart Pointers
In C++ we can do this: struct Base { virtual Base* Clone() const { ... } virtual ~Base(){} }; struct Derived : Base { virtual Derived* Clone() const {...} //overrides Base::Clone }; However, the following won't do the same trick: struct Base { virtual shared_ptr<Base> Clone() const { ... } virtual ~Bas...
You can't do it directly, but there are a couple of ways to simulate it, with the help of the Non-Virtual Interface idiom. Use covariance on raw pointers, and then wrap them struct Base { private: virtual Base* doClone() const { ... } public: shared_ptr<Base> Clone() const { return shared_ptr<Base>(doClone()); }...
6,924,790
6,928,015
opencv create mat from camera data
in my programm I have function that takes the image from camera and should pack all data in OpenCV Mat structure. From the camera I get width, height and unsigned char* to the image buffer. My Question is how I can create Mat from this data, if I have global Mat variable. The type for Mat structure I took CV_8UC1. Mat ...
Unfortunately, neither clone() nor copyTo() successfully copy the values of width/height to another Mat. At least on OpenCV 2.3! It's a shame, really. However, you could solve this issue and simplify your code by making the function return the Mat. This way you won't need to have a global variable: Mat takePhoto() { ...
6,924,846
6,925,112
C++ How to dynamically select a file handle according to the type of data that should be written?
I've got a class outputInterface; that should handle the output (to files) of some data. The data is contained in objects of some custom classes, say dataClassA and dataClassB, that all derive from a common base class dataClassBase. Now I want the data to be written to different files according to its type. So data of ...
Try something like this: #ifndef OUTPUTINTERFACE?H #define OUTPUTINTERFACE?H #include <string> #include <fstream> #include <map> class DataClass { public: virtual bool WriteData(std::ofstream& FStream) = 0; }; class DataClass1 : public DataClass { virtual bool WriteData(std::ofstream& FStream) ...
6,926,145
6,930,247
Apple Push notification service c++ / boost does not connect
I'm currently working on a server-side push notification service with Apple push notification. I'm working with boost asio. Here's my code : void IPhonePush::connection() { std::cout << "Push iPhone connection" << std::endl; std::cout << getCertif() << std::endl; m_context.set_options(boost::asio::ssl:...
I'm currently wondering if the problem is not coming from resolving the dns into an ip to connect. I don't think this is the cause. Here is a sample program showing synchronous resolve and connect working just fine. mac:stackoverflow samm$ cat push.cc #include <boost/asio.hpp> #include <iostream> int main( unsign...
6,926,433
6,926,473
How to shuffle a std::vector?
I am looking for a generic, reusable way to shuffle a std::vector in C++. This is how I currently do it, but I think it's not very efficient because it needs an intermediate array and it needs to know the item type (DeckCard in this example): srand(time(NULL)); cards_.clear(); while (temp.size() > 0) { int idx = ...
From C++11 onwards, you should prefer: #include <algorithm> #include <random> auto rng = std::default_random_engine {}; std::shuffle(std::begin(cards_), std::end(cards_), rng); Live example on Coliru Make sure to reuse the same instance of rng throughout multiple calls to std::shuffle if you intend to generate differ...
6,926,538
6,926,565
how to create template class in another class with out default constructor
I have the following template class template <typename threadFuncParamT > class ThreadPool { // number of threads to be launced initially and added to thread pool. ThreadPool( pThreadFunc pFunction, RtsInt16_t minThreads, RtsInt16_t maxThreads, RtsInt16_t maxExecCount); }; Now i want to use object of another c...
Assuming you mean "as I don't have default constructor in ThreadPool: MyClass::MyClass() : pool( &thrdFunc, 7, 42, 12 ) { } Assuming you mean "as I don't have default constructor in MyClass: MyClass has a default constructor as long as you either provide your own or you do not provide any other constructor. As it ...
6,926,877
6,926,927
Passing user input to function with char* parameters
I get the following errors with my code. cannot convert parameter 1 from 'std::string' to 'char * no operator found which takes a right-hand operand of type 'const char * Can someone tell me what I'm doing wrong in the menuSelection function below? The point of it is if a user selects 1 from the menu options, the pr...
cin >> lastName.c_str() >> firstName.c_str() >> courseName.c_str() >> letterGrade; I don't think you really want to do that. c_str() is to turn a regular C++ std::string into an old C-style "string" for use with functions that expect such a beast. If you're trying to input a regular C++ string, you should change t...
6,926,918
6,926,952
Sending Large amouts of data from Unmannaged C++ application to Managed C#
we have two applications, a native C++ application and a managed C#/WPF UI that creates input for, executes & reads output generated by the native application. Currently, communication between the two is done with XML & plain txt files. However, the amount of output data is quite large & we are looking for a better app...
You could try a named pipe http://www.switchonthecode.com/tutorials/interprocess-communication-using-named-pipes-in-csharp
6,926,922
6,926,948
Call one method of inherited classes without those virtual prototype
I have some base class A, and some number of inherited classes: class B : public A class C : public A class D : public A I have function with parsing some config file, which use name in config call: void do_smth<B>(...); void do_smth<C>(...); void do_smth<D>(...); I have map<A*> objs; and in those functions happend: ...
So you have A* a; and don't know what type it is. Try dynamic_cast: B* b = dynamic_cast<B*>(a); if ( b ) return b->value(); //C and D the same way
6,926,930
6,927,125
++it or it++ when iterating over a map?
Examples showing how to iterate over a std::map are often like that: MapType::const_iterator end = data.end(); for (MapType::const_iterator it = data.begin(); it != end; ++it) i.e. it uses ++it instead of it++. Is there any reason why? Could there be any problem if I use it++ instead?
Putting it to the test, I made three source files: #include <map> struct Foo { int a; double b; char c; }; typedef std::map<int, Foo> FMap; ### File 1 only ### void Set(FMap & m, const Foo & f) { for (FMap::iterator it = m.begin(), end = m.end(); it != end; ++it) it->second = f; } ### File 2 only ### void S...
6,926,998
6,927,239
Loading files that meet certain criteria into hidden buffers in vim
I'd like to do some code refactoring in vim. I have found the following gem to apply transformations to all buffers. :dobuf %s/match/replace/gc My code is layed out with the root directory having a directory for the dependencies and a build directory. I want to load all .cc , .h and .proto files from ./src ./include an...
You can use :argadd to add the files you need to vim's argument list. This will load them as inactive buffers (you can see them afterwards with an :ls. In your case, it might look like this: argadd src/**/*.cc argadd src/**/*.h argadd src/**/*.proto And so on, for the include and tests directories. You might want to m...
6,927,116
6,927,228
What is the best tool to plot intermediate results of my c++ code?
I am developing algorithms for embedded systems and implementing them in c++ code. Prior to testing the c++ code on target, I have to test the algorithms on a PC to make sure the mathematics is correct. To do this, I create a mex file so that I can verify the output in Matlab. The system with mex files works well, but ...
There are many plotting packages out there (GNUPlot, XFig, MATLAB, Excel, and so on) each with their own strengths and weaknesses. But if you have access to MATLAB and are happy with the results why not simply output the data from your program to a .csv file and load it into MATLAB? Then you can plot it using MATLAB wi...
6,927,650
6,927,834
Customizing CFileDialog error messages
It would be nice if there is a way to customize the CFileDialog error messages. For example, Entering an invalid drive in the File name edit box causes an error message like below. I want to show a different error here. Is it possible without subclassing CFileDialog? It is also fine if the dialog returns instead of sh...
if it's ok just to modify the dialog, you can install a hook SetWindowsHookEx with WH_CBT.
6,927,659
6,949,707
Procedure entry point RegCloseKey not found in dynamic link library kernel32.dll
I have a program written in VC++, and I am trying to install it on Windows server 2008. Initially it gave errors about api-ms-win-core-xx-l1.dll files were missing. So, I copied over my Windows 7 dlls to the application folder. But, now it gives an error saying "Procedure entry point RegCloseKey not found in dynamic ...
So, when I compiled the program for Windows 2003 platform(using libraries meant for Windows 2003), and it worked fine on this machine. I was trying to use Windows 7 libraries because it is similar to Windows server 2008.
6,927,885
6,928,359
spawning thread using static function using TBB in C++
I want to use TBB threads in C++ and want to use "tbb_thread" API. for example i have static function in class as below template < typename threadFuncParamT > class ThreadWrapper { public: static int ThreadRoutineFunction(void* pParam); }; I want to use tbb_thread API to spawn a thread with "ThreadRoutineFunction"...
It sounds like your question is really "how do I get a pointer to a static member function?" C++ doesn't officially have a way to do that. However, according to the C++ FAQ (the Note in question 2), "pointers-to-static-member-functions are usually type-compatible with regular pointers-to-functions." Your options are: ...
6,927,895
6,928,085
Dynamic downcast on private inheritance within private scope
A tweak on this question that I've run into. Consider: class A {}; class B : private A { static void foo(); }; void B::foo(){ B* bPtr1 = new B; A* aPtr1 = dynamic_cast<A*>(bPtr1); // gives pointer B* bPtr2 = dynamic_cast<B*>(aPtr1); // gives NULL } Since aPtr1 is, in fact, of type B*, and since we've got...
5.2.7 (ISO/IEC 14882, 12/29/2003) is pretty explicit on this point: [about the expression dynamic_cast<T>(v)] If T is “pointer to cv1 B” and v has type “pointer to cv2 D” such that B is a base class of D, the result is a pointer to the unique B sub-object of the D object pointed to by v. [... bla bla about cv1 and...
6,927,896
6,928,208
Boost.Bind with Function and Python
I get some compile time errors and I can't understand why that is. The following code will refuse to compile, giving me the following errors: error C2664: 'void (PyObject *,const char *,boost::type *)' : cannot convert parameter 1 from 'const char *' to 'PyObject *' error C2664: 'void (PyObject *,const char *,boost:...
boost::python::call_method consists of several overloaded functions that take a different number of arguments, defined like this: template <class R> R call_method(PyObject* self, char const* method); template <class R, class A1> R call_method(PyObject* self, char const* method, A1 const&); template <class R, class A1,...
6,928,012
7,237,295
How to extend C++ HTTP server with FastCGI applications?
I am writing a C++ HTTP server. But because developing in C++ is slower as for example in PHP I want to also support FastCGI applications (PHP via FastCGI, Python via FastCGI, etc.). So I want to use something similar to mod_fcgi (for Apache). Does someone know a good C++ FastCGI library (not for applications but for t...
I could not find a FastCGI client, so I wrote it myself. It was a lot of work, but i succeeded :) It is a lot faster then plain old CGI (duh!).
6,928,242
6,949,619
Get __TEXT and __DATA Dyld address mapping from within an executable
To find the dyld address mapping of __TEXT and __DATA for my mach-o executable I set the environment variable DYLD_PRINT_SEGMENTS=1. This logs on the console where in memory the executable is mapped. However, I need to find the address mapping of __TEXT and __DATA internally from within my executable. Is there some API...
You can obtain this information with the getsectbyname() function from the <mach-o/getsect.h> header.
6,928,431
6,928,689
C++ interface design around shared library boundaries
Suppose I have two projects. One is an application and the other is a shared library that contains common, reusable code that could be used by more than just this application. My application uses STL, and my shared library also uses STL. The first problem here is that my shared library is using STL. If I ever build a n...
One of the pros of the const char* approach is that your library will also be callable from C, and hence from a lot of other laguages interfacing to C as well (pretty much everything out there). This alone is a very interesting selling point. However, if you write and maintain both libraries, and they will be used in C...
6,928,441
6,928,530
Qt Creater _Debug Constant
I want to use the _Debug Constant in Qt Creater. But don't get any output. Seems like Qt Creater don't set the _Debug Constant on debugging. int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); #ifdef _debug qDebug("Test"); qDebug() << "Test"; argv* = new char[2]{ "c:\injection.dll", "...
I'm not sure if Qt defines this by default, but in any case, you can add it yourself to your .pro file: debug:DEFINES += _debug
6,928,554
12,467,276
Calling member variable's virtual function within destructor causes seg fault
I'm having a very odd problem that I'm hoping someone has come across. class Letter { public: Letter() virtual ~Letter() virtual std::string get() const = 0; }; class A : public Letter { public: A() ~A() virtual std::string get() const { return "A"; } }; class Board { public: Board(){} ~...
I didn't realize an object was being passed to setLetter() from the stack, so A was going out of scope before b. Board b; A a; b.setLetter(&a);
6,928,656
6,931,225
Handle two consequent SIGTERMs
There is a daemon which has two threads: th1, th2. th2 reads a socket using read(2). If I kill the daemon with SIGTERM, th1 catches and handles the signal (sets the termination flag), after that the daemon destructor get called, it calls pthread_kill(th2, SIGTERM). However, the second thread does not receive SIGTERM, s...
Unix does allow sending multiple consecutive signals to a process, although if the signals are sent too close together, or an additional signal was been sent to the process before an already pending signal was delivered, then multiple signals can be concatenated into a single signal event. Also keep in mind that while ...
6,928,706
6,928,863
External C++ Libraries Linking Problems
I have been facing difficulties, now and then, linking my C++ projects with external libraries (e.g. Boost, wxWidgets, Gtkmm). Is there a way to incorporate these external libraries into the compiler (GNU G++ in my case, winXP SP3) so that the compiler can take them as part of it just like with C++ STL?
To link with a library (Taking example of Boost Libs and g++ compiler): Compiling the source with correct include files 1) g++ -I /path/to/boost_dir -c code.cpp 2) g++ -L/path/to/your/boost/shared/libs -lboost_regex -o executable code.o For the linking part I have taken example of boost regex library A full ex...
6,928,910
6,961,801
Open MPI program not working when distributing processes among multiple hosts
My test program works fine when I run multiple processes on a single machine. $ ./mpirun -np 2 ./mpi-test Hi I'm A:0 Hi I'm A:1 A:1 sending 11... A:1 sent 11 A:0 received 11 from 1 all workers checked in! When I run the same program on multiple hosts the process is spawned on each host, but MPI_Send never returns. $ ....
I ended up upgrading to 1.5.3 on A and installing 1.5.3 on C. I'm not sure whether it was the upgrade, or an issue with B, but everything is working now. For reference: original setup: node A (arch linux, Open MPI 1.4.3), node B (ubuntu, Open MPI 1.4.3) working setup: node A (arch linux, Open MPI 1.5.3), node C (arch ...
6,928,913
6,962,492
Explain blank class functions in C++
class forums : public master{ public: forums() : next(0),prev(0) {} } Please Explain what exactly does the functions next(0) and prev(0) are meant? What does seperation of function with a comma (,) indicates? what's the effect of empty braces {}, next to these functions? I am a beginner in C++, and trying to figu...
Short answer That is a constructor with an empty body, and a member initialisation list that initialises two data members to the value 0. i.e. class-name([ ctor-args ]) [ : member-init-list ] { [ ctor-body ] } where member-init-list is member-name(args) [, member-name(args) [, ... ] ]. (Note: not actual C++ lexical g...
6,928,957
6,929,246
Finding Time Connected in Seconds
When someone connects to my TCP Server, I log the time they connected using System.DateTime dt = System.DateTime.Now; Then when I need to find how long they have been connected, I do... foreach (KeyValuePair<string, System.DateTime> pair in playerList) { System.DateTime curTime = System.DateTime.Now; ...
You don't have to cast to float, as you are using the BinarryWirter the Write method can take any integral type: double, float, int.., So: writer.Write((DateTime.Now.Subtract(pair.Value)).TotalSeconds);
6,929,239
26,475,484
Catch statements are being completely ignored
I've run into a situation with some code I inherited... honestly, I believe the code is written correctly, but this error still seems to manifest. I'll quickly note that the code is cross-compiled from linux to LynxOS, I'm not sure if that can have anything to do with the error. Basically, in one specific case: try { ...
Since the catch (...) clause didn't catch the exception, my answer does not solve the OP's problem. But for others that found this question on SO, maybe my answer is useful, because it explains why the first catch failed. I had a similar issue where my catch(const std::exception& ex) was just not working. It turned ou...
6,929,334
6,929,385
Is there native XmlReader equvalent API in C++ on Windows?
On Linux platforms I like libxml2 reader API which is based on C#'s XmlReader::Read and reads one node/attribute at a time without actually building DOM tree. Now, I'm in need of native Windows C++ XML parsing library. MSXML instantly comes to mind. Is there MSXML API allowing to read one node at a time, without buildi...
Take a look at another Microsoft's XML parser XmlLite: a non-cached, forward-only parser (that delivers a pull programming model) and a non-cached, forward-only XML generator
6,929,626
6,929,718
CUDA - copy to array within array of Objects
I have a CUDA application I'm working on with an array of Objects; each object has a pointer to an array of std::pair<int, double>. I'm trying to cudaMemcpy the array of objects over, then cudaMemcpy the array of pairs to each of the objects, however this is giving me all kinds of grief. It crashes attempting to copy...
My CUDA experience is only in its infancy, but I believe the error is like this: cudaMalloc is a host function that wants to write the pointer into host memory. However, you are passing to it a pointer in device memory! To fix this, you should first create the device pointers and fill them into your host object structu...
6,929,648
6,929,792
Would a user be required to re-compile, if only non-virtual, non-overloading member functions were added to a class?
This is just a theoretical question. I've run into a similar problem in the COM world and wondered if this is also applicable in the C++ world. I'm also aware that I could avoid this problem with the Pimpl Idiom. Suppose I had a class A version 1. I shipped the header file and the library file to the clients. Then one ...
There are no pitfalls that I'm aware. The concept you're describing is called binary compatibility. Because version 2 of class A is still binary compatible (as far as I'm aware) with version 1 of class A, then no recompile is required. The KDE Techbase article has a decent set of guidelines (with examples) to follow f...
6,929,670
6,931,078
Should one avoid using recursive call in C/C++?
Should one avoid using recursive call of functions in C/C++? I work on machine learning/data mining, so it is very critical for me to make my code scalable. When I was using Java, I avoided using recursive call as much as possible because I often got my call stack overflowed. Although there are options to control the a...
The call stack in C & C++ is kind of like the vtable in C++ in one respect - it's not mentioned in the standard as far as I know, i.e., that implementation is not mandated, but for all practical purposes, it's almost always implemented that way. Granted there are some esoteric architectures, especially in the embedded ...
6,929,779
6,929,837
Logging framework for mixed C#, managed C++, and unmanaged C++ application
Specific Background: I have a Word Add-In written in C#. This Add-In calls a plugin developed for another application (EndNote) written in C++, which is further divided into managed and unmanaged code. The C# code is run from one process, while the C++ code is run from another. Furthermore, the C++ code is multithreade...
I would pick a framework for C# and one for C++ (have you consider log4cplus?) and decide which one can be easily adapted so that its log output is written to the other framework. Which one to pick depends on the structure of your code ("who knows whom?").
6,929,813
6,930,573
Streaming Real and Debug Data To Disk in C++
What is a flexible way to stream data to disk in a c++ program in Windows? I am looking to create a flexible stream of data that may contain arbitrary data (say time, average, a flag if reset, etc) to disk for later analysis. Data may come in at non-uniform, irregular intervals. Ideally this stream would have minimal o...
It is probably better to use an existing file format rather than a custom one. First you don't reinvent the wheel, second you will benefit from a well tested and optimized library. HFD5 seems like a good bet. It is fast and reliable, and easy to read from Matlab. It has some overhead but it is to allow great flexibilit...
6,929,927
6,930,091
Best way to draw scatter plot with lots of data points in C++ using OpenGL
I'm writing a program in C++ that acquires 4 dimensional points data over a UDP socket and then plots the data in 6 separate 2D scatter plots. For example if we name the dimensions: A,B,C,D the six 2d plots would be AxB, AxC, AxD, BxC, BxD, and CxD. Over the course of a few hours the program accrues ~50K points. Curr...
Using Vertex buffer Objects can increase speed rendering, because the geometry to draw can be stored directly in the graphic card memory. However, in your case, if the data always changes, I cannot tell you if this method will be faster than immediate mode because you may have to reconstruct the Vertex Array Object eac...
6,929,957
6,930,469
MVC approach with C++
I have been learning PHP MVC pattern and it is pretty cool. have almost finished app and I can see how mess you can make a code without good design. Now can MCV be applied to C++ apps? Where does Plugin manager/Plugins go if that is even possible?In model or controller? Thanks! EDIT: I mean C++ with GUI toolkit like Q...
how do you actually implement it in C++ make classes in charge of rendering know nothing about application details. Call them SomethingView classes to make this point clear make your domain objects not know anything about visualization or user interaction. You don't need to call them Model, but you could create a se...
6,929,972
6,930,653
Trouble reading .csv files in C++
I am working on a project where I intend on connecting to a database, grabbing a .csv file, reading it, manipulating the data and then returning it back to the database. Fairly simple and straight forward but I am still learning so if any one could point me in the right direction I would greatly appreciate it. Right no...
Try the following code. I think the problem was you were making an assignment statement in the while condition statement. #include <iostream> #include <fstream> #include <string> using namespace std; int main () { cout << "Welcome! " << endl; ifstream myfile; myfile.open ("C:\\Documents and Settings\\RHat...
6,930,039
6,930,165
Is this textbook wrong? Specialising some member functions but not others
I'm reading Vandevoorde and Josuttis's "C++ Templates The Complete Guide" (which seems pretty good, by the way). This claim (section 3.3) seems to be wrong and is not in the published errata: If you specialise a class template, you must also specialise all member functions. Although it is possible to specialise a sing...
You cannot do this: template <typename T> struct C { T foo () { return 0;} T bar () { return 1;} }; // partial specialization of foo on C<int> template <> int C<int> :: foo () {return 2;} // partial specialization of bar on C<float> template <> float C<float> :: bar () {return 3;} // will not compile, ...
6,930,419
6,930,463
Assignment to non-void functions (returning nothing) can change the values?
I encountered this problem in my program which was creating problems. so let me explain it by a example: #include<iostream> int func(){ if(1==0) return 100; } int main(){ int x=99; x= func(); std::cout<<"Value of x: " << x <<std::endl; } I had thought the output will be 99 but output...
You have undefined behavior because your function is declared to return an int but the execution path through the function never reaches a return statement. In C++ it is illegal to exit a function defined as returning a non-void type other than via a return statement with an argument. ISO/IEC 14882:2003 6.6.3 [stmt.ret...
6,930,507
6,930,532
Why does changing what a reference points to not throw an error?
Iv got to the stage in my c++ study concerning references. It states the following rule: Once a reference is initialized to an object, it cannot be changed to refer to another object. Iv wrote a short code (as asked to in an exercise) that is meant to prove this rule correct. int y = 7; int z = 8; int&r = y; r = z; C...
r = z does not change what r "points to." It assigns the value of z to the object pointed to by r. The following code does the same thing as your code, but using pointers instead of references: int y = 7; int z = 8; int* p = &y; // p points to y *p = z; // assign value of z to the object pointed to by p (which ...
6,930,520
6,930,775
Structure of program
I have few files: main.cpp: int main{ ... while(1){ ... draw(); ... } ... return 0; } and draw.cpp: I want to see objects and all manipulations here. I cant make objects local to draw(), because draw() is inside loop, so I will get many object constructor/destructor calls - so they are global. Also I ve made init bloc...
Option 1 Define a new Class called Draw and put the attributes into it. You need to modify main and draw files for this. With this you can avoid declaring anything global Option 2 Define a class within draw.cpp called draw and add your current global variables as static member variables. Initialize and use them using s...
6,930,772
6,933,159
Read Framebuffer-texture like an 1D array
I am doing some gpgpu calculations with GL and want to read my results from the framebuffer. My framebuffer-texture is logically an 1D array, but I made it 2D to have a bigger area. Now I want to read from any arbitrary pixel in the framebuffer-texture with any given length. That means all calculations are already done...
You can use a pixel buffer object (PBO) to transfer pixel data from the framebuffer to the PBO, then use glMapBufferARB to read the data directly: http://www.songho.ca/opengl/gl_pbo.html
6,930,787
6,930,830
tricky InterlockedDecrement vs CriticalSection
There is global long count counter. Thread A does EnterCriticalSection(&crit); // .... do something count++; // (*1) // .. do something else LeaveCriticalSection(&crit); Thread B does InterlockedDecrement(&count); // (*2) not under critical secion. At (*1), I am under a critical section. At (*...
You should use one or the other, not mix them. While InterlockedDecrement is guaranteed to be atomic, operator++ is not, though in this case it likely will be depending upon your architecture. In this case, you're not actually protecting the count variable at all. Given that you appear to want to do simple inrecremen...
6,931,362
6,935,038
Non-maximum suppression in OpenCV
I applied a harris corner detection using openCV which gave me a response map for the potential corners. The documentation states that corners can be found as the local maxima of this response map - does anyone know how this can be done? Thank you.
There is a working implementation with full coding for both Harris and the Shi-Tomasi corner detectors here. The 4th parameter in the corner detector function is a CvPoint2D32f* structure. The function returns the calculated local maxima i.e. the corners into this structure array. Simply looping through the array and ...
6,931,535
6,932,730
Linux | Segmentation Fault in C++ - Due to the function ifstream
I think I should begin by saying that I've just installed linux(debian) in my pc and have zero foreknowledge about doing things in linux. This problem is probably due to some really simple thing. The relevant part of the code is similar to this: ifstream stockNames("names.txt"); while (!stockNames.eof()) { ...
You have a dos file which uses \r\n at the end of each line. Linux doesn't recognise \r as part of the line ending so it gets included in the snline string. \r causes the next thing printed to appear at the beginning of the line so " hey" overwrites the stock names you were expecting to see. Try cout << snline << " " <...
6,931,588
10,445,155
Preventing Singleton Cache Miss in C++
Is there a way to prevent a cache miss when using singleton objects? Here's my current singleton implementation: SingletonObject.h #pragma once class SingletonObject { public: static SingletonObject* SingletonObject(); static void SingletonObject(); private: static SingletonObject* sSingletonObject; S...
This is a very specific question people arrive to way down the performance optimization road. Are you sure you're all the way there? Reason I'm asking is if you access your Singleton frequently enough, the pointer to the object will stay in cache. If it's not in cache, then you're not accessing the object frequently en...
6,931,638
6,931,706
Test SQL Connection String in C++ (WIN32)
I'd like to check a connection string on a SQL 2008 server. Problem is, I have to write the whole thing using C++ (WIN32). Is there any simple way to do this? I've googled it, but it's quite hard, since I don't have much experience with C++. Any help would be appreciated!
The connection string should be the same regardless of what language you implement with. To simply test the connection string you could do it a .NET language of your choice or whatever else you're familiar with. Here's a link to a 2-page tutorial that you can use to quickly put a C++ prototype app together that will co...
6,931,892
6,931,965
How to organize a game engine
I'm working on a small game engine and I've encountered a problem. So far, I have a window class that is a wrapper for a Win32 window. I also have a Window Manager class (it's a singleton class) that manages the creation of windows and the handling of windows messages. I then have an engine class, which is so far the ...
You're living in an event-driven world, so use events. Have your window wrapper provide events that the game engine can hook and react to.
6,931,951
6,932,081
How to make sure that std::random_shuffle always produces a different result?
Is there some function, similar to srand(), that I need to call to make sure that std::random_shuffle() always produces different results? i.e. if I call it several times with the same data, I want the order to be different every time. How can I make sure of that?
std::random_shuffle has two forms. One that takes 2 arguments (begin/end iterators), and one that takes 3 (begin/end iterator and a random generator). The first form uses std::rand(), so you would use std::srand() to seed it's random number generator. You can also use the 3-argument version and provide the RNG your...
6,932,151
6,933,139
How can I control focus within a Win32 app?
I have a situation where I have a main window with a toolbar containing some edit fields. We want the user to be able to keep focus in the edit fields and still be able to right click on the view window (both descendents of the same main window, same thread). In current tests, I see that the focus messages happen even ...
Start by turning on the WS_EX_NOACTIVATE style flag on the right-clicked window. That stops the window manager from automatically activating the clicked window.
6,932,243
6,932,435
Compiler warning when creating custom std stream implementation
I have a Visual Studio 2008 C++ application where I've created a custom streambuf and stream implementation. I've used an approach given by Angelika Langer for creating the stream detailed below: class MyOutputStream_3 : private MyStreamBuf, public ostream { public: MyOutputStream_3() : ostream((MyStreamBuf*) this)...
The C++03 standard has this bit in a note for 12.6.2/7 "Initializaing bases and members": [Note: because the mem-initializer are evaluated in the scope of the constructor, the this pointer can be used in the expression-list of a mem-initializer to refer to the object being initialized. ] I think the warning is issued...
6,932,409
6,932,446
Writing a string to the end of a file (C++)
I have a program already formed that has a string that I want to stream to the end of an existing text file. All of what little I have is this: (C++) void main() { std::string str = "I am here"; fileOUT << str; } I realize there is much to be added to this and I do apologize if it seems I am asking people to co...
Open your file using std::ios::app #include <fstream> std::ofstream out; // std::ios::app is the open mode "append" meaning // new data will be written to the end of the file. out.open("myfile.txt", std::ios::app); std::string str = "I am here."; out << str;
6,932,424
6,932,483
endians, languages, hardwares and network
We know the endian is related to the way how computers store data. Big endian computer architectures include the IBM 370, the Motorola 68000 and Sun Sparc. Little endian computers include the intel series (80486, pentium etc) and VAX. Java is always Big-Endian because of the JVM. Network should always be Big-Endian be...
For C and C++, at least, yes; the endianness typically depends on the machine (but may also depend on the compiler). For C#, I don't know. Many network protocols are big-endian, yes. If you don't call htonl, then you will not be creating a valid packet on a little-endian machine. So you should always call htonl, etc...
6,932,587
6,932,611
extern C and struct method
Given the following C++ code, #ifdef __cplusplus extern "C" { #endif struct foo { void getNum() { } }; #ifdef __cplusplus } #endif int main (int argc, char * const argv[]) { return 0 ; } Is it possible to call getNum() from C?
No, since getNum is a member function, which C doesn't have. A possible solution to that problem is to write a C++ function to return a foo instance as a foo* (where foo is changed to be an empty struct) to C (I assume this is binary compiled as C++ to which C is linking), then have a free function in C++ called foo_ge...
6,932,878
6,933,566
How to blend texture colors with simple multiplication to the colors under it?
So i want my texture colors to multiply with the colors under it, how this can be done with glBlendFunc() ? For example: if i have a texture color (0.31, 0.51, 0.124) and there is a color (0.83, 0.64, 0.12) under it, the resulting color would be 0.31*0.83, 0.51*0.64, 0.124*0.12. How to do this?
So i want my texture colors to multiply with the colors under it, how this can be done with glBlendFunc() ? By "texture colors", I'm going to assume that you mean "the color output by the glTexEnv process". Or, using more rigorous OpenGL spec language, the fragment color. In any case, this is a simple matter of blend...
6,932,959
6,945,431
Visual C++ parallel_for + vectors access violation
I am trying to convert a process that loops through a ~12,000x12,000 cell matrix (around 125 times) to use parallel processing (via parallel_for). The code I am using is below. You can see where the for loop is commented out. When I run this code with the for loop, there are no problems. When I run it (in debug) usi...
You've used no synchronization protection for sqlStrings. It is not safe to mutate the container, print to output, or even increment a shared variable from multiple threads concurrently without using synchronization.
6,933,058
6,933,216
Python: How to check that...?
I'd like some advice on how to check for the correctness of the parameters I receive. The checking is going to be done in C++, so if there's a good solution using Boost.Python (preferably) or the C API, please tell me about that. Otherwise, tell me what attributes the object should have to ensure that it meets the crit...
When in doubt just work out how you would get the required effect by calling the usual Python builtins and translate it to C/C++. I'll just answer for Python, for C you would look up the global such as 'callable' and then call it like any other Python function. Why would you care about it being a function rather than ...
6,933,061
6,933,152
C++, ambiguous inheritance error in vs 2010
I have some troubles with the application of polymorphism in this example. This question is similar to my last question C++, virtual inheritance, strange abstract class + clone problem There are 3 abstract classes: class A { public: virtual A * copy () const = 0; virtual ~A() = 0; }; A::~A(){} class B { publ...
This is a known bug in Visual C++: Visual C++ incorrectly reports ambiguity when covariance is used with virtual inheritance You either need to eliminate the covariance or the virtual inheritance. Unfortunately, you can't have both.
6,933,320
6,933,333
How to use operator> in partial_sort_copy
I hope this is not a noob question - allthough it is my first here on stackoverflow ;) When using partial_sort_copy with for example 2 vectors, it gives you the "smallest" n values, depending on how operator< is defined for the Class of the T (where n is the size of the target vector) Is there a possibility to use ope...
You don't have to define an extra function; the C++ Standard Library already has one. It's called std::greater. // Where 'T' is the type of object being sorted: std::partial_sort(input.begin(), input.end(), output.begin(), output.end(), std::greater<T>());
6,933,342
6,933,493
dynamic_cast reference to base class in stl container
Is it possible to store a bunch of objects by their base class in say an std::list without pointers. I would really like the objects to be held in the container, then retrieve a pointer to the object in the container and dynamic_cast it to correct derived class. I have it working fine using pointers. Like (super simp...
As you guessed, when you stored an object in a container by value, it gets sliced and the data is chopped off. If you only need to store one data type (you only show one in your code), then you can make the container hold that type. If not, you really are stuck using pointers. You can make the memory management much ea...
6,933,787
6,945,325
Draw tick mark in QTree
I want to draw a tick mark in a Qtreeview. I don't want to have a checkbox but just to indicate an item. Is there a way to do so? Thanks
In your model's data() function, return a QIcon or QPixmap for the Qt::DecorationRole: QVariant MyItemModel::data(const QModelIndex &index, int role) const { ... if(role==Qt::DecorationRole) { if(currentItem.isChecked()) return QPixmap(":my_check_icon.png") // Checkmark Image else return QVa...
6,933,989
6,934,044
Which library for video and audio recording?
I am looking for a library to record images from a webcam and sound from the microphone and generate a video file (avi, mpeg or any other format). I would prefer a cross-paltform solution (Windows, MAC and Linux) and something in C/C++ or Python. Any recommendation and/or sample code? Update: Folowing @Rory reccommendt...
gstreamer is an open source multimedia framework with C & Python bindings.
6,934,024
6,934,050
Is there any benefit to declaring a const rather than a variable inside a function?
If I have a function which only exists for a short amount of time, does making the list of colors a constant make a difference? string getrandcolor(){ const string colors[5] = {"red", "blue", "green", "yellow", "purple"}; return colors[rand() % 5]; } Note: The actual list of colors contains hundreds of colors ...
It prevents you from accidentally overwriting variables that you didn't mean to change. "Oops!"-protection is probably const's most important function. Hypothetically a compiler could divine some kind of optimization from knowing a variable isn't supposed to change, but my testing has never found one that actually does...
6,934,121
6,934,142
Parentheses in template parameters in Boost Spirit rules and grammars
Looking at this example for implementing a Spirit parser, something caught me out when I was trying to write something similar. The attribute template parameter of the grammar (std::map<std::string, std::string>()) and the signature template parameter of the rules (e.g. qi::rule<Iterator, std::string()> key, value) con...
std::map<std::string, std::string>() This is a function type. The () makes this mean "a function that returns a std::map<std::string, std::string> and has no parameters." Without the (), the type is just "std::map<std::string, std::string>," which is not correct.
6,934,217
35,385,731
Encrypting / obfuscating a string literal at compile-time
I want to encrypt/encode a string at compile time so that the original string does not appear in the compiled executable. I've seen several examples but they can't take a string literal as argument. See the following example: template<char c> struct add_three { enum { value = c+3 }; }; template <char... Chars> str...
I think this question deserves an updated answer. When I asked this question several years ago, I didn't consider the difference between obfuscation and encryption. Had I known this difference then, I'd have included the term Obfuscation in the title before. C++11 and C++14 have features that make it possible to implem...
6,934,283
6,934,372
How does one generally get the end of a string in C++0x?
template<typename ForwardIterator, typename StringType> inline bool starts_with(ForwardIterator begin, ForwardIterator end, const StringType& target) { assert(begin < end); if (std::distance(std::begin(target), std::end(target)) > std::distance(begin, end)) { return false; } return std::equa...
How about making a little trait class for your string template parameter: template <typename TString> struct StringBounds { typedef typename TString::const_iterator citerator; static citerator Begin(const TString & s) const { return std::begin(s); } static citerator End (const TString & s) const { return std::en...
6,934,505
6,934,655
Any good reason for C++ header file to not include any other header files?
I've seen a header include style like this, where header files don't include other header files and the corresponding *.cpp files must include all the dependencies (and include them in the right order). It seems possible that in the good old days that this would make build dependency tracking easier (but I'm just guess...
It seems whoever wrote that code misunderstood the common recommendation of reducing the number of included headers. It is usually recommended to remove unnecessary #include <> directives in the hope of accelerating compilation. Indeed, on large projects, it may accelerate compilation significantly by: reducing the ...
6,934,579
7,647,823
iPhone game CPU profiling and pthread_setspecific
In profiling an iOS game on an iPhone 3G, instruments is reporting that the system call pthread_setspecific (which is being called from many seemingly unrelated locations) is the biggest CPU bottleneck. Google tells me this deals with storing meta data for threads, however I'm not sure how to track this down since the...
Code generated by exception handling is using thread local storage to store its unwinding stack. There is nothing you can easily do. Try to remove exception when possible. Compile part of the code without it.
6,934,775
6,934,802
Simple struct alignment/padding question
I have a 32-bit C++ program here, and was checking disassembly out of curiosity. I have the following struct: struct Blah { char foo; std::string bar; }; When accessing blah->bar, I noted the following: ; ... address of blah is in eax 003A227B add eax,4 So my question is, why does 4 needed to be ad...
It is adding 4 to the base address of blah. I guess that is the same as adding 3 to the address just after foo. :) It is indeed an alignment issue. Pointers should be aligned on address which are a multiple of 4.
6,934,776
6,934,794
C++: getting the row size of a multidimensional array passed to a function
I'm trying to write a function that will print out the contents of a multidimensional array. I know the size of the columns, but not the size of the rows. EDIT: Since I didn't make this clear, the arrays passed to this function are NOT dynamically allocated. The sizes are known at compile time. I am testing it using a ...
The answer is that you can not do this. You must pass the number of rows as an argument to the function, or use an STL container such as std::vector or std::array. sizeof is computed compile time; sizeof is never useful in determining dynamic size of objects in C/C++. You (yourself, the programmer) can always calculate...
6,934,874
6,934,888
Question about iterating through array in c++
I have an array which is not necessarily full. It can be very sparse. Is there a good way to iterate through this array without visiting all the possible indexes? (c++ array iterator?) Or, even if I use array iterator, will it be nothing different from visiting every indexes and checking the value?
Yes, if you use an iterator, it's the same as visiting every index and checking the value, and there's no good way to skip logical holes. You could keep a list of good indices, but if you did that then why not just use a list to store the data in the first place? If your data is very sparse, perhaps a better data struc...
6,935,118
6,935,191
How to apply std::accumulate algorithm for associative containers?
For a map like std::map, how do I accumulate it's values' sum? Actually, I made it with a functor and std::for_each algorithm. But I'd also like to make this using std::accumulate algorithm. I have no idea how to apply it to std::map. Is this even possible? struct Accumurator : std::unary_function<std::pair<int, in...
Almost. The functor must be a binary operator taking the return value type as the first and the range type as the second argument: x = Functor(init, *it++); x = Functor(x, *it++); x = Functor(x, *it++); // ... until it == end So you don't need a stateful functor at all, a simple function will do: int map_acc(int lhs, ...
6,935,208
6,935,650
Should I lock a variable in one thread if I only need it's value in other threads, and why does it work if I don't?
I am aware of this question, but I believe my concerns are very different. I recently created an SDL application, using threading and OpenGL. I have one thread running in a loop, which continually updates the state of the objects I draw to the screen. The states are very simple, it is just a boolean array (when the a...
In theory, it's completely invalid (undefined behavior) to access memory like this without some synchronization. In practice, it's moderately safe as long as: Only one thread is writing and the others are all reading. You don't care if the readers don't see some of the changes made until sometime later (possibly much ...
6,935,219
6,936,322
fastest integer sort implementation for 200-300 bit integers?
What is the fastest integer sort implementation for 200-300 bit sized integers? Exact int size is fixed; I have up to 2 gigabytes with such integers (all in RAM). I hear that it is possible to sort such set in average at O(n log log M) or even at O(n sqrt(log log M)) time, wher n is number of integers and M is the larg...
A Radix Sort can be used to sort data with fixed size keys. As this condition is not often met the technique isn't discussed much, but it can be O(n) when the key size is factored out.
6,935,362
6,935,423
Loop asking user for input into an array
You all have helped me so much in the past, I am coming back for more help! I am working on another C++ assignment for school. I have to collect 20 numbers between 10 and 100 from the user and compare them all and print out the ones that are not duplicates. The part I am stuck on is trying to get the user input to loo...
your problem is how to enter 20 valid numbers, is it? I think the do while loop will help you. int FindDuplicates[20]; // my little array int UserInput; // the number from the user to compare int count = 0; // the number of numbers entered do { cout << "Please enter a number between 10 and 100: "; // print out wha...
6,935,389
6,935,407
how to get iterator to a particular position of a vector
Suppose i have a std::vector<int> v //and ... for(int i =0;i<100;++i) v.push_back(i); now i want an iterator to, let's say 10th element of the vector. without doing the following approach std::vector<int>::iterator vi; vi = v.begin(); for(int i = 0;i<10;i++) ++vi; as this will spoil the advantage of having rando...
Just add 10 to the iterator. They are intended to "feel" like pointers.