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
7,349,431
7,349,557
Passing raw data in C++
Up until now, whenever I wanted to pass some raw data to a function (like a function that loads an image from a buffer), I would do something like this: void Image::load(const char* buffer, std::size_t size); Today I took a look at the Boost libraries, more specifically at the property_tree/xml_parser.hpp header, and ...
Well, streams are quite used in C++ because of their conveniences: - error handling - they abstract away the data source, so whether you are reading from a file, an audio source, a camera, they are all treated as input streams - and probably more advantages I don't know of Here is an overview of the IOstream library, ...
7,349,441
7,360,942
What tools exist to help finding memory leaks for handles?
What tools exist to help finding memory leaks for handles? I have a file.exe and an inproc-server dll, which is using file.exe. I have about 10 memory leaks of handles evertyime it completes its operation.
Process Explorer (http://technet.microsoft.com/en-us/sysinternals/bb896653) is one of the SysInternals tools that you can use to show the handles that a program has allocated. You have to configure the lower pane view to show handles in order to see them. It tells you the type of handle, which may help in finding the...
7,349,484
7,397,825
How to play random part of mp4 file with vlc or something else?
I have random part (99,9% somewhere in the middle) of the mp4 file. Problem is that it's not in any container or anything just a binary piece of the file in random offset and send to me... it will keep growing but it'll take a while and I need to play content right away. I can get all necessary metadata information for...
OK, I've solved it like this (dirty workaround): Coppied the moov part (just looking for this atom) from oryginal file and created the file of the oryginal size filling with zeros and the metadata parts. Than I'm simply running player and jump with it to part that is already downloaded. (still having problems how to f...
7,349,551
7,351,261
Any opensource C/C++ Libraries/Frameworks for RPC over pipes/internal linux sockets?
I am looking for a lightweight opensource library/framework preferably written in C/C++ (it doesn't have to support x languages and should be easy to understand and use.) which can be used to make RPC over internal linux sockets or pipes. In other words I am looking for an RPC possibility which can be run over some of ...
Look at msgpack-rpc. It's easy and very simple RPC implementation.
7,349,559
7,349,716
Undefined behaviour with const_cast
I was hoping that someone could clarify exactly what is meant by undefined behaviour in C++. Given the following class definition: class Foo { public: explicit Foo(int Value): m_Int(Value) { } void SetValue(int Value) { m_Int = Value; } private: Foo(const Foo& rhs); const Foo& operator=(const Foo& rh...
I was hoping that someone could clarify exactly what is meant by undefined behaviour in C++. Technically, "Undefined Behaviour" means that the language defines no semantics for doing such a thing. In practice, this usually means "don't do it; it can break when your compiler performs optimisations, or for other reaso...
7,349,665
7,349,702
Segfault with List insert?
I feel like I might be overlooking something very extremely simple here, but I have made some code just to test out insert / splice on lists and I am getting a seg-fault on the code I made. Can someone tell me where / why? #include <iostream> #include <vector> #include <list> using namespace std; int main(){ vec...
lIt has not been correctly initialized - it is an iterator - but currently does not point to anything - you need to do this: lIt = iList.begin(); // initialize it to begin, now we can iterate!
7,349,689
7,349,767
How to print (using cout) a number in binary form?
I'm following a college course about operating systems and we're learning how to convert from binary to hexadecimal, decimal to hexadecimal, etc. and today we just learned how signed/unsigned numbers are stored in memory using the two's complement (~number + 1). We have a couple of exercises to do on paper and I would ...
The easiest way is probably to create an std::bitset representing the value, then stream that to cout. #include <bitset> ... char a = -58; std::bitset<8> x(a); std::cout << x << '\n'; short c = -315; std::bitset<16> y(c); std::cout << y << '\n';
7,349,826
7,349,923
dynamic_cast overhead in C++
I know that dynamic_cast have runtime check and therefor consider safer (can return null pointer on failure) but slower then static_cast. but how bad is the overhead between the two? should I realy consider use static_cast in loops for performance issues in regular large projects? or the difference is minor and only re...
Did you profile it? The rule is: Use static_cast when you know that the target type is valid. Use dynamic_cast when you're not sure, and you need the program to look up the object's runtime type for you. It's as simple as that. All other considerations are secondary.
7,349,844
7,349,892
two problems in stack building program
The following program successfully builds up a stack , but the 2 operations pop and stack top are giving exception and wrong result respectively. Here is the program : // Working with stack using Array /* * @author Suhail Gupta * */ #include <iostream> using namespace std; char choice; int *ptrToArray; // this wi...
int *firstElement = NULL; // Global pointer variable void push() { // ... else { // .. int numberToPush; // Resides on stack. // .... firstElement = &numberToPush; // ... } // numberToPush cease to exist from this point. } numberToPush is a local variable and hav...
7,349,899
7,350,092
how are map iterators invalidated when erasing elements?
when and how are iterators invalidated in a map when using the erase method ? for example : std :: map < int , int > aMap ; aMap [ 33 ] = 1 ; aMap [ 42 ] = 10000 ; aMap [ 69 ] = 100 ; aMap [ 666 ] = -1 ; std :: map < int , int > :: iterator itEnd = aMap.lower_bound ( 50 ) ; for ( std :: map < int , int > :: iterator...
Only the erased iterator is invalid, the rest are guaranteed by the standard to remain valid. See Iterator invalidation rules
7,349,915
7,350,060
Unhandled exception when application is finishing
I have a singleton (I know that is a bad pattern). To control the cleaning process, I'm using a shared pointer. The relevant code is: #ifndef _GLOBAL_LOG_H_ #define _GLOBAL_LOG_H_ namespace glog{ class CGlobalLog; typedef boost::shared_ptr<CGlobalLog> globalLogPtr; class CGlobalLog ...
I generally don't expect to see a shared pointer on a singleton. Just returning a reference to your singleton and never keeping a reference to it laying around is a good practice. struct Foo { static Foo &instance() { static Foo foo; return foo; } }; struct Bar { void someMethod() { Foo &foo = Foo::...
7,350,000
7,350,085
mcrypt example not working
I am working on ubuntu in c++ code. I wanted to test an exmple with mcrypt from this link: http://linux.die.net/man/3/mcrypt , but whn i do: gcc test.c -o testt -lmcrypt there is no result back. why? Where am I wrong? For both examples the result is the same. appreciate!!
gcc test.c -o testt -lmcrypt gives no result, because there is no error (see UNIX culture[1]). Try to run the resulting binary with ./testt to see the output (if any). Probe the file, if you will file ./testt ldd ./testt objdump -Ct ./testt If all is well, you'll get all kinds of information about your file :) [1]...
7,350,070
7,497,056
Force encoding when writing txt file with ofstream
I writing a txt file using ofstream, from various reasons the file should have local encoding and not UTF8. The machine which process the file has different localizations then the target local. is there a way to force the encoding when writing a file? regards, Ilan
You can call std::ios::imbue on your ofstream object to modify the locale. This won't affect the global locale. std::ofstream os("output.txt"); std::locale mylocale(""); os.imbue(mylocale); os << 1.5f << std::endl; os.close(); Pay attention to the argument of std::locale constructor, it is implementation dependant. F...
7,350,083
7,350,153
Can I delete a item from std::list based on pointer value?
This code is written on fly, plz ignore syntax mistakes if any. std::list<MY_STRUCT> myList; MY_STRUCT theStruct; myList.push_back( theStruct ); myList.push_back( theStruct ); // assume I store the pointer of the last item (the 2nd item in this case). MY_STRUCT * item2 = &myList.back(); // I added another item myLi...
Sure, list::remove_if uses whatever condition you give it. For example template <typename T> struct AddressIs { T *ptr; AddressIs(T *ptr) : ptr(ptr) {} bool operator()(const T &object) const { return ptr == &object; } }; myList.remove_if(AddressIs<MY_STRUCT>(item2)); Mankarse's point is good t...
7,350,120
7,350,523
Tell VS2010 to collapse regions
So I have written a t4 template which generates a ton of code and works well. The only issue is that most of the code never needs to be seen by developers so I have hidden in regions all of the boiler plate code . Is there any way (i'm assuming no) to give VS a hint in a c++ code file to go ahead and collapse the reg...
You could generate the code into a separate file and then #include it where necessary. That way you won't have developers working directly on top of the generated code: they don't see it, and it makes possible future regenerations of that code very easy.
7,350,155
7,350,783
Initialisation and assignment
What EXACTLY is the difference between INITIALIZATION and ASSIGNMENT ? PS : If possible please give examples in C and C++ , specifically . Actually , I was confused by these statements ... C++ provides another way of initializing member variables that allows us to initialize member variables when they are created rat...
Oh my. Initialization and assignment. Well, that's confusion for sure! To initialize is to make ready for use. And when we're talking about a variable, that means giving the variable a first, useful value. And one way to do that is by using an assignment. So it's pretty subtle: assignment is one way to do initializatio...
7,350,366
7,350,389
What does the minus in /Zc:wchar_t- mean?
Recently I had some linking issues caused by the presence (or absence) of this flag. /Zc:wchar_t- I've read the docs, but they don't mention the trailing minus. But every discussion of it seems to include it. What does it mean?
/Zc:wchar_t- does the opposite of what /Zc:wchar_t does: it causes wchar_t to be treated as the same type as unsigned short, for compatibility with VC6. /Zc:wchar_t- causes your code to be non-conformant with standard C++, so don't use it unless you must.
7,350,925
7,352,318
atomic<int> for older c++ compilers
I am using atomic<int> in my code, but the machine in which now I'm compiling has an older g++ version which doesn't support C++11. Is there any equivalent class available on the net, so that I can use it in my code, or if not, where I can find the C++11 implementation of atomic<int> so I can copy it from there. Can th...
Hans Boehm's atomic ops library is good, although it's hard to determine what's available on various platforms. If you're OK with the LGPL, Intel TBB has what you're looking for as well (plus a lot of other stuff). If you're only looking at GCC, then you may be able to get away with just using GCC's intrinsics (I'm not...
7,351,074
7,351,334
public: typedef other_class::const_iterator my_class::const_iterator - acceptable?
I'm looking for a way to use std::set::const_iterator as const_iterator of my own class. My code (which actually behaves correct and compiles fine), goes like: class MyClass{ public: typedef std::set<T>::const_iterator const_iterator; const_iterator begin() const { return mySet->begin(); } const_iterator end...
Have a look at other C++ Standard Library container adapters like std::queue. std::queue is just an adapter on top of an underlying container (by default a std::deque). This is exactly the method used in those adapters. Given that, I would say your implementation is fine.
7,351,143
7,351,163
what's faster: recreate or clear()?
I have a question about the performance of the std::vector<> in C++. Is it faster to reuse the same vector by calling its clear() method or it it faster to recreate the vector? The following example is no real life code, it's only for making clear what the question is: //Example ONE: is this faster std::vector<int> foo...
The clear() cannot by its contract deallocate the vector memory, instead just sets the internal "size" flag to 0, so that method will be faster.
7,351,153
7,351,220
multimap vs map with set
I'm wondering which is more efficient. std::map< String, std::set<int> > or std::multimap< String, int > EDIT: I do not plan on doing anything out of the ordinary with these maps. Standard insert, delete, modify, search. The size of each set or multi keyed String shouldn't be more than 100.
This I believe is implementation dependant, but an (un)educated guess: In practice it depends on the number of integers that you will be keeping in the multimap or the std::set. A multimap will most likely use a linear search of the values after the log(n) search of the key. If you have a large number of integer valu...
7,351,476
7,351,555
Virtual override and binary compatibility
I have a library that can be compiled as a shared library (or DLL in Windows). It has a class that is derived from another class in another library. The base class has some virtual methods and my class overrides a few of them. For example: class Base { public: virtual void method1(); virtual void method2(); ...
Since you're talking about DLLs, I assume this is C++ in Visual Studio/Windows. Adding the override will not break binary compatibility because the size of the vtable is not changing. However, it may cause some undesired results if you don't recompile all code that instantiates new instances of Derived. This is because...
7,351,579
7,351,890
MFC string width without CDC
Is there any way to get the width of a string in pixels without using CDC or using a CDC not linked with a display. The class that needs to retrieve the string width does not inherit from CWnd in order to use CWnd::GetDC() and there is no way to pass an existing CDC to the function. I have tried to create a dummy CDC t...
The width of a font is dependent on how it is converted to pixels, and this is dependent on the device it is being rendered on. It will obviously be different for a printer versus a monitor for example. This is why you need a DC for this function. You can get the DC for the desktop using CDC::FromHandle(::GetDC(NULL))....
7,351,654
7,351,668
Why does 'sizeof' give wrong measurement?
Possible Duplicate: struct sizeof result not expected I have this C++ struct: struct bmp_header { //bitmap file header (14 bytes) char Sign1,Sign2; //2 unsigned int File_Size; //4 unsigned int Reserved_Dword; //4 unsigned int Data_Offset; //4 //bitmap info header (16 bytes) unsigned int Dib_Info_Size...
The reason is because of padding. If you put the chars at the end of the struct, sizeof will probably give you 30 bytes. Integers are generally stored on memory addresses that are multiples of 4. Therefore, since the chars take up 2 bytes, there are two unused bytes between it and the first unsigned int. char, unli...
7,351,659
7,408,174
How to initialize a glm::mat4 with an array?
I'm using the OpenGL Mathematics Library (glm.g-truc.net) and want to initialize a glm::mat4 with a float-array. float aaa[16]; glm::mat4 bbb(aaa); This doesn't work. I guess the solution is trivial, but I don't know how to do it. I couldn't find a good documentation about glm. I would appreciate some helpful links.
Although there isn't a constructor, GLM includes make_* functions in glm/gtc/type_ptr.hpp: #include <glm/gtc/type_ptr.hpp> float aaa[16]; glm::mat4 bbb = glm::make_mat4(aaa);
7,351,704
7,351,814
Using delete on pointer to std::list?
In my program I have a pointer to a std::list object, it is allocated like so. d_list_p = new std::list<some_type*>(); Then later in my program I delete it like so. d_list_p->clear(); delete d_list_p; For some reason I'm getting a Windows breakpoint triggered on the delete statement. If I break at the delete statemen...
Is d_list_p a member of a class? And, does that class observe the Rule of Three? If not, then (a copy of) d_list_p may have already been deleted.
7,351,705
7,352,391
OpenCV Canny Edge on Live Video
i am trying to implement opencv's canny edge detection on live video from webcam. However, I am getting this error: OpenCV Error: Unsuported format or combination of formats <> in unknown function, file ........\ocv\opencv\src\cv\cvcanny.cpp, line 66 I guess this is a format issue. I can convert the 3-channel 8-bit RGB...
The Problem is that you are passing a 3 channel image everywere IplImage* out = cvCreateImage( cvGetSize(frame), IPL_DEPTH_8U, 3 ); Create other two images of single channel and use those: IplImage* gray_out = cvCreateImage( cvGetSize(frame), IPL_DEPTH_8U, 1 ); IplImage* canny_out = cvCreateImage( cvGetSize(frame), IP...
7,351,750
7,351,832
Need help to resolve library conflicts
I have a .lib file created with previous versions of visual studio, perhaps 2003 I link it with my code in visual studio 2010. build succeeds but I get this warning warning LNK4098: defaultlib 'msvcrt.lib' conflicts with use of other libs; use /NODEFAULTLIB:library I want my application to use VS2010 'msvcrt.lib' lib...
Your library might be using the older 9.0 7.0 or 7.1 runtime library, as pointed out by DeadMG. In VS2010, the 10.0 runtime is the default. You might need to recompile your library with the new runtime. Please note that the v10 runtime targets only Windows XP SP3 or higher. If you still wish to target lower operating ...
7,351,767
7,352,256
CreateProcess works on some computers, not on others. Why?
I work on an app that calls another app via CreateProcess. I'm on Win7 64 bits. The called app is a console that receive data through a pipe. The calling code looks like this: STARTUPINFOA si; PROCESS_INFORMATION pi; GetStartupInfoA(&si); memset( &si, 0, sizeof(STARTUPINFOA) ); memset( &pi, 0, sizeof(pi) ); si.cb = siz...
CreateProcess uses the same permissions as the calling process it also will terminate the process if it has not initialized properly so you should wait and verify the process launched even if CreateProcess returns success. However your access denied issue is probably related to your calling process not having execute o...
7,351,811
7,353,545
Updating mongo collection
I use mongodb and c++ driver for it and when I update some collection of documents with fields entid, div, name, fld2 using this code: connection.update("mydb.mycol", Query(bob().append("entid",1).obj()), bob().append("div", 5).obj()); updating has been done successfully, but updated document has not entid, name and f...
You need the $set modifier. I don't know anything about the C++ driver but the JS syntax is: db.mydb.update({"entid" : 1}, {"$set" : {"div" : 5}}) I hope you can transform this to C++ code ;)
7,351,899
7,352,040
Remove first N elements from a std::vector
I can't seem to think of a reliable way (that also compacts memory) to remove the first N elements from a std::vector. How would one go about doing that?
Since you mention that you want to compact memory, it would be best to copy everything to a new vector and use the swap idiom. std::vector<decltype(myvector)::value_type>(myvector.begin()+N, myvector.end()).swap(myvector);
7,352,099
7,352,131
std::string to char*
I want to convert a std::string into a char* or char[] data type. std::string str = "string"; char* chr = str; Results in: “error: cannot convert ‘std::string’ to ‘char’ ...”. What methods are there available to do this?
It won't automatically convert (thank god). You'll have to use the method c_str() to get the C string version. std::string str = "string"; const char *cstr = str.c_str(); Note that it returns a const char *; you aren't allowed to change the C-style string returned by c_str(). If you want to process it you'll have to c...
7,352,162
7,352,199
Compilation unit and static linkage issue
I'm going to completely reword this question since I'm not quite getting the solutions I was looking for (they're helpful but they weren't saying anything the other questions I referenced didn't say). Given the following 4 files: file #1: A.h class A { void a_func(); }; file #2: A.cpp #include "A.h" static int x = 4;...
The translation unit consists of everything that comes out of the preprocessor. In gcc, try g++ -E myfile.cpp to see what that is. Static globals have, well, static linkage, so their name does not spill outside the TU. In each separate TU, the static global (whether of the same name or not) will be a separate object, ...
7,352,193
7,352,332
using sstream header file in C++
so I was trying to utilise the istringstream to parse through a text file. The idea is to break down each line by space and based on the substring do stuff. The code works fine except for two things, it double counts last substring for each line and it seg faults when its done reading through the file. I have not used ...
The while loops should go like this: std::string line; while (std::getline(file, line)) { std::istringstream iss(line); std::string token; while (iss >> token) { cout << "Substring: " << token << endl; } } The getline and input operations return the stream object, which itself has a speci...
7,352,345
7,352,401
C++ API in Python - SWIG, Redesign, or Message Passing
Ok, quick, and hopefully easy question here... I have a large C++ API that is basically a sockets API with a top level XML type protocol. This is a distributed source package from a company. All of the source code is written into header files (including function implementations) for some odd reason (I guess they figu...
SWIG would usually be my preferred solution for problems like this. "Custom typed" structures can be wrapped perfectly sensibly. The thing you will need to watch out for though is the limitations of the SWIG parser if you've got everything in the header files.
7,352,373
7,353,300
QObject double deletion
I am currently running Qt 4.7.4 on Mac OS X 10.6. I installed Qt using MacPorts. I have been trying to use test-driven development as a part of my coding practice, and I am using QtTest for this purpose. I have a class derived from QObject, and when I try to test the code, my test fails when it should pass. I looked...
This line in ElementTest::initTestCase(): QPointer<Element> element(new Element(this)); is creating a local variable named element that has nothing to do with the member ElementTest::element. The local vairable is getting destroyed when ElementTest::initTestCase() returns. Try changing the line to: element = new Elem...
7,352,424
7,352,640
How to inherit from a list of types and then call a member on the list of inherited members?
I have a set of classes that have the following structure: class U { public: explicit U(int) { ... } U() {...} Init(int) {...} }; I need to be able to compose 1 or more of these classes into a class X. Pseudocode: template<class TypeSequence> class X that derives publicly from all the classes in TypeSequen...
Well, Boost.MPL contains metafunctions inherit and inherit_linearly you can combine them with for_each to get the second variant (with init functions). Or using just boost::mpl::fold and custom metafunctions: struct Null_IntConstructor { Null_IntConstructor(int) { } }; struct InheritFrom_IntConstructor_Folder { t...
7,352,706
7,352,727
"Cannot allocate an object of abstract type" error
Error is here: vector<Graduate *> graduates; graduates.push_back(new AliceUniversity(identifier,id,salary,average)); Grandparent class: Graduate::Graduate(char identifier, long id, int salary, double average) : _identifier(identifier), _id(id),_salary(...
In C++ a class with at least one pure virtual function is called abstract class. You can not create objects of that class, but may only have pointers or references to it. If you are deriving from an abstract class, then make sure you override and define all pure virtual functions for your class. From your snippet Your ...
7,352,729
7,352,759
How to call member function using function pointers for a specific object
I have this code: #include <iostream> class foo { public: foo(int yy){y = yy;} void f(int x){std::cout<<x;} private: int y; }; void main() { foo* obj = new foo(123); void (foo::*func)(int) = &foo::f; //how do I call func with obj as this? delete obj; } Is this possib...
You call it ike this: (obj->*func)(42); The first set of parentheses are needed because of the precedence of "apply function call" over the dereference-PTM ->* operator. You can also use std::bind: std::function<void(int)> my_f = std::bind(func, obj, std::placeholders::_1); my_f(43);
7,352,809
7,404,675
How do I use/access a user argument in a boost accumulator?
I have the gist of a custom accumulator. I want to know how to get an integer argument from the "argument pack", or if this is even possible: namespace boost { namespace accumulators { namespace impl { template<typename Sample> struct quartile_accumulator : accumulator_base { typedef Sample result_type; quart...
I figured it out. I add this before defining the class: BOOST_PARAMETER_KEYWORD(tag, quartile_number) And then I can use that keyword in the result and extract method.
7,352,833
7,352,865
Exception in derived class constructor
Im having some problems to handle constructor exception in derived classes. When the derived class constructor throws an error, but the parent class has allocated some objects. Will the parent class destructor be called? Example: class A { A() { /* Allocate some stuff */ }; virtual ~A() { /* Deallocate stuff */ };...
An exception will cause the stack to unwind to a point where the exception is properly caught. This means that any objects created in the scope prior to where the exception is thrown will be destructed, including base class objects as in this example. Try this: #include <iostream> class A { public: A() { std::cout ...
7,352,858
7,354,044
Are there any supported high bit-depth video or image formats in DirectShow
In the Microsoft DirectShow documentation there appear to be no RGB video or image formats with more than 8 bits per channel. There are some YUV formats with 10 or 16 bits per channel but I've not found much support for them by googling. Video Subtype GUIDs 10-bit and 16-bit YUV Video Formats Are there any supported...
DirectShow itself - as the framework - has no problems supporting 10 bpp and more, it's a matter of video renderers and video adapters to support these formats. Some professional hardware from Balckmagic definitely supports 10 bpp formats, including within DirectShow API.
7,353,025
7,363,425
Strange compiler error due to use of xml in c++ comments
I'm working on a proprietary unix-like os (I don't know if that's relevant though) and compiling with g++. I noticed recently that if I put xml-like tags in my C++ comments I get compiler errors. I don't particularly need to do this, but I thought it was strange and I'd like to know why it's an issue for the compiler....
This sounds suspiciously like a digraph related issue, but without the actual error message or a small code sample that exhibits the problem it's hard to tell for sure. Try changing the whitespacing between the <, / and actual text, as well as try it within a C-style comment to see if that provides additional insight. ...
7,353,032
7,359,588
Stopping Compiler from generating errors in a C++ code that has legacy C code
I am porting a legacy C program to C++. However, the compiler is not happy and requires additional typecastings for C++. For example, I have this function... void foreach_element_in_patch(Patch *patch, void (*func)(), long arg1, long process_id); In the original C Code, it is used like this... foreach_element_in_pa...
The easiest thing to do is to change the function prototypes and headers to declare the correct type of function pointer. So for example, for void foreach_element_in_patch(Patch *patch, void (*func)(), long arg1, long process_id); I just need to change it to void foreach_element_in_patch(Patch *patch, void (*)(Pat...
7,353,050
7,353,109
Pre-assign parameter in script
Actually I have trouble naming the title of this post. Because I don't know how to summarize my meaning in a professional way. But I'll explain my question as below: I'm running a program written by C++, command is: ./VariationHunter_SC Then it'll let you type in many parameters: Please enter the minimum paired-end in...
This depends on how the program actually reads the data that you type in - it's likely that its reading stdin, so you could use separate files with the parameters and pass them in via redirection: ./VariationHunter_SC < parameter-file It's also possible that the program will accept parameters on the command line, but ...
7,353,075
7,353,158
What is the best practice of type conversion overloading?
class A { public: A ( unsigned _a ) : a (_a) { } operator unsigned& () { return a; } operator const unsigned () const { return a; } unsigned a; }; In the above example, I created two type conversion operators, one gives reference, one gives a copy. Both have d...
How about making the second one const as you're returning a copy anyway. That will remove the ambiguity: class A { public: A ( unsigned _a ) : a (_a) { } operator unsigned& () { return a; } operator unsigned () const // make this one const { return a; } unsigned...
7,353,218
7,353,233
Finding NULL in a vector
I'd like to find out if a vector of pointers contains an entry that is NULL, preferably using code in the STL and not writing a loop. I've tried this expression: std::find(dependent_events.begin(), dependent_events.end(), NULL) But I get errors telling me that I have a "comparison between a pointer and an integer." Is...
NULL in C++ is just an integer constant. The pointer conversion is implicit in appropriate contexts, but this isn’t one. You need to cast explicitly: std::find(dependent_events.begin(), dependent_events.end(), static_cast<P>(0)); Where P is the appropriate type of the pointers in the collection. Alternatively, Eddie h...
7,353,254
7,355,724
Having a DLL with C++ class thats constructor takes in other C++ class, how to make C# capable of creating its instance?
My problem is quite simple: I have many DLLs with C++ classes that interfaces look like this: // Boost #include <boost/asio.hpp> #include <boost/property_tree/ptree.hpp> class service { public: virtual void service(boost::shared_ptr<boost::asio::ip::tcp::socket>, boost::property_tree::ptree) = 0; }; I want to...
You cannot directly create instances of native C++ classes in C#. The easiest thing to do would be to create a C++/CLI class that wraps the native class and exposes the members you need. You would have to provide the arguments to the underlying native class in your constructor, and figure out some type of scheme specif...
7,353,272
7,353,541
Avoid pointers and #defines when programming in an Arduino?
I was looking over the StyleGuide for the Arduino when I noticed that in the Commenting your Code section, it recommends to avoid using pointers and #defines. Is there a reason the writer stated this? There isn't an explanation as to why he/she stated this. It doesn't make sense to me. Is this something specific to emb...
I don't know the specific reason the author wrote it, and I am not familiar with the library's written style - so I am going to answer in general terms of C++ programs. I assume the preference is given because modern C++ typically favors other idioms, many of which were designed to avoid or minimize the issues frequent...
7,353,305
8,549,056
Specify Log file when setting up ICE communicator
When initializing an ICE communicator, is it possibly to specify a different log file than what is named in the config file? I want to change where Ice.StdOut and Ice.StdErr log too programatically.
This will help http://www.zeroc.com/doc/Ice-3.3.1/manual/Adv_server.33.20.html
7,353,384
7,353,458
What's the cleanest way code-wise to return a statically sized array from an object?
I have a situation where a class holds a vector of constant size 5. I need the data from the vector as an array of size 5 as our std::vector implementation doesn't appear to use contiguous memory (please don't argue about that, I know it should and we've checked it to death). The contiguous memory block is required s...
boost::array is intended for arrays of fixed size, you can always use that. It uses contiguous memory. Later edit: as correctly pointed out by commenters, std::array is available in the new standard.
7,353,561
7,353,608
Will a variable go out of scope when the function returns?
void main() { File f; DoSomething(f); DoSomething2(&f); } void DoSomething(File& f) { f.Process(); } // will f go out of scope when this function returns? void DoSomething2(File* f); Two questions: As seen in the comment, will f go out of scope when the function returns? Do you suggest writing funct...
f the reference local to DoSomething will go out of scope, but this obviously has no consequences. The f object local to main goes out of scope only after the end of the main (which, incidentally, should be int main. To sum it up, references are aliases to objects, but the original objects retain their scope, as happe...
7,353,703
7,390,089
error while configuring Qt 4.6.2 on ubuntu - "You don't seem to have 'make' or 'gmake' in your PATH. cannot proceed"
I am trying to install Qt 4.6.2 on ubuntu. When I run the configure script I get the following error message "You don't seem to have 'make' or 'gmake' in your PATH. cannot proceed". On echo of the PATH variable I get /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games on running the command $whic...
I downloaded the source again. I am able to run configure without any problems. Seems like there was an issue with the earlier source.
7,353,745
7,353,943
Qt and sound processing
I need to increase tempo of voice in sound file. (This effect will speed up the playing but leave the original tempo). Any ways to do this with c++ and Qt media library? Thanks. Any links are excepted.
You may want to try SoundTouch.
7,354,118
7,354,320
Disable items in a CheckedListBox in MFC
Does CheckedListBox::Enable() to enable/disable items should behave like GetDlgItem(checkedbox)->EnableWindow(False), for a simple checkedbox, I mean for the last one, the item has the aspect of a disabled item, but for checkedlistbox the item has a normal aspect but I can't select it. So is this normal for disable ite...
Try to avoid using GetDlgItem CCheckedListBox::Enable() is used to enable and disabled the individual checkbox in the list based on the index you pass into it. EnableWindow is intended to enable or disable the entire control. In the case of a checkbox I would expect these to be similar however the CCheckedListBox may h...
7,354,239
7,354,474
How should I approach this web architecture involving c++ heavy load library and php front end
I have c++ api that its job is connect to some server , this is the only way I can connect to this server via this c++ lib Now. I need to be able to let users to register to web site done in php ( already done no problem here ) For each user I need to run this c++ lib to perform some tasks for the user and return res...
You could enter these tasks into a job system or queue, such as Gearman. Jobs can be ran synchronously (get the results immediately) or asynchronously (for tasks that take a while and don't need an immediate result sending back to the visitor).
7,354,305
7,354,445
c++: Using X Macro to define enum and string array inside class?
Using C++ (Visual Studio). I'm trying to find a solution for converting an enum to a string. I came across X Macros (http://drdobbs.com/cpp/184401387) which seems to be a reasonable solution but I'm having a hard time getting it to work inside of a class. All the examples I've seen show everything defined outside of...
The problem is that you can't initialize a non static constant inside a class definition. You would probably have to do it like that: // MyClass.h class MyClass { public: MyClass(); virtual ~MyClass(); #define X(a, b) a enum Colors { #include "ColorNames.h" }; #undef X static const...
7,354,597
7,363,042
C++ subclass using keyword question
Say I have the following: template<typename TemplateItem> class TestA { public: TemplateItem Item; void Function1(){;} void Function2(){;} void Function3(){;} void Function4(){;} //Etc etc number of functions is quite lengthy }; template<typename TemplateItem> class...
If you really really want to do this, why not make a filename.in and then create filename in your makefile or what have you with a shell script or a perl script or similar? That's been my approach for writing tedious code more than once.
7,355,197
7,355,339
Assertion trying to delete an empty object
trying to solve a mem leak I've changed this: void addListener(IListener* listener, const std::string& appender ) { std::pair<t_ListenerVectorMap::iterator,bool> p = listenerVectorMap.insert(std::string(appender), new t_ListenerVector); p.first->second->push_back(listener); //add the appender addA...
For this answer I am assuming that the type of t_ListenerVectorMap is boost::ptr_map<std::string, boost::ptr_vector<IListener>>. If it isn't then this answer is probably worthless. You have a misunderstanding about how boost::ptr_map works. It is true that your original code contains a memory leak, but your replacemen...
7,355,239
7,355,367
Ways to return objects with constant members from a function
Suppose you have a class with a member variable declared constant. class Test { public: Test(const int const_param) : const_member_(const_param) {} private: const int const_member_; }; We want a function that will return an instance of this object either as a "return value" Test Foo(); Test* Foo(); Tes...
You can just return such an object by copy, unless you have good reason do avoid this design: Foo make_foo() { int n = get_mystery_value() Foo x(n); x.manipulate(); return x; } If you'd rather handle the object by pointer, use std::shared_ptr<Foo> instead: std::shared_ptr<Foo> make_foo() { int n = roll_dice(...
7,355,295
7,355,322
Pass an array through a function
I'm trying to pass a simple array through a function to compute the mean. int main() { int n = 0; // the number of grades in the array double *a; // the array of grades cout << "Enter number of scores: "; cin >> n; a = new double[n]; // the array of grades set // to the siz...
There's no loop in your function. It should be something like: double sum = 0; for (int i = 0; i != n; ++i) sum += values[i]; return sum / n; I'm surprised your current version only takes the last number, it should only take the first number, since *values is the same as values[0]. A better solution uses idiomatic ...
7,355,388
7,355,402
basic question on std::vector in C++
C++ textbooks, and threads, like these say that vector elements are physically contiguous in memory. But when we do operations like v.push_back(3.14) I would assume the STL is using the new operator to get more memory to store the new element 3.14 just introduced into the vector. Now say the vector of size 4 is store...
std::vector first allocates a bigger buffer, then copies existing elements from the "old" buffer to the "new" buffer, then it deletes the "old buffer", and finally adds the new element into the "new" buffer. Generally, std::vector implementation grow their internal buffer by doubling the capacity each time it's necessa...
7,356,242
7,357,515
C++ - Build Order and Dependency Problem
I seem to be misunderstanding something related to build order dependencies in C++. So I have this code, which defines a class that I use as a functionoid (object whose purpose is to substitute for passing a function pointer): #include "Imports.h" class X: public Y { public: X (T* t) { this->t= t; } virtual ...
I solved my problem. The issue was that I was doing the above code inside a header file. The compiler understandably couldn't compile t->booleanReturningFunction() based on a forward reference (it needed to see the class declaration to know what address to bind the function call to).
7,356,366
7,356,391
Same old identifier not found error in C++
Hello I've been trying to resolve the issue that I've been having with the code I am working on at the moment. I have looked at other posts but couldn't find anything relevant. Basically, i have added all the necessary files: header and source files but still getting errors. One of many is "'setValue': identifier not ...
You're using a member function without having an instance. You need to create an object and then call it on that object: CDoubleVector dv; ... dv.SetValue(i, sqrt(_spatialCorrFunc.param[i])); // etc You can only use the plain SetValue(something) when you're inside a member function in the class that has the member Set...
7,356,378
7,356,432
cout vs printf -- order of execution
Possible Duplicate: Compilers and argument order of evaluation in C++ cout << order of call to functions it prints? This: int k=3; printf("%d %d %d",k++,k,++k); Gives output as 4 4 4 because they are pushed into the stack as: %d%d%d 4 -- for k++ 4 --for k 4 --for ++k Right? This: int k = 3; cout << k+...
This is undefined because there is no sequence point between the , in the printf statement. Without a sequence point the compiler is free to order writes to the memory location k as it wills. Now you may be wondering 'what the hell is a seqeunce point' and why is it relevant? Basically a sequence point is a point in th...
7,356,436
7,356,514
When to use std::vector<unsigned char> vs. std::vector<char>
Which of one of these is best suited for managing a character buffer that can be easily converted to std::string and passed to and used ( i.e. read / write ) in C functions std::vector<unsigned char> std::vector<char>
char's signedness depends on the compiler.1 It can represent a unsigned char or signed char. Which type is used when representing a string is dependent on the compiler - therefore you should use char for portability, and clarity. If that isn't enough, would the less typing needed when writing char convince you? :) Agai...
7,356,485
7,356,828
Debugging release build on a client's machine
We have a native C++ Win32 .exe built using Visual Studio 2005 that works flawlessly on all the machines we've tested in-house on (XP 32-bit, Vista 32-bit & Windows 7 64-bit). But of course, it crashes repeatedly on a client's 32-bit Vista machine. Digging around on several websites I found tidbits that indicate if I s...
We are able to get crash dumps from our Release builds out in the field and do not need to ship the pdb files with our product. We build in calls to create the crash dump file ourselves in our top-level exception handler using MiniDumpWriteDump(). But even without that, you could have the user generate the crash file a...
7,356,499
7,356,505
Unresolved externals error
I know there's a lot of these sorts of questions but I'm not sure what I'm doing wrong exactly. I have two classes, Player and HumanPlayer. HumanPlayer is supposed to inherit from the Player class. When I'm trying to do the constructors in the HumanPlayer.cpp file and compile, I get the following errors: Error 2 e...
You did not implement the constructor Player::Player() that takes no arguments. And since HumanPlayer::HumanPlayer() calls the Player::Player() constructor that you never implemented, you have a problem.
7,356,603
7,357,299
References to incomplete types
According to the C++03 standard, is it valid to have references to incomplete types? I'm not aware of any implementation that implements references as any other than non-null pointers, so such code ought to work. However, I wonder whether references to incomplete types are standard conforming. I would appreciate answer...
The C++ standard doesn't explicitly say, as far as I know, that you can have a reference to an incomplete type. But the standard does have a section that specifies when a type must be complete: 3.2 One definition rule [basic.def.odr] 4. Exactly one definition of a class is required in a translation unit if the class...
7,356,607
7,393,300
How to get the current most derived state in a boost::statechart state_machine object?
I am using boost::state_chart library. For debug purposes, I would like to know at any given time the state of my state machine. How to get the current (most derived) state in the state_machine object ?
You can get at the current state object(s) with state_machine::state_begin and state_machine::state_end, see "Custom State Queries" here: http://www.boost.org/libs/statechart/doc/tutorial.html#StateQueries These give you base class pointers, if you want to get at the most-derived type you'd have to employ a visitor of ...
7,357,042
7,357,082
Pre-compiled header warnings on Linux (too short to be a PCH file)
I have a header in my project, called Core.h, that I use as a pre-compiled header: $(CXX) $(CXX_CFLAGS) -x c++-header Core.h Which creates a file named Core.h.gch *#include "Core.h" is the first directive of every source file in the module. On OS X, it works fine -- my project compiles fine & it compiles pretty fast. ...
Are you using a parallel make? Possibly g++ is trying to read the .gch file while another instance is writing to it.
7,357,078
7,357,103
Why doesn't C++ need forward declarations for class members?
I was under the impression that everything in C++ must be declared before being used. In fact, I remember reading that this is the reason why the use of auto in return types is not valid C++0x without something like decltype: the compiler must know the declared type before evaluating the function body. Imagine my surpr...
The standard says (section 3.3.7): The potential scope of a name declared in a class consists not only of the declarative region following the name’s point of declaration, but also of all function bodies, brace-or-equal-initializers of non-static data members, and default arguments in that class (including such things...
7,357,136
7,357,388
Analysing audio data for attributes at time intervals
I've been wanting to play around with audio parsing for a while now but I haven't really been able to find the correct library for what I want to do. I basically just want to parse through a sound file and get amplitudes/frequencies and other relevant information at certain times during the song (like every 10 ms or s...
For parsing and decoding audio files I had good results with libsndfile, which runs on Windows/OSX/Linux and is open source (LGPL license). This library does not support mp3 (the author wants to avoid licensing issues), but it does support FLAC and Ogg/Vorbis. If working with closed source libraries is not a problem fo...
7,357,331
7,357,352
Is the at() const accessor for map standard in C++11?
I was trying to figure out how to return a value from a map in a const method and I stumbled on the at() method for map in gcc 4.6. When I looked this up I realized it was non-standard: C++ map access discards qualifiers (const) But it sure is a whole lot less verbose than the find() approach. I was wondering if the C+...
Yes. std::map has an at member function in C++11 with the following specification (23.4.4.3/9): T& at(const key_type& x); const T& at(const key_type& x) const; Returns: A reference to the mapped_type corresponding to x in *this. Throws: An exception object of type out_of_range if no such element is present. Co...
7,357,349
7,361,097
WinAPI Aero Glass without ATL/WTL/MFC/SDK/etc
I've been looking for ages for C++ examples for Aero Glass interfaces using just WinAPI (CreateWindow/CreateWindowEx) without ATL/WTL/MFC/etc. I found someone linking to one somewhere on a forum but the link was dead and I couldn't find any others. Any ideas where I can find one?
The samples on this MSDN article are not specific to any framework (except Windows)
7,357,687
7,357,871
Private variable in Qt
I have two classes under QT, one to make a form, the other to send the collected data on the serial port. There is a button to submit and send the information on the serial port. The first class "myform" contains the file descriptor variable and the slot function for the submit button. class myform: public QWidget...
Derived class construction involves base class sub-object construction first followed by derived class sub-object. So, derived class object has two sub-objects. myform *trial = new myform; trail has a sub-objects of type QWidget, myform. Now this myform sub-object has it's own member variable(s) serialfd which is uni...
7,358,017
7,358,075
clang_complete error: unknown argument: '--std=c++0x'
clang++ version: 2.9 vim version: 7.3 I write my .clang_comple --std=c++0x with follow source code test.cc: int main () { return 0; } And the clang_complete shows test.cc|| unknown argument: '--std=c++0x' in the quickfix list. I try to add the option with set g:clang_user_options="--std=c++0x" the problem is st...
It isn't --std=c++0x but -std=c++0x according to the docs. Try it but I have never used clang though. From docs : To use with clang you can: clang++ -stdlib=libc++ test.cpp clang++ -std=c++0x -stdlib=libc++ test.cpp
7,358,188
7,358,348
Using box.net, dropbox, (OR ANY cloud storage) with a C++ application
How do you use cloud storage such as Dropbox in your C++ Apllication ? I've checked out their API and they only have Java, Python, and Ruby options. If you cant use dropbox with a c++ app, is therte any cloud storage provider that has an API for C++.
The drop box APIs seem to be wrappers for a http interface. So if you want to hit them up from C++ you can use a http supporting library like libcurl to access stuff using the REST api
7,358,212
7,358,256
Change embedded destination port in compiled application
I have a compiled client application without the source code. It connects via TCP to my server on port 7777 (this is the destination). I would like to change the application to use a different port and there is no settings on the client to change it easily. This leads me to believe that it is hard-coded into the applic...
How did you compile this without the source code? That question aside. Look for 7777 (hex 1e61) i.e. 1e followed by 61 (or the other way around) in a binary editor and change it.
7,358,233
7,375,891
C++0x, user-defined literals with friend operator ""()
Will it be possible and/or useful to define an operator "" (...) as a friend function? class Puzzle { friend Puzzle operator "" _puzzle(const char*, size_t); ... }; void solve(Puzzle); int main() { solve("oxo,xox"_puzzle); }; I am thinking about "useful" especially, because of the rule that operator "" shall be ...
The Standard addresses this directly in the only place it mentions any restrictions on the declarations of user-defined literals, §13.5.8/2: A declaration whose declarator-id is a literal-operator-id shall be a declaration of a namespace-scope function or function template (it could be a friend function (11.3)), an ex...
7,358,579
7,358,828
c++ mcrypt error at mcrypt_generic
I have the following code: [test.cpp] #include <mcrypt.h> #include <string> #include <iostream> #include <vector> #include <stdio.h> #include <stdlib.h> #include <string> using namespace std; int main() { char algo[] = "rijndael-256"; char mode[] = "cbc"; char *block_buffer=(char*)"HELLO!! MY NAME IS: "; cout<<...
You should invoke mcrypt_generic() with a char*, not a char** as you do: mcrypt_generic(td, block_buffer, sizeof(block_buffer)); ^^^ ^^^^^^^^^^^^^^^^^^^^ ouch! Also, the length is wrong, as sizeof(block_buffer) is just be the size of the pointer, not t...
7,358,588
7,359,692
Exception handling mechanism on Solaris
I'm building an error handling mechanism for a C++ application. Right now, I got the windows part done using VectoredExceptionHandling and I wanted to know if there is a similar concept on Solaris. Basically, whenever an exception is thrown from anywhere in the program, I want to have a callback called. Under windows, ...
Not 100% if this will work, but you can try to mimic the way gdb's catchpoints work: see http://www.delorie.com/gnu/docs/gdb/gdb_31.html The key piece of info is this: "To stop just before an exception handler is called, you need some knowledge of the implementation. In the case of GNU C++, exceptions are raised by cal...
7,358,613
7,367,986
Sending floating point numbers to QuartzComposer via UDP with C++
In the another question a user provided a method to send data to QuartzComposer via UDP. It appears that QuartzComposer is very particular about the padding of byte data sent to it. In particular it requires that each character sent be preceded with "\0\0\0". I was able to mock up a quick Python program to solve this p...
I don't have a compiler handy, but this should be sufficient. We do the string conversion Create a buffer 4 times the size (plus 1 for the null termination), initialized to 0 Copy in the string at every 4th position. I am not sure if asio expects the null terminator to be part of its size, so I followed your example....
7,359,101
7,361,719
Using created DLL-file (call function from application)
I have got a dummy question. I have three C files: f1.c f2.c f3.c, which contain: // f1.c int f1() { return 2; } // f2.c int f2() { return 4; } // f3.c int f3() { return 10; } I have already 3 object file, when i run the following command (i use mingc under windows7): gcc -c f1.c f2.c f3.c and i create ...
Assuming you have the header, the only thing that you are missing is the A archive, which the linker needs in order to figure out what a DLL provides. Change this: gcc f1.o f2.o f3.o -o test1.dll -shared To this: gcc f1.o f2.o f3.o -o test1.dll -shared -Wl,--out-implib,libtest1.a Then, to link with the shared libra...
7,359,276
7,359,428
Why vector.push_back(auto_ptr) wouldn't compile?
I learned that STL can forbid programmer putting an auto_ptr into a container. For example following code wouldn't compile: auto_ptr<int> a(new int(10)); vector<auto_ptr<int> > v; v.push_back(a); auto_ptr has the copy constructor, why this code can even compile?
Looking at the definition of std::auto_ptr: namespace std { template <class Y> struct auto_ptr_ref {}; template <class X> class auto_ptr { public: typedef X element_type; // 20.4.5.1 construct/copy/destroy: explicit auto_ptr(X* p =0) throw(); ...
7,359,284
7,359,349
unordered_map error in GCC
When was the unordered_map concept built into g++? Because the following code throws an error. #include<iostream> #include<unordered_map> #include<stdio.h> using namespace std; std::unordered_map<std::int,int> mirror; mirror['A'] = 'A'; mirror['B'] = '#'; mirror['E'] = 3; int main(void) { std::cout<<mirror['A']...
The problem is your assignment. You cannot assign values to your map in this place. C++ is not a script language. This program works fine on my machine with gcc4.6: #include<iostream> #include<unordered_map> std::unordered_map<int,int> mirror; int main() { mirror['A'] = 'A'; mirror['B'] = '#'; mirror['E']...
7,359,306
7,359,416
How compute the offset of struct
I found a method of computing the offset of struct. as follow: #define offsetOf(type , f) ((int)\ ((char *)&((struct tagName*)0)->f-(char*)(struct tagName*)0)); but I often write it like this: #define offsetOf(type , f) ((int)(&((struct tagName*)0)->f); The book said the subtraction of NULL pointer is to make su...
The standard library should supply an offsetof that does exactly what you want, I would strongly recommend that you use it, as many compilers would issue a warning for the kind of code that would be required for a custom variant. Anyway, the subtract will take your code from the pointer domain to the domain of size_t. ...
7,359,550
7,359,603
transform_iterator not compatible with std::iterators?
I'm having problems using boost::transform_iterators where "ordinary" iterators are expected. For instance, I want to add all keys from a map to a set. I wrote the following short snippet: template <typename K, typename V> struct map_keys { typedef const K& result_type; const K& operator()(const std::pair<K,V>&...
Ok, solved it myself suddenly. The problem is the typedef result_type (which is not mentioned in the documentation, but unless I have it, the code does not compile (result_type is not a member of map_keys<K,V>)). If I instead typedef it as typedef K result_type; It works. I suppose as it was written earlier, it retur...
7,359,572
7,359,609
Read N bytes from file and append them to a std::vector
I want to read N bytes of data from a file stream and append them to a vector. So let's say we have a basic_ifstream<uint8_t> myFileStream; and a vector<uint8_t> myBuffer; Currently I'm doing something like this: myBuffer.reserve(N); for (int i=0; i<N; ++i) { uint8_t tmpByte; myFileStream.read(&tmpByte, 1); ...
Your problem is that resize may need to reallocate the whole vector, and thus invalidate your previous ptr. You need to take the pointer only after resize. std::size_t oldSize = myBuffer.size(); // resize first myBuffer.resize(oldSize + N); uint8_t* ptr = &myBuffer[oldSize]; // already first element after existing data...
7,359,637
7,359,711
Map::using size() and looping
//employee is class with public members salary and nname int main() { map<int,employee> employees; employee e1; strcpy(e1.nname,"aaa"); e1.salary=25000; employee e2; strcpy(e2.nname,"ccc"); e2.salary=26000; employees[1]=e1; employees[2]=e...
You are displaying employees[i], where i= 0,1,2,3,4,5. Why are you displaying 6 entries if employees.size() == 3 prior to entering the for-loop? The answer is, that when i==0, you are adding an entry to the map at employees[0]. (This is because map::operator[] returns a reference, and if the entry does not exist, it cr...
7,359,660
7,359,710
"Does not name a type" error even though I declare right before assigning the values
I have slimmed my problem down to the following code: #include <iostream> using namespace std; struct hello { int array[4]; array[0] = 1; array[1] = 2; array[2] = 3; array[3] = 4; }; And when I compile this I still get the 'array does not name a type' error, on every line where I assign a value. ...
Assignment statements like array[0] = 0; cannot go into the struct definition, the need to go into an executable block of code like a function, a constructor or similar. struct hello { int array[4]; hello(){ array[0] = 1; array[1] = 2; array[2] = 3; array[3] = 4; } };
7,359,664
7,359,840
Are dynamic_casts safe to remove in production code?
dynamic_casts are slower, but they are safer than static_casts (when used with object hierarchies, of course). My question is, after I've ensured in my debug code that all (dynamic) casts are correct, is there any reason for me not to change them to static_casts? I plan on doing this with the following construct. (Btw,...
after I've ensured in my debug code that all (dynamic) casts are correct, is there any reason for me not to change them to static_casts? IMHO, If you are 100% sure that all dynamic_cast<> are correct, then there is no reason for not changing them to static_cast<>. You can change them.
7,359,933
7,362,460
Storing Tile Data In Excess of 100 Million Tiles Per Layer Multiple Layers
Problem: i am trying to store tile data for my map class. i had the idea of using a palette per layer, the palette would describe the data in the layer which would be an array of bytes with each byte representing a tile type. this means 1 layer of 100 million tiles would equal ~96mb. however i overlooked how much data ...
I suggest representing your data in an array which maps to the two dimensional plane using a space filling curve such as the Hilbert curve. Then, compress this using a combination of Huffman coding and run-length encoding. This will be particularly effective if you data is often repeated locally (i.e. there are lots of...
7,360,500
7,360,564
What are the differences between RedrawWindow and UpdateWindow in Win32?
What are the differences between RedrawWindow and UpdateWindow in Win32? Since they seem to have the same purpose to refresh a window, what are the differences?
RedrawWindow is typically used to force a redraw of the entire window (or some specified region within) right now. UpdateWindow will force a redraw of only the update region of the window, i.e. that part of the window that has been invalidated (e.g. by calling InvalidateRect) since the last paint cycle.
7,360,611
7,360,714
Why is this char stopping my program?
Does the newline character have some kind of special significance in c++? Is it a non-ASCII character? I'm trying to build a Markov chain for each unique n-character substring within a larger piece of text. Every time I come across a new unique substring I enter it into a map whose value is a 256-element vector (one el...
Your GetNextChar function is assuming that if you are at the last character in some line, there will be a character in the next line. What happens if there is no character in that next line? This can happen in two places: When you have hit end of file, or when the next line is the empty string. The second line is the e...
7,360,752
7,361,019
How C++ virtual inheritance is implemented in compilers?
How the compilers implement the virtual inheritance? In the following code: class A { public: A(int) {} }; class B : public virtual A { public: B() : A(1) {} }; class C : public B { public: C() : A(3), B() {} }; Does a compiler generate two instance of B::ctor function, one without A(1) call, and o...
It's implementation-dependent. GCC (see this question), for example, will emit two constructors, one with a call to A(1), another one without. B1() B2() // no A When B is constructed, the "full" version is called: B1(): A(1) B() body When C is constructed, the base version is called instead: C(): A(3) ...
7,360,767
7,361,138
Relative paths not set at debugging, Why?
I retrieve the values using simple C++ code to check the assigned values of XML Loader and load the XML scenario file by setting relative path like this. "loader.LoadXMLScenarioFile("relative path");" But when debugging loader doesn't load the value if we are not setting up the absolute path. But its successfully writ...
Since you are using VS2008 you should double check your debug settings. Especially the path settings for the debugger. Look at Properties->Configuration Properties->Debugging. Is the working directory really what you expect for your relative path? By default it is set $(ProjectDir) which is not the directory where your...
7,360,833
7,360,924
How to wait for a window to finish its painting in Win32?
I use the function PrintWindow to get the screenshot of a certain window. However, due to certain reason, the call to PrintWindow usually triggered when the window is drawing itself, and thus some parts of the window which have not been drawn yet are totally black. Any solution to wait for the window to finish its pai...
Waiting for the window to finish its painting is not the solution to the problem. Or, put another way, the problem is not that PrintWindow is called whilst the target window is part way through its paint cycle. PrintWindow functions by posting a WM_PRINT (or WM_PRINTCLIENT) message to the target window and then waiting...
7,361,239
7,361,317
How to convert a string to char[]
Possible Duplicate: Convert std::string to const char* or char* i've got a line from a txt data with this methode for ( int anrede=0;!user1.eof();anrede++){ if (anrede==1){ getline(user1, inhalt_anrede); } } now inhalt_anrede should be converted to char[5] anrede i have used anrede in ot...
std::string str("abc"); char cstr[5]; strcpy(cstr, str.c_str()); Be sure not to overflow the c string (can contain only 4 chars + NULL in this example).
7,361,251
7,361,308
Difference between sequence containers and container adaptors in c++
What is the difference between sequence containers and container adaptors in c++? Here i mean sequence containers as vectors, deque, list while container adaptors as stack, queue, priority_queue. When do we prefer sequence containers and container adaptors?
Sequence containers You could see sequence container as containers "built from scratch". They use different structures to hold data and have different algorithmic time to insert, delete and retreive element. You can find a lot of information about the algorithmic time of containers here Container adapters Container ad...