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
3,898,547
3,898,576
How does Boost ASIO receive_from return underlying socket errors?
i.e. will the blocking version return -1 on error. Or more to the point, how do you know the call failed? does boost::asio::ip::udp::socket::receive_from() return -1 on error The normal BSD socket API receive_from call will return -1 on errors and you can look at errno for the specific error code. Does the boost vers...
It throws a boost::system::system_error exception on failure. There's an overload taking a parameter if you don't want to handle the exception.
3,898,593
3,898,642
If I can take a normal pointer to a variable within a class, what's the point of class member pointers?
Take this code: struct mystruct { int var; mystruct() : var(0) {} }; int main() { mystruct ins; int* p = &ins.var; *p = 1; } So what are some concrete really good examples of uses for the class member pointer? int X::*p = &X::data; /* p contains offset */ X object; X *objptr = new ...
It seems the your question is about pointers of pointer-to-data-member type. In C++ there are also pointers of pointer-to-member-function type. The two have something in common at some abstract level, but otherwise they are different. Pointer of pointer-to-data-member type is applicable to any instance of the class. An...
3,898,651
3,900,810
XPATH contains(string, string) Not Working
sI have an XML file that looks like the following... <a> <b> <version>1.0</version> <c> <Module>foo.EXE</Module> </c> <c> <Module>bar.DLL</Module> </c> </b> </a> I have a COM DLL that uses MSXML2:IXMLDOMNode objects that call "selectNodes" something like... CComPtr<MSXML2::IXM...
You have to issue this on the document object: setProperty("SelectionLanguage", "XPath"); before calling the SelectNodes() methd with XPath expressions. The default value is not XPath but some earlier selection language.
3,898,663
3,898,666
Why isn't this compiling?
I don't understand why the below code does not build: bool AguiRectangle::pointInside(const AguiPoint &p ) { if(p.getX() < x) return false; if(p.getY() < y) return false; if(p.getX() >= x + width) return false; if(p.getY() >= y + height) return false; return true; } I get this: Error 1 error C...
The functions AguiPoint::getX() and AguiPoint::getY() need to be defined as const member functions or you won't be able to call them on const AguiPoints. You attempted to call a non-const member function on p, which is reference to a const AguiPoint. Since references are aliases to the original object, calling a non-co...
3,898,704
3,898,729
GCC inline assembly: constraints
I'm having difficulty understanding the role constraints play in GCC inline assembly (x86). I've read the manual, which explains exactly what each constraint does. The problem is that even though I understand what each constraint does, I have very little understanding of why you would use one constraint over another,...
Here's an example to better illustrate why you should choose constraints carefully (same function as yours, but perhaps written a little more succinctly): bool add_and_check_overflow(int32_t& a, int32_t b) { bool result; __asm__("addl %2, %1; seto %b0" : "=q" (result), "+g" (a) : "r" (b)...
3,898,728
3,898,779
c++ convert matrix into row pointer vector
vector<vector<int> > mymatrix; vector<int> *ptr_vec; How do I make the ptr_vec point to the vectors which are inside mymatrix one after another. In more details Let's say mymatrix.at(0).size() gives 10, and mymatrix.at(1).size() gives 14 ..if I go ptr_vec->at(15) it should give me the fifth member in mymatrix.at(1) ho...
Given your clarification "how to make that ptr have all the addresses of what ever other vectors" I think you placed the * incorrectly in your declaration. It think you meant ptr_vec to be a vector of pointers. If so, ... #include <iostream> #include <vector> #include <stddef.h> using namespace std; typedef ptrdiff_t ...
3,898,772
3,898,777
How to reduce redundant code during error checking
NOTE: The restriction is that I cannot use exceptions (the code is eventually compiled with exceptions disabled - not under my control). The project is a real-time 3D graphics application. I am using my own error class (I had posted a question regarding that not too long ago) which each class uses. Very simple, all ...
Assuming you really don't care which function fails or can determine which one failed by some means other than testing the return value, if (CreateGrid() != NO_ERROR || SomeOtherFunc() != NO_ERROR) { // Handle error }
3,898,817
3,898,919
C++ Converting a float to an unsigned char?
I'm new to C++, and doing a bit of googling I thought sprintf would do the job, but I get an error upon compiling that I can't convert between an unsigned char and a char. I need an unsigned char because I am going to print to an image file (0-255 RGB). unsigned char*** pixels = new unsigned char**[SIZE]; vector<float...
I'll guess that the floats are in the range 0.0 ... 1.0, then you do it like this: float redf = 0.5f; unsigned char reduc = redf * 255; The variable reduc is now 128. EDIT: complete example, outputting image in Net PPM format. // Usage // program > file.ppm #include <vector> #include <iostream> typedef struct { ...
3,898,905
3,899,022
Is it possible to infer which line in source has the problem according to disassembly?
The problem exists at 017D0B5F call eax : 017D0B56 mov esi,esp 017D0B58 mov edx,dword ptr [ebp-20h] 017D0B5B push edx 017D0B5C mov eax,dword ptr [ecx+8] 017D0B5F call eax 017D0B61 cmp esi,esp 017D0B63 call @ILT+2525(__RTC_CheckEsp) (17C49E2h) ...
Looks like it is the pSample->Release() call - what error do you get? 017D0B56 mov esi,esp 017D0B58 mov edx,dword ptr [ebp-20h] // get the pSample this pointer 017D0B5B push edx // push it 017D0B5C mov eax,dword ptr [ecx+8] // move pSample to eax 017...
3,898,929
3,898,937
How to expand the .lib with its source in c++?
Now my problem requires a .lib and I've grabbed all the source for that library,how can I replace the .lib dependance with its source code so that I can trace directly in source level instead of disassembly?
If you compile the source files for the .lib file with debugging information included, then you can continue to link the .lib file into your executable and the debugger will know how to find the source files. You may be using a .lib file at the moment that's compiled without debugging information, so the debugger will ...
3,898,933
3,898,943
Difference in ways of deleting object array
Is there some difference in the following deletions of object array? The first way: MyClass **obj = new MyClass*[NUM]; for (int i=0; i<NUM; i++) obj[i] = new MyClass(val); obj[0]->method(); for (int i=0; i<NUM; i++) delete obj[i]; /// Deletion1 delete obj; /// Deletion1 The second way: MyC...
In your first example, you are explicitly calling the destructor for each object pointed to by members of the allocated array. Then you are deleting the array of pointers (which should really be delete[] because you allocated it as an array, but in practice for this example it probably doesn't matter). In your second e...
3,898,999
3,899,119
c++ 'CA2W': identifier not found
why do i get 'CA2W': identifier not found for(DWORD i = 0; i < numMaterials; i++) // for each material... { material[i] = tempMaterials[i].MatD3D; // get the material info material[i].Ambient = material[i].Diffuse; // make ambient the same as diffuse USES_CONVERSION; // allows ce...
Edit: The OP has just told me that Visual Studio 2010 Express was used to compile the code. That would explain why CA2W couldn't be found, because the Express editions do not include the entire ATL/MFC library. Therefore, my original answer is irrelevant to the OP. The moral of the story: make sure to mention exactly...
3,899,024
3,899,064
Good way to add event handlers?
I'm making a Gui API for games. Basically I have event callbacks in my class which are function pointers. I thought of directly letting the user = the function pointer ex: widget->OnPaintCallback = myPaintFunc; But I don't like how I cannot check for NULL or do anything else. It also makes my class feel exposed. I als...
But I don't like how I cannot check for NULL or do anything else How about making the callback (OnPaintCallback) an object of a class that overloads operator =, that way you can do any additional checking and throw an exception if something goes wrong. You can also overload operator () so that you can call this objec...
3,899,162
3,899,367
How to send keystrokes to an application in C++
I'm trying to make a program to open Acrobat files using Adobe Acrobat Reader and save them in a text file, automatically. What I want my program to do is: open the pdf send Alt + Tab //to move to the acrobat tab send Alt + F //to open file send Down Down Down Down (4 times) //to select 'save as text' option ...
Try AutoIt. From it's website: "AutoIt is a freeware Windows automation language. It can be used to script most simple Windows-based tasks."
3,899,223
3,899,248
What is a non-trivial constructor in C++?
I was reading this http://en.wikipedia.org/wiki/C%2B%2B0x#Modification_to_the_definition_of_plain_old_data It mentions trivial default constructor, trivial copy constructor, copy assignment operator, trivial destructor. What is trivial and not trivial?
In simple words a "trivial" special member function literally means a member function that does its job in a very straightforward manner. The "straightforward manner" means different thing for different kinds of special member functions. For a default constructor and destructor being "trivial" means literally "do noth...
3,899,255
3,899,305
Pointer giving garbage values even after being set
I am having a weird problem with pointers .I am building a k-d tree for ray tracing and during the BuildKDtree function I print root->left and root->right and I get correct values for various attributes stored at node. The moment I complete that code and then try to traverse the tree using the original root's pointer t...
What is the signature of the BuildKDtree function? Is it possible that somewhere there is a pointer but what actually needed is a pointer-to-pointer? Just trying to guess :)
3,899,353
3,899,361
C++ Storing copy of string in vector of pairs
I have a private attribute in a class that is defined as vector<pair<char *, int> > data;. I add data to this vector with data.push_back(make_pair(p, r));. Later when I go to get the data out of the vector I get bad data for the p value. The data returned is like ��U3. I think this is because a pointer to the char arra...
It looks as though you have a pointer to p (which is defined at the time) placed on the stack. Once the stack frame gets popped off you still have the pointer but the memory it points to may be garbage. These sort of dangling pointer problems can get annoying so I'd recommend using the std::string class that is defined...
3,899,448
3,899,498
c++ directx 9 mesh texture
ok so i can load a mesh perfectly but loading its texture is not working. im not sure what im doing wrong. here is my code.. //render a single frame void RenderFrame(void) { d3ddev->Clear(0, NULL, D3DCLEAR_TARGET, D3DCOLOR_XRGB(0, 0, 0), 1.0f, 0); d3ddev->Clear(0, NULL, D3DCLEAR_ZBUFFER, D3DCOLOR_XRGB(0, 0, 0),...
First of all, you're setting all the textures to NULL in your for loop, so of course there's no texture to render! for(DWORD i = 0; i < numMaterials; i++) { /* ... */ texture[i]=NULL; // <--- You're setting all your textures to NULL! } Also: D3DXCreateTextureFromFile(d3ddev, L"ramiz.x", &texture[i]); The ...
3,899,456
3,899,464
Is time complexity for insertion/deletion in a doubly linked list of order O(n)?
To insert/delete a node with a particular value in DLL (doubly linked list) entire list need to be traversed to find the location hence these operations should be O(n). If that's the case then how come STL list (most likely implemented using DLL) is able to provide these operations in constant time? Thanks everyone for...
Insertion and deletion at a known position is O(1). However, finding that position is O(n), unless it is the head or tail of the list. When we talk about insertion and deletion complexity, we generally assume we already know where that's going to occur.
3,899,563
3,899,728
private inheritance, friends, and exception-handling
When class A privately inherits from class B it means that B is a private base class subobject of A. But not for friends, for friends it is a public sububject. And when there are multiple catch handlers the first one that matches (that is, if the exception type can be implicitly converted to the handler's parameter typ...
Nope, that's not what the standard says. It says (C++0x): A handler is a match for an exception object of type E if — The handler is of type cv T or cv T& and E and T are the same type (ignoring the top-level cv-qualifiers), or — the handler is of type cv T or cv T& and T is an unambiguous public base class...
3,899,636
3,899,722
How can I print a Binary Tree Search class Vertically?
I've been learning how to program Binary Tree Search using Linked Lists in C++. Everything works fine and I understand how the Binary Tree works however I would like to be able to print the tree with the head on top and all the nodes following bellow as I try to demonstrate here: [r...
As sbi mentioned, making a left-aligned version is easier than a center-aligned one. But whichever alignment you choose your fundamental algorithmic approach should be: Traverse the tree breadth-first. Do this by using a queue with the following algorithm: Declare a queue Add the root node to the queue While the que...
3,899,688
3,899,716
default virtual d'tor
Let us assume I have two classes: class Base{}; class Derived: public Base{}; none has d'tor, in this case if I declare about variables: Base b; Derived d; my compiler will produce for me d'tors, my question is, the default d'tors of the b and d will be virtual or not?
my question is, the d'tors of the b and d will be virtual or not No, they won't. If you want a virtual destructor, you will have to define your own, even if its implementation is exactly the same as that which would be supplied by the compiler: class Base { public: virtual ~Base() {} };
3,899,755
3,899,760
Can I do this with class objects?
class xyz{ ... ... }; while(i<n){ xyz ob; ... ... } Do I need to destroy the earlier object before reallocating memory to it?
You mean define an object not declare (removed from question). Yes you can do that. No you don't need to destroy it since it's destroyed automatically. The memory is allocated on the stack and will be reused anyway. The compiler can even optimize it in many cases. And HOW could you reallocate the memory anyway?
3,899,819
3,899,834
What is the strongest encryption to use on protecting text?
Hello all I need to encrypt text what is the best encryption to use programmatically ? In general I have input file with string that I need to encrypt then read the file in the application Decrypt it for the application flow . with c++
The strongest encryption is to use a one-time pad (with XOR for example). The one time pad algorithm (unlike most other commonly used algorithms) is provably secure when used correctly. One serious problem with this algorithm is that the distribution of the one-time pad must be done securely and this is often impractic...
3,899,839
3,899,854
converting string to integer problem in c++
i am getting an problem string ccc="example"; int cc=atoi(csession); it says cannot convert ‘std::string’ to ‘const char*’ for argument ‘1’ to ‘int atoi(const char*)’ do i should convert the string to char array and then apply to atoi or is there is any other way
istringstream in(ccc); int cc; in >> cc; if(in.fail()) { // error, ccc had invalid format, more precisely, ccc didn't begin with a number //throw, or exit, or whatever } istringstream is in header <sstream> and in namespace std. The above code will extract the first integer from the string that is, if ccc were "...
3,899,844
3,899,875
detecting a string charset
i am looking for the best linux library that will let me detect a string charset. any idea ?
ICU is a quite good library, you might use ucsdet_detect or ucsdet_detectAll to detect 'possible' matches on the charset of an input buffer.
3,899,870
3,899,916
print call stack in C or C++
Is there any way to dump the call stack in a running process in C or C++ every time a certain function is called? What I have in mind is something like this: void foo() { print_stack_trace(); // foo's body return } Where print_stack_trace works similarly to caller in Perl. Or something like this: int main ...
For a linux-only solution you can use backtrace(3) that simply returns an array of void * (in fact each of these point to the return address from the corresponding stack frame). To translate these to something of use, there's backtrace_symbols(3). Pay attention to the notes section in backtrace(3): The symbol names ma...
3,899,894
3,902,301
How to obtain total available disk space in Posix systems?
I'm writing a cross-platform application, and I need the total available disk space. For posix systems (Linux and Macos) I'm using statvfs. I created this C++ method: long OSSpecificPosix::getFreeDiskSpace(const char* absoluteFilePath) { struct statvfs buf; if (!statvfs(absoluteFilePath, &buf)) { unsigned ...
I suppose the last two answers are correct and useful. However I solved by simply replacing the function statvfs with the function statfs. The block size is then 4096 as expected and everything seems to be correct. Thanks!
3,899,945
3,899,954
How can I automatically load DLLs from a subdirectory?
In Visual Studio, you create a .dll project and it creates a .dll and .lib files. You link statically to the .lib, and if the .dll is in the same folder as the .exe, everything works. I suspect that everything would also work if the .dll was in System32 or any other PATH folder (confirm or correct, please). But here's...
You could use SetDllDirectory for this. The loader will use the additional directory you specify when loading libraries. There can only be one additional directory, however, so you need to make sure that there aren't other calls to this at a later point in your application, otherwise the directory you specify will be...
3,899,973
3,901,577
mingw g++ cant see sdl-config
All works good if I insert sdl-config output manually. How to fix this bug? g++ -O3 -c 'sdl-config --cflags' test.cpp g++.exe: sdl-config --cflags: no such dile or directory
oh... I mixed up ` and ' !!!!! now all works...
3,900,136
3,900,144
Malloc in C++ constructor
I have to interface with some C code from C++ class constructor (Intel library) class A{ A{ x = ippiMalloc(); if(x==NULL) ... } } In the constructor malloc function (intel version) is used. If ippiMalloc function do not succeed what is the correct way to handle it. Throw exception?
Yes, an exception would likely be the most appropriate way to handle the error here -- at least it would be the cleanest way. This is also what the "new" operator would do on failure. If your app isn't exception aware than you have a problem. In which case a factory method on the class might make sense. static A * crea...
3,900,192
3,917,482
MSVC9.0 bug or misunderstanding of virtual inheritance and friends?
consider the following code: class A { friend class B; friend class C; }; class B: virtual private A { }; class C: private B { }; int main() { C x; //OK default constructor generated by compiler C y = x; //compiler error: copy-constructor unavailable in C y = x; //compiler error: assignment opera...
Your code compiles fine with Comeau Online, and also with MinGW g++ 4.4.1. I'm mentioning that just an "authority argument". From a standards POV access is orthogonal to virtual inheritance. The only problem with virtual inheritance is that it's the most derived class that initializes the virtually-derived-from class f...
3,900,237
3,900,245
Detecting if type is a function
template<class T> struct IsFunc { typedef char one; typedef struct { char dummy_[2]; } two; static one f(...); static two f(T (*)[1]); enum {value = (sizeof(f<T>(0)) == 1)}; }; And if I try to run it in main: void functionA(); int _tmain(int argc, _TCHAR* argv[]) { ...
functionA is a function, not a type, so it cannot be a valid template parameter to IsFunc which expects a type. If you need a template to detect whether a type is a function type, there is already boost::is_function (which is part of TR1/C++0x).
3,900,457
3,900,477
Generic inheritance in java
In c++ we can write: #include <iostream> class Base1 { public: void test() { std::cout << "Base 1" << std::endl; } }; class Base2 { public: void test() { std::cout << "Base 2" << std::endl; } }; template<class T> class Derived: public T { }; int main() { Derived<Base1> d1; Derived<Base2> d2; d1.tes...
No. C++'s templates are much stronger than Java's generics. Generics in Java are only for ensuring proper typing during compile time and are not present in the generated bytecode - this is called type erasure. In my scenario I have two subclasses, Sprite and AnimatedSprite (which is a subclass of Sprite). The next ste...
3,900,501
3,900,515
C++ program does not work on some inputs
Hallo I have this assignment to print only alphabets in a C++ string. It works for most input but when [ and ] are present in the input they are printed as well. #include <iostream> #include <string> using namespace std; int main() { string input = "THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG]"; for(...
The problem is here: if(input[i] >='A' && input[i] <= 'z') ^^^ ^^^ You are using uppercase 'A' and lowercase 'z'. The range A-z is not same as A-Z + a-z. The ASCII value of Z is 90 and that of a is 97. Between them there are 6 other characters which you are considering as alphabets. ASCII...
3,900,586
3,900,597
iterator to pointer or reference - ERROR
I have this: //function definition //Point and Range are classes made of 2 ints Point barycenter_of_vector_in_range(vector<cv::Point> &points, cv::Range range); //In other place... vector<vector<Point> > tracks_; //it has some content for (vector< vector<Point> >::const_iterator track = tracks_.begin(); track != trac...
*track is a reference to const vector<Point>, so you have two problems: 1) You're trying to pass a pointer to that into barycenter_of_vector_in_range, which doesn't take a pointer. 2) It's const, and barycenter_of_vector_in_range takes a non-const reference.
3,900,598
3,900,609
How to define two depend classes?
take a look at following simple code : class A; class B { A a; }; class A { B b; }; int main(int argc, char *argv[]) { return 1; } it does not compile, why ? Error Message from GCC (Qt): main.cpp:6: error: field ‘a’ has incomplete type
well that's impossible since A would contain a B which would contain an A etc. if they depend on eachother they could hold references or pointers to eachother or one could hold the other whilst the other holded a pointer/reference.
3,900,629
3,900,764
Imitation of hardware exceptions
Can anyone tell me a code for next function, which raises EXCEPTION_FLT_STACK_CHECK or EXCEPTION_BREAKPOINT, for I could catch them in main func: int _tmain(int argc, _TCHAR* argv[]) { __try { FaultingStack(); // What I need to write in this function??? } __except(GetExceptionCode() == EXCEPT...
Breakpoint exception is raised easily. You can use one of the following (which is all the same): DebugBreak(); // API function __debugbreak(); // MSVC intrinsic __asm int 3; // Actual instruction Now, EXCEPTION_FLT_STACK_CHECK is related to the invalid floating-point register stack state. First one should enable FP ex...
3,900,696
7,762,842
How to move a QGraphicsItem to another scene without losing the mouse grab?
I have one QGraphicsScene as the main scene with several movable QGraphicsItems in it and another QGraphicsScene on top of the main scene as an overlay. The overlay scene is exactly the same size as the user's display, whereas the main scene is much bigger, so it needs to be scrolled up and down automatically. If an it...
What you may need to do is use the drag and drop framework. You can start a system drag when the mouse leaves the initial canvas, and then as long as your overlay scene accepts the mime data you've packed into your QDrag, the two can inter-operate. It's a somewhat frustrating system, since it provides the least-common-...
3,900,784
3,900,898
Can't compile 32bit with 64bit g++
I'm using codeblocks. I'm using ubuntu. Here is output of compilation. g++ -Wall -O2 -m32 -nostdlib -Iinclude -c /home/miroslav/Development/WEBGINE/src/WEBGINE/Component.cpp -o obj/ReleaseCGI32/src/WEBGINE/Component.o g++ -Wall -O2 -m32 -nostdlib -Iinclude -c /home/miroslav/Development/WEBGINE/src/WEBGINE/D...
Be sure to install gcc-multilib and g++-multilib. These depend on both the 64 as the 32-bit gcc and stdc++ libraries.
3,900,819
3,900,843
Polymorphic operator [] implementation
Lets say we have this code: class test_t { void* data; public: template <typename T> T operator [](int index) { return reinterpret_cast<T*>(data)[index]; } }; int main() { test_t test; int t = test.operator []<int>(5); return 0; } Is there a way to convert it to compilable idio...
What you could do is to return a proxy object struct Proxy { template<typename T> operator T() { return static_cast<T*>(data)[index]; } void *data; int index }; Proxy operator [](int index) { Proxy p = { data, index }; return p; } You can resort to obj.get<T>(index) or to something s...
3,900,874
3,901,295
What files are actually included when compiling
I have a very large code, a lot of which is legacy code. I want to know which of all these files are taking part in the compilation. The code is written in GNU compilers and mostly in C/C++, but some in other programs too. Any advice will be highly appreciated. Thanks, Moshe. I am compiling under linux with a mix o...
Two options come to mind. Parse the compilation log Run a build, save the log, and then search in the log. Find the files that are opened during the compilation time. A way to do that might be to use a system tracing tool like strace or library tracing tool like ltrace and then look out for file open calls. See also ...
3,900,890
3,900,956
How to typedef a type derived through several layers of templates?
Maybe my Google-fu just isn't strong enough. Using GCC 4.4.3, I've got a set of classes like this: template <typename storage_t, typename index_t = std::size_t, typename leaf_payload_t = std::size_t> struct btree_node { public: typedef btree_node<storage_t, index_t, leaf_payload_t> this_t; typedef boost...
It looks like a compiler bug to me. To be sure, I put your code into clang and instantiated btree<int>::caching_storage_t, all working fine also with the comment chars removed. It also works on GCC4.5.1 and GCC4.3.4.
3,900,972
3,900,982
upcast at runtime. (Morph from Base Class to derive Class)
class B{ private: int a; } class D: public B{ private: int b; } B* b = new B; Now for some reason I want turn b into a D* Type of Object. e.g. retain the information of B and become D with extra Informations required. What I am currently thinking of is. static_cast to do the upcasting. the additional attr...
If you do a static_cast<> then the additional attributes will not be null or garbage, they will actually be outside the memory allocated for the object. Use dynamic_cast<>, which will properly fail if the variable does not contain the correct type. Also, the similarity between C++ and PHP in this case is merely superfi...
3,901,022
3,901,032
scope of pointers to (local) objects declared within a for loop
I'm not sure if the snippet of C++ code below is legitimate or not: std::vector<int*> myints; for (int i = 0; i<N; i++) { int j = i; myints.push_back(&j); } for (int i=0; i<myints.size(); i++) cout<<*(myints[i])<<endl; How does the compiler handle this ? I understand the variable j itself goes out of scope wh...
Once the block ends, the compiler stops caring about the memory that was previously reserved for them. But even if nothing else disrupts that, you have another problem: all the int*s in the vector<int*> point to the same memory location, so they all have the final value of i.
3,901,051
3,901,071
I have a problem building an array of "*" in C++
I have a program that contains the following piece of code for constructing an array of asterisks: char array[Length][Height]; for (int count1 = 1; count1 <= Length; count1++) { for (int count2 = 1; count2 <= Height; count2++) { strcpy(array[count2][count3], "*"); cout << array[count2][count3];...
Try this: char array[Length][Height]; for (int count1 = 0; count1 < Length; count1++) { for (int count2 = 0; count2 < Height; count2++) { array[count1][count2] = '*'; cout << array[count1][count2]; } } cout << endl; Note that your code contained off-by-one errors: count1 and count2 would g...
3,901,062
3,901,158
Using debug/release versions DLL in C++
I am writing an C++ application that could be compiled under Linux (gcc 4.3) and Windows (MS VS08 Express). My application uses third-party libraries, On Linux , they are compiled as shared libraries, while on Windows, there are two versions "Debug" and "Release". I know that debug version provides extra support for d...
The Debug configuration of your program is compiled with full symbolic debug information and no optimization. Optimization complicates debugging, because the relationship between source code and generated instructions is more complex. The Release configuration of your program contains no symbolic debug ...
3,901,179
3,903,423
Get sound level from device while recording in C++
I want to get sound level, so I can display it in my SDL application (the platform is Linux) when recording sound. How can I do that? I use FMOD API in my app, but for recording, I'm using SoX (forking and using exec() to set it up - probably this could be done better but I don't know how :( ). Should I use some functi...
You can do recording in FMOD if you like. FMOD APIs such as System::recordStart and System::getRecordDriverInfo can be used. FMOD ships examples of recording which you can use as a basis for your solution. Specifically for getting the sound level, if you wanted to do it as a runtime thing you could use Channel::getWave...
3,901,209
3,901,288
Using iostream << to serialize user objects
I want serialize object to binary file using operator "<<", but when I serialize, for example, int fields, I obtained it's symbolic representation: ofstream out("file", ios::out | ios::binary); int i=0xAA; out << i; And output: 0x31 0x37 0x30 i.e. (0xAA -> 170) 170 If I use write function, all ok: out.write((char*)&...
First, a warning: You do know that the bytes within an int, or anything similar, depends on your compiler, computer, and operating system, right? Other systems might output bytes 0x00 0x00 0x00 0xAA for your example above, or something else entirely. Which means that if you send those bytes to a different computer an...
3,901,256
3,901,301
C macro computing the number of bytes that a given compile-time constant requires
Often I have some compile-time constant number that is also the upper limit of possible values assumed by the variables. And thus I'm interested in choosing the smallest type that can accomodate those values. For example I may know that variables will fit into <-30 000, 30 000> range, so when looking for a suitable typ...
Now that this is tagged with c++, I suggest using Boost.Integer for appropriate type selection. boost::int_max_value_t< MyConstant >::least would give the type you are looking for.
3,901,313
3,901,890
The most elegant way to write an abstraction layer
I'm curious how to write an abstraction layer. By abstraction layer, I mean a wrapper above one or more 3rd party libraries. Or do I have to solve it like this? #include<an3rdpartyl> #include<another3rdpartyl> class layer { private: an3rdpartyl* object1; another3rdpartyl* object2; public: //... int loa...
Take a look at the Facade, Adapter, and Bridge patterns. Or even better, just pick up the "Gang of Four" Design Patterns book and learn about software design in a whole new light.
3,901,356
3,901,380
deleting while iterating
Possible Duplicates: Vector.erase(Iterator) causes bad memory access iterate vector, remove certain items as I go. Hi, I wrote this but I am get some errors when running it for (vector< vector<Point> >::iterator track = tracks_.begin(); track != tracks_.end(); track++) { if (track->empty()) { // if track is ...
A vector's erase() invalidates existing iterators, but it returns a new iterator pointing to the element after the one that was removed. This returned iterator can be used to continue iterating over the vector. Your loop could be written like this: vector< vector<Point> >::iterator track = tracks_.begin(); while (track...
3,901,549
3,901,567
How to reduce a number of parameters of a template template parameter
I need to adapt a two parameter template to a one parameter template. I would like to bind the first parameter of a template: template<class T1, class T2> struct Two_Parameter_Template { // Two ctor's Two_Parameter_Template() { }; template<class Param> Two_Parameter_Template(Param) { /* ... */ } }; by u...
You can use boost mpl bind for this However it will not do exactly how you would like it to behave Edit: I saw you made one little mistake in your code that it does not work as you expected: typedef SomeTemplate< bind_1st<Bound_Param_class, Two_Parameter_Template>::eval > ConcreteClass; If you put the eval inside it wi...
3,901,606
3,901,622
Proper way to #include when there is a circular dependency?
I'm using #pragma once, not #include guards on all my h files. What do I do if a.h needs to #include b.h and b.h needs to #include a.h? I'm getting all sorts if errors because by doing this, the pragma once takes effect and one of them is missing each other. How should I do this. Thanks
You need to forward declare the definitions you need. So if A uses B as a parameter value, you need to forward declare B, and vice versa. It could be that just forward declaring the class names: class A; class B; solves your problems. The accepted answer to this question provides some additional guidance.
3,901,630
3,901,666
Performance issue for vector::size() in a loop in C++
In the following code: std::vector<int> var; for (int i = 0; i < var.size(); i++); Is the size() member function called for each loop iteration, or only once?
In theory, it is called each time, since a for loop: for(initialization; condition; increment) body; is expanded to something like { initialization; while(condition) { body; increment; } } (notice the curly braces, because initialization is already in an inner scope) In practice, i...
3,901,747
3,901,772
Why am I getting these linker errors?
I'm getting the following linker errors: Error 1 error LNK2001: unresolved external symbol "public: __thiscall AguiEvent<class AguiEmptyEventArgs>::AguiEvent<class AguiEmptyEventArgs>(void)" (??0?$AguiEvent@VAguiEmptyEventArgs@@@@QAE@XZ) AguiWidgetBase.obj Error 2 error LNK2001: unresolved external symbol "p...
You need to define templated class functions in your header file, you cannot put them in a separate .cpp file (don't even think about using the poorly supported export keyword to do that). The reason for this is because the compiler needs the source code for the template every time it's instantiated: it has to generate...
3,901,783
3,901,794
Detecting array type do not works
template<typename T> class CompoundT { // primary template public: enum { IsPtrT = 0, IsRefT = 0, IsArrayT = 0, IsFuncT = 0, IsPtrMemT = 0 }; typedef T BaseT; typedef T BottomT; typedef CompoundT<void> ClassT; }; template<typename T, size_t N> class CompoundT <T[N]> { ...
Because isArray must take reference, otherwise if you take an array by value it's the same as if you take a pointer :) template <class T> bool isArray(const T& ) {...} because void f(int a[10]); and void f(int* a); are equivalent declarations.
3,901,869
3,901,898
How can I create a C++ project/solution in Visual Studio 2010?
I want to write simple C++ code for adding two integers (in a command line window). How do I do this in Visual Studio 2010? (I know the code for adding the numbers.. I don't know how to prepare the files) @Armen Tsirunyan I did just that, then I added the following code to the c++ file:- #include <iostream.h> main() {...
Open Visual Studio File -> New Project Select Visual C++ -> Win32 -> Win32 Console Application Enter name and location press OK Select Application Settings. Remove the check from Precompiled headers. Add the check for empty project. Click Finish Click Project -> Add New Item -> C++ file Code and enjoy :)
3,901,944
3,903,446
Specify Array from Command Line Argument
I realize that each argument passed from the command line is stored as a string in 'char *argv[]' I'd like to pass $ progname array[500] and pull the string from argv[1] subsequently specifying an array based on what I read in. Any ideas?
Well from your new comment, I will try to answer the question. I am doing most of this to show you one possibility, my code will have some makeshift string parsing and not much error checking, it's just to give you an idea of how you can do it. If you wanted the user to specify the size of an array you wanted to make, ...
3,901,947
3,901,968
How do compilers optimize our code?
I ran into this question when i was answering another guys question. How do compilers optimize the code? Can keywords like const, ... help? Beside the fact with volatiles and inline functions and how to optimize the code all by your self!
Compilers are free to optimize code so long as they can guarantee the semantics of the code are not changed. I would suggestion starting at the Compiler optimization wikipedia page as there are many different kinds of optimization that are performed at many different stages. As you can see, modern compilers are very 's...
3,901,977
3,901,987
C++ String Array, Loading lines of text from file
I have a problem. When I try to load a file into a string array nothing shows. Firstly I have a file that on one line has a username and on the second has a password. I haven't finished the code but when I try to display what is in the array nothing displays. I would love for this to work. Any suggestions? users.txt us...
You cannot create arrays in C++ with runtime values, the size of the array needs to be known on compile time. To solve this you may use a vector for this ( std::vector ) You need the following include: #include <vector> And the implementation for load_users would look like this: void load_users() { std::ifstream d...
3,902,011
3,902,016
What's the difference between new char[10] and new char(10)
In C++, what's the difference between char *a = new char[10]; and char *a = new char(10); Thanks!
The first allocates an array of 10 char's. The second allocates one char initialized to 10. Or: The first should be replaced with std::vector<char>, the second should be placed into a smart pointer.
3,902,066
3,902,495
How to call Java methods from C++ in JNI
So I'm writing an Android app which uses a large c++ library. I have everything working so that the java app can call the c++ delegation methods, but I'm finding myself wishing I could log messages from c++ to the Android log. This is easy from java, but I'm at a loss as to how to call a java method from c++. My sea...
C++ calls to cout and printf will not show up in the LogCat output. There are two solutions. Use the Logging macros provided by the NDK that allow you to log messages to LogCat. This is good for new code and wrapper code you are writing, but not so good when you have a library full of existing debugging statements. ...
3,902,126
3,902,154
Platform Invoke, bool, and string
suppose a dll contains the following functions extern "C" __declspec(dllexport) void f(bool x) { //do something } extern "C" __declspec(dllexport) const char* g() { //do something else } My first naive approach to use these functions from C# was as follows: [DllImport("MyDll.dll")] internal static extern void f(...
[DllImport("MyDll.dll")] internal static extern void f( [MarshalAs(UnmanagedType.I1)] bool x ); [DllImport("MyDll.dll")] [return: MarshalAs(UnmanagedType.LPStr)] internal static extern string g();
3,902,167
3,902,225
thread contention on dynamic memory allocation
I have just learnt that in C language malloc function comes with the issue of thread contention when used in a multi-threaded applications. In C++ does operator new suffer from the same problem? If yes what tecnhique can I use to avoid this that sounds like a big penalty in the application performance?
That "issue" of thread contention really depends on the implementation. Some of the implementations of malloc in common use were not originally designed with multithreading in mind. But a malloc implementation designed for multithreaded applications shouldn't suffer from contention in normal circumstances. As an exampl...
3,902,219
3,902,284
Function help in c++
I'm trying to create a very simple function in c++ however I keep getting a "Link error". My code: #include <iostream> using namespace std ; int fun(int,int); main(){ int width,height,w,h,mult; cin>>width; cin>>height; mult = fun(width,height); int fun(int w,int h);{ w * h ; }...
Ack...so many things wrong with that. Should be something like this: #include <iostream> using namespace std ; int fun(int, int); void main(){ int width,height,mult; cin >> width; cin >> height; mult = fun(width, height); cout << mult << endl; } int fun(int w, int h) { return w*h; } (B...
3,902,264
3,903,052
What do the terms platform and framework refer to?
I ran into this question many times ago and have seen the terms again and didn't know their real concept in computer engineering. What do platform and framework refer to? I see many terms like platform-independent and development platforms, and also same for frameworks, but i can't quietly understand them. Do they refe...
The term framework is very well defined: a framework is very similar to a library, except that Control is Inverted. (Inversion Of Control is the defining characteristic of what constitutes a framework.) IOW: you call a library, but a framework calls you. Another way to think about it, is that you write an application, ...
3,902,291
3,902,325
using Qt destructors
I've just begun to study qt using qt-creator, I found some tutorials int which the author doesn't use d'tors at all? is it good practice? or it will be better to manage my objects destruction, thanks in advance
When a class doesn't declare a destructor, the compiler automatically gives it a definition equivalent to {}. Often in Qt, this is good enough, even if the class contains pointers. Whenever something derived from QObject is destroyed, Qt automatically deletes all its children (recursively) as well, as long as each ch...
3,902,399
3,902,408
error: invalid operands to binary % (have 'double' and 'double')
I have a program I am writing that lists 100,000 prime numbers. It works fine for 10 numbers, but after so many numbers they turn into negative values. I changed the ints to long ints and that did not change anything, then I changed them to doubles and I get the error listed in the title. What should my variable be?...
You can't use a double with the operator, you must have an int. You should: #include <math.h> and then use the fmod function. if(fmod(x,j)==0) Full code: #include <math.h> int is_prime(double x,char array[]){ //doesnt use array but I put it in there double j=2;//divider for(j=2;j<=pow(x,0.5);j++){ ...
3,902,479
3,904,693
OpenGL: Render to FBO using multiple textures
I'm experimenting with a renderer. What I want is to write a color buffer and a normal buffer to two separate textures. I got that part figured out. However, the color buffer is supposed to be a combination of two textures. This should do the trick: glActiveTexture(GL_TEXTURE0_ARB); glEnable(GL_TEXTURE_2D); g_Tex->Bind...
Well I figured it out. :) The reason my textures didn't work was because I didn't set up the uniform locations. Fixed code: g_Shader->Enable(); glActiveTexture(GL_TEXTURE0_ARB); glEnable(GL_TEXTURE_2D); g_Tex->Bind(); glUniform1i(glGetUniformLocation(g_Shader->GetProgram(), "tex_diffuse"), 0); glA...
3,902,609
3,902,739
How do I count the zeros and ones in a file?
Given a file (binary or textual), what is the fastest or most elegant way in C++ to count the ones and zeros in the binary representation of that file?
I would recommend you use results array: unsigned char cheating[] = { 0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4...
3,902,644
3,902,729
Choosing between std::map and std::unordered_map
Now that std has a real hash map in unordered_map, why (or when) would I still want to use the good old map over unordered_map on systems where it actually exists? Are there any obvious situations that I cannot immediately see?
As already mentioned, map allows to iterate over the elements in a sorted way, but unordered_map does not. This is very important in many situations, for example displaying a collection (e.g. address book). This also manifests in other indirect ways like: (1) Start iterating from the iterator returned by find(), or (2)...
3,902,648
3,902,681
C++ Representing a 3D array in a 1D array
I want to store the byte value of aFloat in pixelsArray for each 3D coordinate, in a 1D array: float aFloat = 1.0; unsigned char* pixelsArray = new unsigned char[HEIGHT*WIDTH*3]; for (int i = 0; i < HEIGHT; i++) { for (int j = 0; j < WIDTH; j++) { for (int k = 0; k < 3; k++) { pixelsArray[?]...
Your inside line needs to be: pixelsArray[(i * WIDTH + j) * 3 + k] = (unsigned char)(255.0 * aFloat); This should give you an all-white image. Make sure your target is really three bytes per pixel and not four (alpha channel or padding); if it is four, you'll just need to change the 3 above to a 4.
3,902,763
3,902,837
'const Name &var' or 'const Name& var'?
Possible Duplicate: What makes more sense - char* string or char *string? Sorry if this is a silly question, I am new to these things :-) I am working on a C++ code base which uses the following reference conventions: const Name &var const Name& var As far as I'm aware, they mean the same thing. Which of these is ...
From the language or compiler perspective both are exactly same. For a group project, you have to use a group style. For personal project, you are free to make any choice. Though it is hard, but on topics like these, I always try to remember Rule# 0 from C++ Coding Standards: 101 Rules, Guidelines, Best Practices: Don...
3,902,786
3,902,825
cygwin1.dll missing when compiling c++ with g++
I'm using cygwin and when I'm compiling hello world with gcc somehow the compiler doesn't understand about using std namespaces (some of them are missing), but when I compile with g++ yes they work. But when I click on the helloworld.exe it says that cygwin1.dll is missing. Is there anything can I do?
"gcc" is the C compiler - and namespaces are not a part of the C language. "g++" is the C++ compiler, so it will understand namespaces. Try the no-cygwin option when compiling to produce executables that depend on the mingw runtime instead of the cygwin runtime (which, AFAIR, introduces licencing issues).
3,902,815
3,902,905
How to line things up when outputting to a file in C++
New code.... #include <cstdlib> #include <iostream> #include <fstream> #include <iomanip> using namespace std; void gradeg (double & average, string & grade) { if (average >= 90) { grade = "A"; } else if ((average < 90) & (average >= 80)) { grade = "B"; ...
You're making a very simple mistake, which is that a formatting manipulator (such as setw) has to come before the data that it formats, like so: fout << left << setw(24) << "Names" << setw(10) << "Score 1" << setw(10) << "Score 2" << setw(10) << "Score 3" << setw(10) << "Total" << setw(10) << "Average"<< setw(10) << "...
3,902,880
3,902,919
How can I load a string based on resource identifier?
I'm reading an entry from the registry that comes out something like: @%SystemRoot%\\System32\\wscsvc.dll,-200 I need to actually load the string from the file. I found an article which describes how the number on the end behaves (negative == specific resource ID, positive == the nth resource in the file), but I'm conf...
Load the DLL with LoadLibrary, load the string with LoadString, and then unload the DLL (assuming you don't need anything else from it) with FreeLibrary: HMODULE hDll = LoadLibrary("C:\\WINDOWS\\System32\\wscsvc.dll"); if(hDll != NULL) { wchar_t *str; if(LoadStringW(hDll, +200, (LPWSTR)&str, 0) > 0) ; ...
3,902,967
3,902,983
Is Visual Studio 2010's unit testing feature usable for native C++ code?
It seems to be mainly tailored to .net code.
Only managed C++ (/clr:safe): Unit Tests and C++ You could use WinUnit (if you are not already): Simplified Unit Testing for Native C++ Applications
3,903,180
3,903,199
Make a friend class have only special access to 1 function of another class?
Possible Duplicate: Is this key-oriented access-protection pattern a known idiom? I have class A and class B. I want class A to access one of class B's private functions; but only that, not everything else. Is that possible? Some kind of example: class A { //stuff }; class B { int r; // A cant use this MagicF...
If there is one (or few) members functions in class A, that want to use class B's private member functions, then you can declare those one/few functions as friend. E.g. class B { // ... friend void A::mutateB( B * ); // ... }; See http://en.wikipedia.org/wiki/Friend_function
3,903,190
3,919,066
C++: Trouble with Parsing XML using Libxml
I am having a lot of trouble working with the libxml2 library to parse an xml file. I have weeded out a previous, similar problem, but have run into another. Here is the problem code: class SSystem{ public: //Constructors SSystem(){}; //Make SSystem from XML Definition. Pass ptr to node SSystem(xmlNodeP...
Okay, I am going to use a different XML parsing library, as Libxml is a bit too complicated for me. I am looking into using MiniXML (http://www.minixml.org/).
3,903,232
3,903,242
Is there any way to make a variable length array global in c++?
I've created a variable length array in one function, however I need to refer to this array in a second function. The problem occurs when I put the declaration above main() seeing as its length hasn't been defined yet, my compiler gets angry. How does one typically go about this? EDIT: Here is my code so far. I need...
C++ does not support variable length arrays; either you are not using C++ or you are using an implementation-specific language extension. In C++ you should use std::vector for a dynamically sized array. If you need to access it from multiple functions you can: have the functions that need access to the vector take a r...
3,903,336
3,903,349
Scope resolution operator and dependent name
I have the following test code #include <iostream> template <typename T> struct PS { template <typename U> static void foo() { std::cout<<"Some test code"; } }; template <typename T> void bar() { PS<T>::template foo<T>(); //won't compile without `::template` } int main() { bar<int>(); } ISO...
The Standard talks about -> and . but not about ::. The scope resolution operator (::) is part of the qualified-id referred to by "or after nested-name-specifier in a qualified-id." The additional verbiage in C++0x is part of the resolution to CWG defect 224. Effectively, the definition of dependent names has been c...
3,903,444
3,903,670
Shuffle array variables in a pre-specified order, without using extra memory of "size of input array"
Input : A[4] = {0,4,-1,1000} - Actual Array P[4] = {1,0,3,2} - Order to be reshuffled Output: A[4] = {4,0,1000,-1} Condition : Don't use an additional array as memory. Can use an extra variable or two. Problem : I have the below program in C++, but this fails for certain inputs of array P. #include<iostrea...
First of all, I really like Jonathan's solution, but I feel like I can add some interesting ideas too. The main observation is that array P consists of several loops. Let's consider p = {1, 4, 3, 2, 0, 5}. There're three loops: 0 => 1 => 4 => 0, 2 => 3 => 2 and 5 => 5. And to replace variables alongside one loop we nee...
3,903,587
3,903,595
How to check if a std::string is set or not?
If using a char*, I can initialize it to NULL and later check if it is set by doing a comparison. How to do the same thing for a std::string? How to check if the string is set or not? EDIT: What if the string I set to is also empty? Do I have to use an additional flag to check if the std::string is set or not?
Use empty(): std::string s; if (s.empty()) // nothing in s
3,903,664
3,903,730
Data structure for string indices?
I'm looking for a data structure for string(UTF-8) indices that is highly optimized for range queries and space usage. Thanks! Elaboration: I have list of arbitrary length utf-8 strings that i need to index. I will be use only range queries. Example: I have strings - apple, ape, black, cool, dark. Query will be somet...
Since you mentioned "relatively static", a simple sorted array would do everything you want and is highly optimized both in terms of space and time. "get from 2 to 3 element in desc order" is simply a lookup of the corresponding array indices. "get strings that start by 'ap'" can be done with a binary search. The searc...
3,903,680
3,903,683
C++ floats being converted to ints
I have the following function that should return an average of l1- l7. However, it seems to only return an integer. Why is it doing this, and how do I make it return a float rounded to 2 decimal places? Snippet: int lab_avg(int l1,int l2,int l3,int l4,int l5,int l6,int l7) { float ttl; ttl = l1 + l2 +l3 +l4 +l...
Because your function's return type is an int. Change it to float and it'll work fine. Also, if you just want to print 2 decimal places, use an appropriate format in your output function. You don't need to do anything with the float itself: printf("%.2f", some_value);
3,903,682
3,903,695
How should I pass a std::string to a function?
Should I always pass a std::string by const reference to a function if all that is done inside that function is to copy that string? Additionally, what is the difference (perf or otherwise) between passing by value and passing by reference? As I understand, one uses operator= and the other copy constructor. Is that the...
Should I always pass a std::string by const reference to a function if all that is done inside that function is to copy that string? No. If you are going to just copy the string inside of the function, you should pass by value. This allows the compiler to perform several optimizations. For more, read Dave Abraham'...
3,903,807
3,905,961
How does malloc_info() work?
I've been trying to figure out how the malloc_info() function located in malloc.h works. I know you have to pass it a FILE* and that no options are implemented yet, but I am at a loss as to what it is actually reporting!? Furthermore i've written a test app that allocates a whole bunch of memory and the values reported...
Large allocations are typically handled by just telling the OS "I need x number of memory pages.", often by mmaping /dev/zero. Allocations of larger than a page or 4 (A page is usualy 4096 bytes) are usually handled this way and those allocations are not things I'd expect a malloc diagnostic to track. Unfortunately, I ...
3,903,843
3,903,859
Help me convert this Java function to C++
I've been following this forum for sometime now but officially registered today. I'm a Java guy learning C++ now. As an exercise I'm started to rewrite some of the Java code I had written (while I was learning it ) now in C++. There are several questions here that helped me a lot. But I'm stuck now and need some help. ...
You are not initializing the frequency array arr to all zeros in your C++ code.You can fix this in either of the two ways: Fix 1: In Java array elements get initialized to default values depending on their type. For int the default value if 0. In your C++ version the dynamically allocated array elements will have garba...
3,903,898
3,903,996
Access variable through memory location
I get wrong value when accessing variabel v2 using their memory location when HWND is before bool variable. If Ii use HWND after bool then I get correct result. Using instance variable (t) I get correct value for v1 and v2 such as t->v1 and t->v2. I am using Windows Server 2003. I have the following Test class. this i...
You seem to assume that your v1 and v2 must reside precisely at the end of the object of type Test. This is a completely unfounded assumption. The language makes no such guarantees and in general case they will not. The object will generally end with padding bytes. These padding bytes is what you are actually reading i...
3,904,028
3,905,397
Double buffering winAPI
Okay, so in my application, there are a bunch of winAPI and a few custom controls. Yay... Now, normally, they will just quietly redraw themselves for animations, state changing, ect.... and it all works fine. But I have a method of class Window called fix(). This is called whenever the whole window needs to be updated....
It is at this time that one realized the depths of Microsofts disregard for native developers. One could in fact start to harbor paranoid delusions that Microsoft has purposely broken native painting in order to force native developers to move to WPF. First, consider WS_EX_COMPOSITED. WS_EX_COMPOSITED seems to be the m...
3,904,098
3,904,309
Is const_cast acceptable when defining an array?
I have a static const array class member (const pointers to SDL_Surfaces, but that's irrelevant), and have to loop through it in order to populate it. Aside from a const_cast when I'm done looping, which I hear is bad practice, how would I go about doing this? EDIT: The reason I don't just do... static SDL_Surface *co...
One method to provide "logical constness" is to make the data inaccessible, except by non-mutating means. For example: class foo { public: const bar& get_bar() { return theBar; } private: static bar theBar; }; Even though theBar isn't constant, since foo is the only thing that can modify it, as long as it doe...
3,904,224
3,904,283
Declaring a pointer to multidimensional array and allocating the array
I've tried looking but I haven't found anything with a definitive answer. I know my problem can't be that hard. Maybe it's just that I'm tired.. Basically, I want to declare a pointer to a 2 dimensional array. I want to do it this way because eventually I will have to resize the array. I have done the following success...
I just found this ancient answer still gets read, which is a shame since it's wrong. Look at the answer below with all the votes instead. Read up on pointer syntax, you need an array of arrays. Which is the same thing as a pointer to a pointer. int width = 5; int height = 5; int** arr = new int*[width]; for(int i = 0;...
3,904,288
3,904,840
Needed C++ HTML parser + regular expression support
I'm working on a C++ project and I need to find an external library which provides HTML parser and regular expression support. The project is under 2 OS - iOS & Android. I was thinking using libxml2 which has a HTML parser module and xml regular expression. Can I use the xml regular expression module on HTML page? In a...
I've never used libxml2 to parse html, but I remember that it was easy to use for xml parsing, so probably it's worth a try. For the regular expressions, instead, I would suggest you to use Boost Regex.
3,904,304
3,904,564
3D array C++ using int [] operator
I'm new to C/C++ and I've been cracking my head but still got no idea how to make an "structure" like this It's supposed to be a 3D dynamic array using pointers. I started like this, but got stuck there int x=5,y=4,z=3; int ***sec=new int **[x]; It would be enough to know how to make it for a static size of y an...
To create dynamically 3D array of integers, it's better you understand 1D and 2D array first. 1D array: You can do this very easily by const int MAX_SIZE=128; int *arr1D = new int[MAX_SIZE]; Here, we are creating an int-pointer which will point to a chunk of memory where integers can be stored. 2D array: You may use ...
3,904,307
3,904,373
how to traverse a grid of numbers using AB-pruning in C++?
Firstly I would like to accept that it is a homework question , but then I know how to code AB-pruning from the algorithm of it . The problem is how to apply it on a grid of numbers where the game can go on in any direction (right , left , up and down ) , thus how will be the tree formed . Sorry for being a bit vague ...
You question is very vague so I can only guess what you are asking: Are you talking about a game where the player can only move in one of those 4 directions on each turn? If that is the case, your Node will be an (x, y) position of your player on the grid, and each node will branch 4 times (once for each direction) plu...
3,904,316
3,904,334
What does this function definition mean?
This function definition is found here. : static void (*resolve_memcpy (void)) (void) { return my_memcpy; // we'll just always select this routine } I don't understand what it means.
resolve_memcpy is a function taking no arguments and returning a pointer to a function taking no arguments and returning void. EDIT: Here's a link where you can read more about this kind of syntax: http://unixwiz.net/techtips/reading-cdecl.html
3,904,411
4,000,510
Is there a chatbot framework available?
I am trying to create an program similar to ELIZA. My preference is to implement this project in a general language such as ruby, java, C++. is there some framework (open source would be great) available for any of these languages ?
At the heart of a chat bot there is a natural language processor (NLP), the engine implements algorithms that would break a sentence entered by a human (e.g plain English) to a series of token the computer can process. while I am not familiar with a chat bot framework there are several open source NLP engines you ...
3,904,759
3,904,775
How can I initialize a const variable of a base class in a derived class' constructor in C++?
I have an abstract C++ class with no constructor. It's supposed to be a base class so other classes can inherit from it. What I am trying to do is to declare a constant variable in the base class and initialize it in each derived class' constructor but nowhere else in each one of those classes. Is it legal in C++? If s...
Is it legal in C++? No. The constant must be initialized in the base class constructor. The solution is to provide an appropriate constructor in your base class – otherwise it cannot be used. Furthermore, there’s no reason not to provide that constructor. class Base { int const constant; public: virtual ~Base...
3,904,825
3,905,965
OpenMP library specification
i am new to open mp and i tried an sample program from the official site #include <omp.h> #include <stdio.h> int main() { #pragma omp parallel printf("Hello from thread %d, nthreads %d\n", omp_get_thread_num(), omp_get_num_threads()); } and i have set the library in the eclipse as libgomp in project Properties->GCC c+...
Try linking with gomp instead of libgomp: library names must be passed to the linker without the lib prefix, which it adds automatically. Hence the error, it is trying to find liblibgomp. Don't forget the compiler flag -fopenmp, otherwise the OpenMP pragmas will simply be ignored.