question_id
int64
25
74.7M
answer_id
int64
332
74.7M
title
stringlengths
20
150
question
stringlengths
23
4.1k
answer
stringlengths
20
4.1k
6,067,067
6,067,092
Precedence of increment and decrement opreators in C++
I tried this on my gcc: int a=1; cout<<(--a)--; and the output is 0; but change it to cout<<--(a--); results in an error (lvalue required as decrement operand). Could someone enlighten me about this? Thanks!
Both versions of ++ require lvalues as arguments, but the prefix version returns an lvalue as an argument, while the postfix version returns an rvalue. Either way, you can't modify the same object twice between sequence points, so your "working" example invokes undefind behavior. The output can be whatever the compiler...
6,067,244
6,067,267
Type of 'this' pointer
As mentioned in the title, I would like to know about the type of 'this' pointer. I'm working on a project and I observed that the type of 'this' pointer is "ClassName * const this" on windows using VC++ 2008. Well I would want to know what is the need/requirement to make the this pointer a constant pointer. Thanks.
The type of this pointer is either ClassName * or const ClassName *, depending on whether it is inspected inside a non-const or const method of the class ClassName. Pointer this is not an lvalue. class ClassName { void foo() { // here `this` has `ClassName *` type } void bar() const { // here `this` has ...
6,067,289
6,067,314
Problem with c++ template constructor
code: #include<iostream> using namespace std; template<class T, int N> class point { T coordinate[N]; public: point(const point<T,N>&); const double& operator[](int i) const { return coordinate[i]; } }; template<class T, int N> point<T,N>::point(const point<T,N>&p) { for(int i=0;i<N;i++) ...
The compiler-generated default constructor is not being provided because you have created a constructor of your own. Therefore when you create P2 with no arguments to its constructor, you need to define a default constructor for it to compile.
6,067,339
6,067,567
How to handle "switch/case" when new parameters added in SW release
How to handle when there is a new SW Release sometime and it adds another index to switch case. Index represents a parameter in this case. For example, Rel1: i = 1-5, 7 (excluding 6) Rel2: i = 1-7 for (int i = 1; i<=7;i++) { switch (i) { case 1: /*process data*/ break; case 2: /*process data*/ break; c...
#define which release is this and then use #ifdef. switch (i) { case 1: /*process data*/ break; case 2: /*process data*/ break; case 3: /*process data*/ break; case 4: /*process data*/ break; case 5: /*process data*/ break; #ifdef REL_2 case 6: /*process data*/ break; // <-- executed only f...
6,067,407
6,067,461
why sometime a function return a const, or const reference
First, why return const? say I have friend const MyVec operator-(const MyVec& left, const MyVec& right) so is returning const makes me cannot do: mva - mvb = mvc; Second, why return const reference? if there is: friend const MyVec& operator++(MyVec& v) with const I cannot: (++mva) = mvc if it is MyVec& operator++(M...
There is not any good reason to return a const object. However, there are many good reasons to return pointers or references to const objects. The program might have an object that is very expensive to copy, so it returns a reference. However, the object should not be changed through that reference. For example, it mig...
6,067,413
6,068,200
Is it advisable to expose a templated class of a Library?
I am developing a Library for Matrix Calculations in C++. For this I wanted to use Templates. After doing a bit of Template Meta Programing, I realized that I would end up in exposing my implementations in the Templatise Matrix Class.Is there any way to obfuscate the template class implementation in the header file whe...
I will answer from the customer perspective. When I need to use a library, and integrate it in my code, I expect to see the source code. It is not because I wish to rip it out from the author... It is not because I am a lawless and irrespective hacker... It is, simply, because: code is documentation, and seeing the im...
6,067,454
6,067,932
What is the correct way to use MPI with thread
I have a piece of code like this, running on 4 MPI process. for (i=0;i<niter;i++){ //.. do something with temprs memcpy(rs, temprs,..) // copy temprs content to rs MPI_Gather(rs,...0...); //gather result to 0 if (mpiRank == 0) writeToDisk(rs); } I want to put 2 last line of code into a function c...
Use MPI_Init_thread: http://www.mpi-forum.org/docs/mpi-20-html/node165.htm and check return status: Available level of thread support Cheerz.
6,067,460
6,068,725
C++ How to calculate the number time a string occurs in a data
I want to measure the following two things: How many times a comma appears in a std::std, e.g. if str ="1,2,3,4,1,2," then str.Count(',') returns me 6 in case of above string The second thing is also similar to the first on but instead of single char i want to calculate the number of occurances of a string e.g str.Fin...
Using one of the std::string::find methods, you can step through the reference string, counting each time you find the sub-string. No need for copies or erases. Also, use std::string::npos to check whether the pattern has been found or not, instead of literal -1. Also, using the sub-string's size, std::string::size(), ...
6,067,535
6,069,286
Error with C++ operator overloading
#include<iostream> using namespace std; class complex { double real; double image; public: complex(double r=0,double i=0) : real(r), image(i) { }; complex(const complex& c) : real(c.real), image(c.image) { }; ~complex(){}; double re() const { return real; }; double im() const{ ...
There are two alternatives to overload the binary + operator, as a free function or as a member function. As a member function the signature is Type operator+( Type const & ) const (const is optional there, but I am assuming that a+b does not modify a, which seems a fair assumption). The alternative approach is using a...
6,068,167
6,068,360
Is it safe to modify mutable members of objects inside sets?
I was curious as to whether the following scenario is safe. I have the following class definitions: class ActiveStatusEffect { public: StatusEffect* effect; mutable int ReminaingTurns; ActiveStatusEffect() : ReminaingTurns(0) { } //Other unimportant stuff down here } I then store a group of the...
Changing data that affects the ordering of an object will indeed break the invariants of associative containers, but because ActiveStatusEffect::ReminaingTurns is not involved in the ordering of ActiveStatusEffect objects whatsoever, keeping it mutable and modifying its value is perfectly harmless. I'm concerned becau...
6,068,292
6,068,323
Rules of thumb for putting functions in header files
Lately I have started to put more and more functions into header files, mostly for convenience. But I fear I might be overdoing it, my headers are full of includes and I'm not sure if that's a good idea. What are your rules of thumb for moving functions out of or into header files? In case you're wondering, I'm talking...
One of my most inviolable rules: only function bodies which are inline are allowed in header files. Anything else is asking for trouble with multiple definitions in the link phase. Headers should be left predominantly for declarations rather than definitions. I have exceptions to that rule (being the flexible type) but...
6,068,623
6,070,086
Script in Qt doesn't return the correct value
I am trying to use the script in the Qt, here is a very simple code. QCoreApplication a(argc, argv); double x; cout<<"Please enter a number: "; cin>>x; QFile file("cube.js"); if(!file.open(QIODevice::ReadOnly)) abort(); QTextStream in(&file); in.setCodec("UTF-8"); QString script=in.readAll(); file.close(); QScri...
You are calling return on the Javascript global level, which is not allowed. You can use QScriptEngine::hasUncaughtException and QScriptValue QScriptEngine::uncaughtException to determine errors in the javascript code. Also, you are calling result.data() which is for storing internal data. So the script should be x*x*x...
6,068,655
6,070,835
what are the functions i need use for serial communication in vc++?
I am working on an embeeded device.i connect to it using COM port. It gives the list of all files when i send a command "LIST" to it. so i wrote an "hello world" which will connect to the port device is connected and will send data. When i connect my device and run my program it is writing to the port and not receiving...
You might try setting all the DCB options and clearing port errors // Common settings dcbSerialParams.DCBlength = sizeof( dcbSerialParams ); dcbSerialParams.ByteSize = 8; dcbSerialParams.BaudRate = CBR_9600; dcbSerialParams.fParity = FALSE; dcbSerialParams.Parity = NOPARITY; dcbSerialParams.StopBits = ONESTOPBIT; dcbSe...
6,068,801
6,069,329
Convert wchar_t to int
how can I convert a wchar_t ('9') to a digit in the form of an int (9)? I have the following code where I check whether or not peek is a digit: if (iswdigit(peek)) { // store peek as numeric } Can I just subtract '0' or is there some Unicode specifics I should worry about?
If the question concerns just '9' (or one of the Roman digits), just subtracting '0' is the correct solution. If you're concerned with anything for which iswdigit returns non-zero, however, the issue may be far more complex. The standard says that iswdigit returns a non-zero value if its argument is "a decimal digit ...
6,068,963
6,068,995
c++ open SSL EVP_aes_128_cbc()
Can someone please give me an example of encryption and decryption using #include <openssl/evp.h> in c++ code: Aes 128 with cbc a key and an iv? Thanks.
There are several answers on Stack Overflow, e.g. AES CTR 256 Encryption Mode of operation on OpenSSL If you don't know what CBC and friends are all about, I would suggest either reading up on it, or using a wrapper library. OpenSSL is fairly low level, so if you don't know what you are doing, you will probably be not...
6,069,064
6,069,190
How to make macdeployqt use another qt-installaton?
The macdeployqt which comes with Qt SDK 1.1 is broken (it's already files on the Qt bugtracker). How do I make macdeployqt use the libraries of another Qt-version I installed instead of Qt SDK 1.1? I couldn't find a bash-environment variable for it.
macdeployqt should deploy Qt libraries which are linked to your binary. Use otool to check what libraries are linked. To get more control over the deployment of libraries, I ended up rewriting macddeployqt to always deploy/link to my preferred library location.
6,069,152
6,069,170
c++ dtor to free _bstr_t memory
A simple question but I am not sure what it is done in C++. When I have a class that have _bstr_t member. I would like to know if does member are freed when the object is deleted: class A { _bstr_t foo("Testing"); } The A class does not have a dtor. So is the default dtor calling the dtor of yeach member of the cl...
Yes, _bstr_t destructor will have been called - the compiler will take care of that. Even though it doesn't have a user-defined destructor the compiler will emit code that destroys all fully constructed subobjects by calling their destructors. Since _bstr_t has a non-trivial destructor that takes care of calling SysFre...
6,069,185
6,069,481
Marshall char** to string problem calling unmanaged code from managed code
I've this C++ function, bool MyClass::my_function(int num, TCHAR** filepath) I've expose the function as extern "C" { __declspec(dllexport) bool MyFunction(int num, char* filepath[]) { OutputDebugStringA("--MyFunction--"); TCHAR **w_filepath = (TCHAR **)calloc(num, 2* sizeo...
1) w_filepath[i] = (TCHAR *)calloc (1, len); - calloc requires size in bytes, so it should be w_filepath[i] = (wchar_t *)calloc (1, len*sizeof(wchar_t)); 2) data from c# comes as wchar_t*, so you don't need converting routines at all , and should change function declaration to __declspec(dllexport) bool MyFunction(int ...
6,069,458
6,069,510
linker error problem
Program: #include<iostream> using namespace std; int main() { int a[5] = {4,5,9,1,2}; int i,j,temp; cout<<"Assending sorting: "<<endl; for(i=1; i<5; i++) { temp = a[i]; if(a[i]<a[i-1]) { temp = a[i-1]; a[i-1] = a[i]; a[i] = temp; } ...
As far as I can see, you seem to have declared two functions with the name main in your code, possibly in another .c/.cpp file.
6,069,719
6,083,892
Elegant way of implementing call multiplexing in a C++ aggregate class?
When multiplexing calls to many sub-objects, what is an elegant way of preventing looping-boilerplate code? Problem description by example: struct Foo { void Boo(); void Hoo(); bool IsActivated(); }; struct FooAggregator { ... void Boo(); void Hoo(); ... std::vector<Foo> m_foos; }; FooAggregator::Boo(...
I'll take Nawaz's good 1st example and simplify some more: (Remember, I want to reduce the boilerplate, not introduce the fanciest features.) // FooAggregator.h struct FooAggregator { template<typename MemFn> void CallForEachFoo(MemFn fun); void Boo(); void Hoo(); }; // FooAggregator.cpp template<type...
6,069,920
6,070,192
c++ referring to a sibling namespace
given: namespace root { namespace parent { namespace childa class hard_to_get_at{}; }}} namespace root { namespace parent { namespace childb // how do I refer refer to namespace childb relative to the current namespace ? ..::hard_to_get_at instance_of_childa_class; // psuedo syntax }}} Do I need to specif...
Next should work : namespace root{ namespace parent{ namespace childb{ // some function where you want to use class hard_to_get_at void foo() { childa::hard_to_get_at obj; // do stuff } } // namespace childb } // namespace parent } // namespace root
6,070,220
6,070,308
Size/Resize of GHashTable
Here is my use case: I want to use glib's GHashTable and use IP-addresses as keys, and the olume of data sent/received by this IP-address as the value. For instance I succeeded to implement the whole issue in user-space using some kernel variables in order to look to the volume per IP-address. Now the question is: Sup...
Neither g_hash_table_new() nor g_hash_table_new_full() let you specify the size. The size of a hash table is only available as the number of values stored in it, you don't have access to the actual array size that typically is used in the implementation. However, the existance of g_spaced_primes_closest() kind of hints...
6,070,231
6,070,315
Simulating new[] with argument constructor
If I am not modifying any static variable inside the argument constructor, is below the proper way to simulate new T[N] (x,y); (array new with arguments) ? template<typename T> void* operator new [] (size_t size, const T &value) { T* p = (T*) malloc(size); for(int i = size / sizeof(T) - 1; i >= 0; i--) memcpy(p...
This isn’t OK. You are copying objects into uninitialised memory without invoking proper copy semantics. As long as you’re only working with PODs, this is fine. However, when working with objects that are not PODs (such as your A) you need to take precautions. Apart from that, operator new cannot be used in this way. A...
6,070,430
6,139,097
Fitting a big grid (wxGrid) in a dialog (wxDialog)
Here is my layout: I have a sizer that contains a grid (with a proportion of 1) and a ok/cancel button bar The all thing is in a wxDialog Here it is: ||||||||||||||| | | | GRID | | | | | | | ||||||||||||||| | OK CANCEL | ||||||||||||||| The issue is that the g...
The easiest way to handle this is to use a grid of fixed size. If there are more rows than will fit, then a scroll bar will appear. You set the size you want in the constructor. new wxGrid( this, IDC_grid, wxPoint(-1,-1),wxSize(igridxsize,igridysize)); If you want the size of the grid to adjust, e.g. when the user r...
6,070,784
6,070,921
Using multiple cores to process large, sequential file in c++
I have a large file (bigger then RAM, can't read whole at once) and i need to process it row by row (in c++). I want to utilize multiple cores, preferably with Intel TBB or Microsoft PPL. I would rather avoid preprocessing this file (like splitting it to 4 parts etc). I was thinking about something like using 4 iterat...
Since you are able to split it into N parts, it sounds like the processing of each row is largely independent. In that case, I think the simplest solution is to set up one thread to read the file line by line and place each row into a tbb::concurrent_queue. Then spawn as many threads as you need to pull rows off that...
6,070,920
6,114,346
Measuring distance along ellipse
Suppose we have an ellipse x^2/a^2 + y^2/b^2 . Taking a point (a*cos(t),b*sint(t)) on the ellipse, what is the fastest way to find another point on the ellipse such that distance between them is a given d. [d is less than pi*a*b]. The problem was encountered when i have a corner [quarter ellipse] and need to find point...
The length of a subsection of an ellipse is an elliptic integral, with no closed form solution. In order to compute the distance along the ellipse, you will need a numerical integration routine. I recommend Romberg, or Gauss Quadrature (look up on Wikipedia). If you are doing this repeatedly, then precompute the dis...
6,071,068
6,078,305
Control to draw in a window gdi
I have used Visual Basic 6 in the past (LOONG ago), and it had a control called PictureBox where you could just draw stuff to, get a device context if you wanted, etc. I'm now trying to find out how to have a similar "control" in pure GDI/WinApi (no MFC, .net, atl, gdi+, etc). I was using an owner-draw button control, ...
In all honesty, i think this may be a bit of a big project for you to take on right now. You may want to try a few simpler projects using the windows api before trying this, but i'll give you a bit of an explanation anyway. You're going to need to create a custom control. Using an existing control for this is bad pract...
6,071,071
6,080,751
Design and Technical issue in Multi Threaded Application
I wanted to Discuss the Design and technical issue/challenges related with multi threaded application. Issue I faced 1.I came across the situation where there is multiple thread is using the shared function/variable crash the application, so proper guard is required on that occasion. 2. State Machine and Multi thread- ...
Well, there are so many... 1) Shared functions/procedures - they are just code and, unless the code modifies itself, there can be no problem. Local variables are no problem because each thread calls on a separate stack, (amost by definition:). Any other data can an issue and may need protection. 99.99% of all house...
6,071,110
6,071,135
How memory is managed for C# objects when C++ code uses as C# class?
How memory is managed for C# objects when C++ code uses as C# class? NOTE: I am not specific in this question but just wondering how it is done.
It works exactly the same... objects that are not reachable by managed code are eligible for garbage collection so if your unmanaged code is relying on managed resources to continue existing you must hold a reference to it somewhere in the c# side of the app. edit: this applies to unmanaged c++
6,071,129
6,071,222
Using C++ in a CUDA C project
I am implementing a sort and stream compaction algorithms in CUDA C. However I have just figured that it is not that simple to implement those algorithms by myself with good performance. Given that I am working with matrices I cannot use CUDPP, so, although I was avoiding it, I will have to work with thrust library(I k...
On the host code side, thrust is simple to integrate. Even though you might think that your host side code in any .cu file you compile is C, it is compiled using a C++ compiler anyway (most of CUDA internally relies on C++ features to compile). So you are actually working in C++ now without realizing it.
6,071,253
6,071,291
error in attaching temporary to a reference to const
Possible Duplicate: typedef and containers of const pointers Why is the code emitting an error? int main() { //test code typedef int& Ref_to_int; const Ref_to_int ref = 10; } The error is: error: invalid initialization of non-const reference of type ‘int&’ from a temporary of type ‘int’ I read the post on ...
Here the type of ref is actually reference to int and not const reference to int. The const qualifier is ignored. $8.3.2 says Cv-qualified references are ill-formed except when the cv-qualifiers are introduced through the use of a typedef (7.1.3) or of a template type argument (14.3), in which case the cv-qualifiers a...
6,071,396
6,071,476
WinHttp doesn't work when hostname doesn't contains www. (error 12029)
I am testing this winhttp example from http://msdn.microsoft.com/en-us/library/aa384270%28v=vs.85%29.aspx DWORD dwSize = 0; DWORD dwDownloaded = 0; LPSTR pszOutBuffer; BOOL bResults = FALSE; HINTERNET hSession = NULL, hConnect = NULL, hRequest = NULL; // Use WinHttpOpen to obta...
microsoft.com returns a 301 Moved Permanently header, to get winhttp to honour that and redirect to the URL in the Location: header (the www.) you need to use WinHttpSetOption to set the appropriate WINHTTP_OPTION_REDIRECT_* option(s).
6,071,415
6,071,604
c++ boost::thread execute code on main thread?
Is it possible, after calling a boost::thread running some instructions, to come back to main thread ? My code is based around proactor pattern, however a certain function may take some time, so in order not to block the whole program, I'm creating a thread running this function. When this function is over, I need to c...
I think you might want to look into boost asio strands. They will let you specify which thread (strand) to do some wok on, and it will automatically get queued on that strand. Note that a strand is actually more like a fiber (meaning: if there are more strands than actual threads, the strands will get multiplexed onto ...
6,071,497
6,071,650
Runtime errors when coding OpenCV programs using codeBlocks in linux
When I try to compile a C++ program which uses the openCV library in CodeBlocks it gives me a runtime error : error while loading shared libraries: libopencv_calib3d.so.2.2: cannot open shared object file: no such file or directory This is in spite of the fact that I have added all the required libraries using linker...
The file libopencv_calib3d.so.2.2 is part of OpenCV 2.2. There is, however, no libcv, libhighgui or libcvaux part of OpenCV 2.2. This means that your g++ call links against another version of OpenCV. To link against OpenCV 2.2, you would need flags like -lopencv_core -lopencv_imgproc -lopencv_highgui -lopencv_ml -lopen...
6,071,647
6,071,724
How to display in a Primary window from a secondary thread for a video player
I am creating a video player application with a UI in C# and the video decoding and display (DirectX) in C++. The C++ code is compiled as a DLL and interfaced with the C# UI. To maintain the correct display frame rate I need to create a secondary thread either in C++ DLL or C# which can do accurate timing and call th...
I think the crashes you experience are caused by the fact that you can't access Windows Forms controls from outside the main thread. Consider using Control.Invoke() to invoke the execution you need on the main thread. Bear in mind though that Control.Invoke() uses Windows' message queue to pass the request through, so ...
6,071,669
6,073,886
Is an unnamed parameter actually passed during a function call?
template <typename TAG> fn(int left, TAG, int right) { } fn(0, some_type_tag(), 1); /* or */ fn(0,int(), 1); // where the primitive, int, is not empty. EDIT: There are two perspectives to this question. Function declaration vs definition. The declaration might not name the parameter, but the declaration might do.Thi...
It's quite an interesting question actually. First of all, note that we are in an imperative language, meaning that when you ask for something (even useless, such as constructing an unused object) then the compiler need to comply unless it can come up with an equivalent form. Basically, it could elide the parameter if ...
6,071,709
6,071,738
Incrementing Individual Characters in String
I dont know if I have the correct tiltle for this, so please correct me if I am wrong and I will change my title. I have a string, for this example I will use: "8ce4b16b" I would like to shift the bits (I think) along 1 so the string would be: "9df5c27c" Any Ideas? EDIT: Just so you know, these strings are hex. So it...
Do you mean you want to increment each character in the string? You can do that my iterating through the array and adding one to each character.
6,072,147
6,072,300
How to concat LPCWSTR and char[]?
I am trying to concat a LPCWSTR and a char[] (and get LPCWSTR as output). How can I do that?
You could convert your char[] array into a wide-char array using the following code (from MSDN) wchar_t * wcstring = new wchar_t[strlen(array) + 1]; // Convert char* string to a wchar_t* string. size_t convertedChars = 0; mbstowcs_s(&convertedChars, wcstring, strlen(array) + 1, array, _TRUNCATE); After that you can u...
6,072,192
6,072,234
Deleting dynamically allocated memory from a map
I've got a map of dynamically allocated object and was wondering what the best way of deleting them was? I was thinking maybe an interator? Something like: studentlist::const_iterator deletemem = studentmap.begin(); for(studentlist::const_iterator deletemem=studentmap.begin(); deletemem!=studentmap.end();++deletemem) {...
Your code looks fine. However, manually deleting is probably not exception-safe. You might consider using share_ptr (either the one from Boost, or, if you use C++0x, the standard implementation) for the values or using a boost::ptr_map. Edit: To delete the actual data in the map, call studentmap.clear() after deleting ...
6,072,342
6,072,627
How to use utf8 character arrays in c++?
Is it possible to have char *s to work with utf8 encoding in C++ (VC2010)? For example if my source file is saved in utf8 and I write something like this: const char* c = "aäáéöő"; Is this possible to make it utf-8 encoded? And if yes, how is it possible to use char* c2 = new char[strlen("aäáéöő")]; for dynamic alloc...
The encoding for narrow character string literals is implementation defined, so you'd really have to read the documentation (if you can find it). A quick experiment shows that both VC++ (VC8, anyway) and g++ (4.4.2, anyway) actually just copy the bytes from the source file; the string literal will be in whatever encod...
6,072,472
6,072,578
How to represent static struct in Java
Following is a static struct in C++. How can this be represented in java. static struct { int c1; int c2; } pair[37]= {{3770,3780}, {3770,3781}, {3770,3782}, {3770,3785}, {3770,3786}, {3770,3787}, {3771,3780}, {3771,3781}, {3771,3782}, {3771,3785}, {3771,3786}, {3771,378...
In java you could make a collection/array of Pair objects or use an multidimensional array (array of arrays); static int[][] pairs = new int[][] { {3770,3780}, {3770,3781}, {3770,3782}, {3770,3785} } or class Pair { int a; int b; Pair(int a, int b) { this.a=a; this.b=b; } } static Pair[] pairs = new Pair[] ...
6,072,685
6,072,809
OpenGL: How to check if the user GFX card can render with my shader?
I need to make a fallback if the user doesnt support the shader i have made to render some things faster. So, how exactly do i check these things? I know some of the shader functions are not supported by some GLSL versions, but, where is the complete list of these functions vs versions they need? But the problem is, i ...
If glLinkProgram sets the GL error state then the shader(s) are not compatible with the card.
6,073,150
6,073,511
DEFPUSHBUTTON not defaulting focus to IDCANCEL
My resource file contains a DEFPUSHBUTTON for IDCANCEL, but for some reason, they Focus on the button is not changing from IDOK to IDCANCEL. IDD_HEALTHCARDINFO DIALOGEX 0, 0, 256, 223 STYLE DS_SETFONT | DS_MODALFRAME | WS_POPUP | WS_CAPTION | WS_SYSMENU CAPTION "Health Card Information" FONT 8, "MS Sans Serif", 0, 0, 0...
Default button doesn't affect focus. It affects what button is activated by the ENTER key when some non-button control has focus. You can use SetFocus in OnInitDialog (and also return FALSE) to change which control has focus when the dialog opens. Or you can reorder the controls within the dialog resource. As a side...
6,073,209
6,073,442
Is there something wrong with my CMakeLists?
The following is my CMakeLists file. By default, I expect it to define the symbol ALLEGRO_STATICLINK in the agui_allegro5 library, but it does not, however when I check off WANT_SHARED it defines it, which it shouldnt, but does not define AGUI_BACKEND_BUILD as it should. Is my logic flawed or something? cmake_minimum_r...
According to CMake documentation "DEFINE_SYMBOL sets the name of the preprocessor symbol defined when compiling sources in a shared library" while you are trying to use it on a static library, hence no effect. You may also find this discussion useful.
6,073,887
6,074,010
Template function "Subscript requires array type", but works in smaller projects. Why?
The following code is part of an interpolation function I wrote as part of a larger project. The first version of this function returned the myScalar yval, but I modified it to return a flag on whether or not the function worked. My question is this. The following code compiles when run by itself both on codepad.org ...
As per your comment, in your real code a mere double is being passed in for yarray rather than a double* or std::vector<double>. This is a simple case of having a sufficiently small, but incorrect, repro -- the real error lies in your real code.
6,074,039
6,074,141
Visual C++ Express 2010 suddenly won't accept #includes
I'm working with an API which has #defineed all their include files. I'm developing in Visual C++ 2010 Express, and it's been working fine up till now. I was adding a new cpp-file to the project, and accidentally added a "Windows Form" instead. VC warned me that my project was not using CLR at the moment, did I really ...
The problem almost certainly lies in the order in which the two statements are pre-processed, rather than having anything to do with inadvertently adding a Windows Form object. This knowledge base article suggests: The problem is in using a defined constant to specify an include file in the #include directive. The dir...
6,074,400
6,074,540
multiple return statements or a "goto end;"
What is better stylewise/readability? I have a loop that reads input and does different things according to the input, and when an error occurs, I need a simple return;. Example: while( get_input() ) { if( input == "somethingcool" ) { if( !process_somethingcool() ) return; // <-- a couple of...
For C, goto is reasonable (it's used widely in the Linux kernel) as you can enhance readability with a single point of return. For C++, because you have the possibility of anything throwing an exception, you implicitly have multiple points of return so you should always use the RAII model with multiple returns.
6,074,470
6,074,570
Reading from serial prints garbage
I'm trying to configure a serial communication between a dsp and my computer. The dsp sends the value of a 16-bit counter which increments each time it is sent. So it's just counting... Here is what I get on my computer : 3335 3336 3337 3338 36388 46920 16372 46919 3339 3340 3341 3342 36388 ...
I strongly suspect those are being sent by the DSP, the serial port drivers are pretty well debugged by now. Other possibilities are that you're reading the serial port from multiple threads at once (maybe in the same process, maybe not). Open the port exclusively to make sure that isn't your problem. Or, you could be...
6,074,797
6,075,000
Embedding ruby in c++, problem with ruby libraries
I want to have a ruby interpreter in my c++ application. I found an article about it: http://aeditor.rubyforge.org/ruby_cplusplus/index.html But here they use a makefile to compile the program, and I'm not really familiar with this consequently I can't modify it properly. I also found a really simple example here: http...
You probably don't have an i486 architecture. like for me it's "x86_64-linux" run the arch command to see what architecture you have and then put that infront of "-linux" and see if it that is there.
6,075,093
6,075,415
deducing references to const from rvalue arguments
Okay, this may seem like a silly question, but here it goes: template <typename T> void foo(T& x) { } int main() { foo(42); // error in passing argument 1 of 'void foo(T&) [with T = int]' } What is preventing C++ to instantiate the foo function template with T = const int instead?
The problem is that template type deduction has to work out an exact match, and in that particular case, because of the reference in the signature, an exact match requires an lvalue. The value 42, is not an lvalue, but rather an rvalue, and resolving T with const int would not yield a perfect match. Since template type...
6,075,271
6,075,288
why my local object destroyed twice?
I have a function returning a local object: class AT { public: AT() { cout<<"construct"<<endl; } AT(const AT& at) { cout<<"copy"<<endl; } ~AT() { cout<<"destroy"<<endl; } }; AT funcAt() { AT tmp; return tmp; } ... funcAt(); output is: construct copy destroy destroy I suppose there are only cons...
Because it is 1) created: AT tmp inside funcAt 2) copied: return tmp; and this is because the function returns a copy: AT funcAt() 3) destroy - the first tmp object, and the returned copy Hint: note the copy in the output :)
6,075,794
6,075,834
Template call: Actual specialization not called
#include <iostream> using namespace std; template<typename T> void test() { cout << "1"; } template<> void test<std::string>() { cout << "2"; } int main() { test<std::string()>(); //expected output 2 but actual output 1 } Why is the output 1 and not 2?
test<std::string> (note: no parentheses at the end) would yield what you expect. Writing it as test<std::string()> instantiates the template with the type "function taking no arguments and returning std::string"
6,075,806
6,075,835
How to pass data to C# COM DLL from unmanaged application
С# COM DLL Interface: public interface IShowDialog { void showMessage(byte[] array); } and call it in unmanaged C++ application: SAFEARRAY *array; array = SafeArrayCreateVector(VT_BSTR, 0, 1); long lidx = 0; SafeArrayPutElement( array, &lidx, SysAllocString(L"test") ); hr = dlg->showMessage(array); Result: 0x8...
The COM interface needs to be called from native code with a SAFEARRAY whose contents are VT_I1 instances. You are providing instead VT_BSTR values and hence receiving the error. You need to convert the string value into VT_I1 values and put those into the array. EDIT The proper in C++ name is VT_I1 and not VT_BYTE...
6,076,015
6,076,081
typename outside of template
This in VS2010sp1 doesn't compile (it does compile with gcc 4.6 though): template<class T> struct Upcast; template<> struct Upcast<signed char> { typedef signed short type; }; template<> struct Upcast<char> { typedef typename std::conditional<std::is_signed<char>::value,short, unsigned short>::type type; }; ...
VS is right on C++03. GCC is right on C++0x. Now it may be sensible for GCC to also allow this in C++03 mode (there are many things real compilers don't diagnose in C++03 mode that are actually only valid in C++0x), and it may as-well sensible for VS to reject it in C++03 mode. It doesn't matter anymore whether or not...
6,076,031
6,076,137
LAPACK wrappers for C/C++
I would like to use Visual Studio 2008, programming in C++, but would also like to use LAPACK power, Is there any wrapper so I can use LAPACK in Visual Studio 2008.
Check out CLAPACK, lapack++, or its supposed successor Template Numerical Toolkit.
6,076,225
6,076,363
How to use SGI Ropes with Windows Visual Studio 8.0?
Good afternoon, We are building a prototype of a deduplication program with C++ on Windows and Linux. Yesterday, we posted a question on Stack Overflow about how to avoid the STL string deep copying when we store a std::string version of a record to deduped in the std::string* StringArray, STL makes a deep copy of the ...
Did you download only the two implementation files? I doubt that this would work as they most likely rely on other files that are part of the SGI STL implementation. That would explain why you can't build them... The easiest way to get at the SGI rope implementation might be to use STLport, which is a port and further ...
6,076,254
6,076,334
recombine split TCP packet with flash sockets
I have a program in c++ that sends a socket of 23723 bytes to a flash player in one "shot". The flash player sometimes receives two packets of size 17520 and 6203, and other times it receives a single packet of 23723. EDIT: There does not seem to be a way to obtain the total number of bytes associated with the send dat...
This has nothing to do with tcp. The socket can send you any number of bytes as long as it is at least one byte. So you might get [1, 23722]. The correct way to do this is to call read in a loop and fill an array yourself. If your code does not contain a loop but works, then it works by accident. This cannot work witho...
6,076,292
6,076,327
typedef with templates
template<class T> struct A { typedef int Int; A::Int b; // Line 1 (fails) Int c; // Line 2 (compiles) }; int main(){ A<int> x; x.c = 13; } Errors error: ISO C++ forbids declaration of ‘Int’ with no type error: extra qualification ‘A<T>::’ on member ‘Int’ error: expected ‘;’ before ‘b’ Line 1 fa...
You need a typename typename A::Int b; The typename keyword is required because the member is referred to using a qualified name A::Int. Int c is fine because no qualified name is used in that case. 14.6/6 Within the definition of a class template or within the definition of a member of a class template, the keyword ...
6,076,405
6,076,577
What is boost log, how to get it and how to build it
So I heard good things about boost log. This claims its existence: http://boost-log.sourceforge.net/libs/log/doc/html/index.html This is the tutorial: http://boost-log.sourceforge.net/libs/log/doc/html/log/tutorial.html#log.tutorial.trivial However, boost log is not part of boost. Hence not in the regular boost branch...
boost log v2 is simply what you get by checking out trunk, according to what Andrey says in the post you link. indeed, it seems that this version too has got problems compiling against boost::filesystem v3. if this is also your case, one workaround is compiling after adding <define>BOOST_FILESYSTEM_VERSION=2 to the ja...
6,076,434
6,076,486
Compile C++ to asm in Visual Studio
Possible Duplicate: How to generate assembly code from C++ source in Visual Studio 2010 Hello. How can I compile C++ code to asm in Visual Studio? In gcc I just add one parampeter: -s
Looks like /FAs is the command-line argument. There is also a setting in the GUI: http://codegem.org/2008/10/generate-assembly-from-c-code-in-visual-studio
6,076,939
6,077,114
Which STL container has facilities for slicing into two or more containers?
Say I have a vector / list whatever of ints populated with 2300 values I want to be able to easily slice this into 4 vectors /lists (not necessarily of equal size). e.g. vec1 ( elements 0 - 500 ) vec2 ( elements 501 - 999) vec3 ( elements 1001 - 1499) etc.
A common way to do it would be to use the one container, and just define separate iterator ranges over it. std::vector<int> vec(2300); it0 = vec.begin(); it1 = vec.begin() + 500; it2 = vec.begin() + 1000; it3 = vec.begin() + 1500; it4 = vec.begin() + 2000; it5 = vec.end(); Now, the first range is simply defined by th...
6,076,941
6,077,261
How do I fix my "self-deleting" .exe from deleting itself early?
For the sake of testing and personal proof of concept, I have a .exe file that only outputs a simple string and then calls a system pause (literally system("pause") in C++). I have a simple Python script I'm testing on a Windows XP VM that does these operations when messing up: subprocess.call(r'echo Nothing special. >...
Given the symptoms, my understanding is that you can only safely delete an executable in this particular setting (Windows XP, perhaps at a particular patch level, when the executable is from an alternate stream) once this executable has finished initializing. If you delete an executable while it's loading, the program ...
6,076,946
6,076,999
Specializing member function for non-template class in C++
I'm trying to specialize a template member function of a non-template class using a templatized parameter: #include <array> class C { public: template<class Container> void Foo( Container& ) { // ... } }; template<class T, std::size_t N> template<> void C::Foo< std::tr1::array<T,N> >( std::tr1::array<T,N>&...
Only the member function is templated, which means that you should only use one template<...> in there. But that will not solve it either, as you cannot partially specialize a function. The usual way of handling the problem is through overloads, rather than specialization (specialization of template functions is not th...
6,077,143
6,077,164
Disable copy constructor
I have a class: class SymbolIndexer { protected: SymbolIndexer ( ) { } public: static inline SymbolIndexer & GetUniqueInstance ( ) { static SymbolIndexer uniqueinstance_ ; return uniqueinstance_ ; } }; How should I modify it to disable code like: SymbolIndexer symbol_indexer_ = SymbolIndexer::GetUn...
You can make the copy constructor private and provide no implementation: private: SymbolIndexer(const SymbolIndexer&); Or in C++11, explicitly forbid it: SymbolIndexer(const SymbolIndexer&) = delete;
6,077,170
6,077,450
MsiEnumProductsEx Not Working
I have the following application, to check installed programs in a system: #include <iostream> #include <Msi.h> #include <Windows.h> using namespace std; void main() { UINT ret; DWORD dwIndex = 0; DWORD dwContext = MSIINSTALLCONTEXT_ALL; char szInstalledProductCode[39] = {0}; char szSid[128] = {0}...
The MSIINSTALLCONTEXT_ALL (and related identifiers) are defined in <msi.h> only if _WIN32_MSI >= 300. You have to tell the Windows SDK what the minimum OS version you're targeting is, by defining a few macros before installing any SDK headers (like <msi.h> or <windows.h>). You do that according to this MSDN page. Once...
6,077,189
6,077,274
Will std::string always be null-terminated in C++11?
In a 2008 post on his site, Herb Sutter states the following: There is an active proposal to tighten this up further in C++0x and require null-termination and possibly ban copy-on-write implementations, for concurrency-related reasons. Here’s the paper: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2534.htm...
Yes. Per the C++0x FDIS 21.4.7.1/1, std::basic_string::c_str() must return a pointer p such that p + i == &operator[](i) for each i in [0,size()]. This means that given a string s, the pointer returned by s.c_str() must be the same as the address of the initial character in the string (&s[0]).
6,077,332
6,077,379
Does reference changes the state of the referent
As I read ---references are not pointers it is the object itself,A reference is an entity that is an alias for another object. ---references can never represent NULL ---Reference variables allow two variable names to address the same memory location: ---it cannot later be made to refer to a different object ---A refere...
No, it does not convert integers. You now just have an alias for integers through which you can't change it. You can still change integers through the original name: int i = 0; int const& i_ref = i; i = 5; cout << i_ref; // outputs 5 The above examble also shows how you can change the state of the referee.
6,077,370
6,077,410
Extract variadic template parameter pack and use it in another variadic template in a type traits meta-function?
I want to determine if any variadic class template is the base of another class. Typically I'd use std::is_base_of, but I don't think my use case fits, and I'm not sure if there's already something in std or boost to handle this. I want the variadic base class template's parameter pack to come from another variadic c...
template <template<typename...> class A, typename B, typename ArgsC> struct is_variadic_base_of; template <template<typename...> class A, typename B, template<typename...> class C, typename ...ArgsC> struct is_variadic_base_of<A, B, C<ArgsC...>> : std::is_base_of<A<ArgsC...>, B> {}; Hope it helps!
6,077,443
6,077,698
Can I use the search box control seen in Windows Explorer in my own application?
Can I use this search box control seen in Windows Explorer in my own Qt/C++ application? Or is it a custom control I'd have to implement manually?
I haven't seen this kind of control, however in Qt it's easy to implement it manually. You may follow this tutorial: http://labs.qt.nokia.com/2007/06/06/lineedit-with-a-clear-button/ and just replace a clear icon with a search one (and change slot from clear() to something which performs desired search, of course).
6,077,526
6,084,029
How is SndVol able to change the volume level of a given audio session?
I am writing my own API to perform some of the functionality of the SndVol system utility. I would like part of this API to be the ability to set the volume level of a given audio session. SndVol displays a slider on the "Device" panel that the user can use to change the master volume level of the audio device as well ...
If you call QueryInterface on the IAudioSessionControl interface, you can often get access to an ISimpleAudioVolume.
6,077,652
6,077,739
Swinging/Bobbing Camera
I have been searching on the internet for a while now, for a solution with nothing. What I want to know is how to implement a swing/bobbing motion in a 3D Camera in OpenGL(or DirectX) like you find in Minecraft, Call of Duty, etc. I tried cycloids, while they work I can't get the direction to work correctly.
What do you think about the following. compute cam_pos, cam_dest, cam_up as usual. compute cam_right as cross (cam_pos, cam_up) create a float camera_time (if walking, camera_time += delta_time; ) compute offset_factor = sin(camera_time); Then you can call gluLookAt or similar function as follows. gluLookAt(cam_pos +...
6,077,706
6,078,796
Get number of bytes read by boost::asio::async_read
I am attempting to convert the return value of the function boost::asio::async_read to an int in order to see if I've received any data: int recvlen = boost::asio::async_read ( socket_, boost::asio::buffer((char*)buffer, 1000), boost::bind(&Connection::Receive, this, boost::asio::placeholders::error) ); H...
async_read does not return the number of bytes read. It performs the read in the background, asynchronously. The number of bytes is passed to the completion handler. The completion handler is invoked by ASIO when the read completes. You pass the completion handler into async_read. async_read is a template that accepts ...
6,077,718
6,081,253
Is this a valid (ab)use of lambda expressions?
Like we all know, it's not that easy to break from a nested loop out of an outer loop without either: a goto (Example code.) another condition check in the outer loop (Example code.) putting both loops in an extra function and returning instead of breaking (Example code.) Though, you gotta admit, all of those are kin...
Please don't do that in a project I'm managing. That's an awkward abuse of lambdas in my opinion. Use a goto where a goto is useful.
6,077,833
6,077,884
How to check if Google Test is running in my code
I have a section of code that I would not like to run if it is being unit tested. I was hoping to find some #defined flag that is set by the gtest library that I can check. I couldn't find one that is used for that purpose, but after looking through the gtest header, I found one I thought I could use like this: SomeCla...
Google Test doesn't need or provide its own build wrapper. You don't even have to recompile your source files sometimes. You can just link them along with your test code. Your test code calls your already-compiled library code. Your library code probably doesn't even include and Gtest headers. If you want your library ...
6,077,960
6,077,992
C++ Segmentation fault from pointer backtrace
I am currently getting a seg fault and its starting at what I believe to be a line in main, after doing a backtrace in gdb, I can basically pinpoint it but I am not sure what needs to change. here are the places I am seeing it in order: First in main: DeckOps *deck = new DeckOps(filename); I believe is the line that i...
In the DeckOps::DeckOps, the line deck->insertRear(card); is probably causing the segfault. deck is a pointer but you never initialize it to anything (like deck = new dlist or whatever) so it points to a random location in memory (or is initialized to 0 depending on your compiler) and you're trying to use the random m...
6,077,986
6,078,025
I finally made my add function in linked list but cant use in main. :(
I finally made my func but can't use it in my main. The compiler errors with: cannot convert Node' toNode*' for argument 1' tovoid add(Node*, Node*)' Can somebody help me resolve the error? #include <iostream> #include <stdlib.h> #include <stdio.h> using namespace std; struct Node { int data; struct N...
It should be void add(struct Node* node, struct Node* newNode);. OR: struct Node { int data; struct Node *next; }Node; Also, please note that you asign values to fields of newNode which is a pointer, before allocating space for the actual struct: newNode = malloc(sizeof(stuct Node)); And one more thing ...
6,078,127
6,078,334
How can I successfully link Flex, Bison, and Node.js in a native Node addon?
I'm trying to write a native Node.js parser using Flex/Bison. There are three parts to the addon: the lexer, the parser, and the node/v8 interface. The lexer and the parser were working well in the beginning (I used g++ to compile the lexer/parser and included the necessary lexer functions like this: http://tldp.org/HO...
renaming the files to .cc will generally cause default make rules to build using c++ instead of c. That could mean that the linkage is wrong on the functions in the lex.yy.c file. I think you need to figure out another way to make the node build system recognize your .c files and build them properly with as c, not c++
6,078,159
6,078,605
Scrollbar Appearance Control in Windows 7
I have an application that has a ListView control with scrollbars, and it has the cool looking scrollbars in it automatically: CreateWindowExW(WS_EX_WINDOWEDGE,L"SysListView32",L"MyList", WS_CHILD|WS_VISIBLE|LVS_NOSCROLL|LVS_REPORT|LVS_NOCOLUMNHEADER|WS_VSCROLL|LVS_SHOWSELALWAYS| LVS_SINGLESEL, 0,0,500,290,ownerhWnd, (...
Maybe an open door, but you have added a Windows XP/Vista/7 manifest to your application's resources?
6,078,431
6,078,549
Selecting a device for CUDA debugging
I've got a couple of Parallel Nsight compatible CUDA GPU's. The second (lower) one is connected to my monitor, and the first (upper) one is is set up as a PhysX accelerator. You can clearly see my configuration below. Now in order to perform CUDA debugging with Nsight, I need to only run kernel code on the GPU not conn...
cudaSetDevice https://visualization.hpc.mil/wiki/Choosing_the_GPU_in_a_Multi-GPU_system
6,078,513
6,078,531
Error : non-lvalue in assignment
#include <iostream> using namespace std; class Array { friend ostream &operator<<( ostream &, const Array & ); public: Array( int = 5 ); Array( const Array & ); ~Array(); int getSize() const; const Array &operator=( const Array & ); // subscript operator for non-const objects returns modifiabl...
You cannot modify a const reference, Try this: //Snippet1 Array& integers4=integers1; integers4[3] = 2000; To clarify OP's doubt about modifying const references: //Snippet2 //This will not compile as you saw. const Array& integers4=integers1; integers4[3] = 2000; //errors Now this is what Xeo did in his reply to t...
6,078,529
6,078,541
error LNK2019: unresolved external symbol "public: __thiscall Server::Server(class boost::asio::io_service &)
The following code using boost::asio will not compile: #ifndef _SERVER_H_ #define _SERVER_H_ #include "Connection.h" class Server { public: Server(boost::asio::io_service& io_service); private: void start_accept(); void handle_accept(Connection::pointer new_connection,...
This means that whatever source file you put Server's constructor definition into isn't being compiled and/or linked.
6,078,542
6,078,564
Does bitwise-or guarantee an evaluation ordering?
Say I have this code: unsigned int func1(); unsigned int func2(); unsigned int func3(); unsigned int x = func1() | func2() | func3(); Does C++ guarantee that func1() will be called first, then func2(), and then func3()? Or is the compiler allowed to call the functions in any order it feels like? Also, is the compiler...
No, there is no guarantee which order the functions will be called in. Unlike ||, | does not imply a sequence point. All functions in the expression must be called unless the implementation can determine that they have no side-effects and it can determine the result of the expression without actually calling one of the...
6,078,597
6,079,874
How to convert COPYDATASTRUCT's Data to a understandable string in VC++?
I am trying to change poCopyData (PCOPYDATASTRUCT) to a string and also a way to turn a string back into that. So i can send it, poCopyData is where the program copies the messages from another program to. PCOPYDATASTRUCT poCopyData = (PCOPYDATASTRUCT)ulParam; // Note this is just outputs the message i don't how it co...
inline LRESULT CopyData( HWND hwnd, DWORD message, const char* str ) { COPYDATASTRUCT copy_data = { message, strlen( str ) + 1, str }; return SendMessage( hwnd, WM_COPYDATA, 0, reinterpret_cast< LPARAM >( &copy_data ) ); } LRESULT WINAPI WndProc( HWND hwnd, UINT message, WPARAM wparam, LPARAM lparam ) { if( mess...
6,078,712
6,079,669
Is it safe to fork from within a thread?
Let me explain: I have already been developing an application on Linux which forks and execs an external binary and waits for it to finish. Results are communicated by shm files that are unique to the fork + process. The entire code is encapsulated within a class. Now I am considering threading the process in order to ...
The problem is that fork() only copies the calling thread, and any mutexes held in child threads will be forever locked in the forked child. The pthread solution was the pthread_atfork() handlers. The idea was you can register 3 handlers: one prefork, one parent handler, and one child handler. When fork() happens prefo...
6,078,727
6,078,754
Guess the number - Infinite loop when bad read
So I am making this Guess the number game in c++ that looks like this: #include <iostream> #include <cstdlib> #include <ctime> using namespace std; int main() { srand(time(0)); int secretNumber = rand() % 100 + 1; //Generate "Random number" int nbrOfGuesses = 0; int userInput; cout<<"\t***********...
Check this post, it is about the same problem. To summarize: cin>>userInput; if (cin.fail()) { cout<<"Invalid Entry, please try again."<<endl; cin.clear(); cin.ignore(numeric_limits<streamsize>::max(), '\n'); } Thanks ildjarn for pointing the missing ignore statement, I missed that part even though its clearly ...
6,078,861
6,078,883
How to make '<?=' available for use in C++?
Possible Duplicate: What does the >?= operator mean? I found this code segment ... for(k=i+1;k<j;k++) r <?= go(i,k,b)+go(k,j,b); for(k='A';k<='Z';k++) r <?= 1+go(i,j,k); ... I'm interested in <?= operator. It seems to me that it should compare value of r with right side of the operator and in case that right side i...
The <?= operator was a GCC extension that was removed in version 4.2. See this question. Use std::min instead.
6,079,020
6,079,060
In what scenarios might a web crawler be CPU limited as opposed to IO limited?
It seems like typical crawlers that just download a small number of pages or do very little processing to decide what pages to download are IO limited. I am curious as to what order of magnitude estimates of sizes relevant data structures, number of stored pages, indexing requirements etc that might actually make CPU t...
Only when you are doing extensive processing on each page. eg if you are running some sort of AI to try to guess the semantics of the page. Even if your crawler is running on a really fast connection, there is still overhead creating connections, and you may also be limited by the bandwidth of the target machines
6,079,044
6,079,116
How do I manually enter in a Matrix of data?
I just want to hard code in a matrix using C++ (g++ 4.1.2), by default I went with a std::vector of std::vectors. My guess is this can be done in one line I just don't know the correct syntax. For example: (1,2,5) (9,3,6) (7,8,4) I thought it might be something like this - vector<int> v1(1,2,3); vector<int> v2(4,5,...
If you're not going to change the size or shape of this matrix and since you're hard-coding the values anyway, you may be better with a plain old array: int matrix[][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; Otherwise, Fred Nurk's answer is what you are looking for.
6,079,052
6,079,095
Property like features in C++?
My use is pretty complicated. I have a bunch of objs and they are all passed around by ptr (not reference or value unless its an enum which is byval). At a specific point in time i like to call CheckMembers() which will check if each member has been set or is null. By default i cant make it all null because i wouldnt k...
Reality (edit): this proved to be tricky, but the following code should handle your requirements. It uses a simple counter in the base class. The counter is incremented once for every property you wish to track, and then decremented once for every property that is set. The checkMembers() function only has to verify tha...
6,079,063
6,079,087
Why is a function call, rather than variable addresses, used to detect stack growth direction?
I read different responses to the question of detecting stack growth detection and I understand that, in modern architectures, stack might grow randomly, might be created off heap, and so on. However, in this classic interview question, I want to understand why people use a function call rather than comparing 2 local v...
Within a single stack frame, the compiler is free to order the local variables as it sees fit, so the code: int i; double j; may have i before or after j. As long as the compile generates the correct code to access the variable, it can go anywhere. In fact, unless you use the address-of operator & (or otherwise have t...
6,079,124
8,981,748
dyld: Library not loaded (image not found) but it's there
I got this error when trying to launch my Qt-application (which was deployed with macdeployqt) on another Mac. dyld: Library not loaded: kqoauth.framework/Versions/0/kqoauth Referenced from: /MyProject.app/Contents/MacOS/MyProject Reason: image not found Trace/BPT trap I checked the .app-bundle and copied the kqoauth....
Check that otool -L was showing relative paths for both Qt and for kqoauth, my guess is they are probably all starting at root / and you didn't see the qt loading failing, because they're installed on your system. Regardless, I suggest following this tutorial to correctly inform the binary where all the dylibs are: Qt ...
6,079,133
6,079,148
return value as a function argument
I have posted a similar question before why my local object destroyed twice? but I am confused on other point. here's the program: class AT { public: int a; AT() { cout<<"construct"<<endl; } AT(const AT& at) { cout<<"copy"<<endl; } ~AT() { cout<<"destroy"<<endl; } }; AT func(AT at) { return at...
AT func(AT at) { return at; } Probably some compiler optimization. At is not created only to be destroyed afterwards. Instead the argument is of func is used to create the argument of func2 directly as if you had called func2(at);
6,079,154
6,079,182
Format of the basic CGI protocol. Examples
I am writing a C CGI program For GET requests, I assume all the information is somehow stored in getenv(). My question is, what does this array look like a most basic CGI request from the webserver. With two prarameters e.g. username= and password=. For POST request, I am unsure. I've read that stuff is handled on stan...
envp is not standard (well, not ISO C or C++ standard anyway, though POSIX may have something for it). However, envp is pretty much the same format as argv escept it doesn't have a controlling argc to limit it. Each envp[x] will be of the form "key=value" where the key is the environment variable name and the value is ...
6,079,603
6,079,650
Infinite compilation with templates
This question is just out of curiosity. In recursive templates if we forget to put one particular specialization, then compiler will do large number of iterations and then stop at sometime and gives error such as, error: incomplete type ‘X<-0x000000000000001ca>’ used in nested name specifier In certain cases, the comp...
If I understand your question correctly, you want the compiler to recognise that it will never stop iterating. Besides just stopping after a fixed number of nesting types, what you want is provably impossible: If I see it correctly you can express any turing-machine in this fashion (at least the templates in D are turi...
6,079,653
6,079,835
Custom windows skin,
What is the best way to create a custom skin for an application the way google chrome has done in Windows using native API? I'm writing an opengl app and would like to have all the windows borders, min, max button and caption bar handled by the app.. I tried using CreateWindowEx to create a borderless window, however w...
You will want to handle the WM_NC* methods, including WM_NCPAINT, WM_NCHITTEST, WM_NCLBUTTONDOWN, etc.
6,079,785
6,079,821
What is the difference between putc and ungetc?
int ungetc(int c, FILE *fp) pushes the character c back into fp, and returns either c, or EOF for an error. where as int putc(int c, FILE *fp) writes the character c into the file fp and returns the character written, or EOF for an error. //These are the statements from K&R. I find myself confused, because putc() can b...
putc writes something to output, so it appears on the screen or in the file to which you've redirected output. ungetc put something back into the input buffer, so the next time you call getc (or fgetc, etc.) that's what you'll get. You normally use putc to write output. You normally use ungetc when you're reading input...
6,079,807
6,079,829
warning errors problem
Program: void DibLaplacian8Direct(CDib sourceImg) { register int i,j; int w = sourceImg.GetWidth(); int h = sourceImg.GetHeight(); CDib cpyImage = sourceImg; BYTE** pSourceImg = sourceImg.GetPtr(); BYTE** pCpyImage = cpyImage.GetPtr(); float G; for(j =1;j<h-1;j++) { for(i ...
The first warning is due to the fact that a float has only six significant figures whereas an int can have more. If it does, then accuracy is lost. In general, you cannot convert an integer to floating point without possible losing data. Also, you cannot convert from floating point back to integer without losing the de...
6,079,850
6,079,917
Mutual return types of member functions (C++)
Is it possible in C++ to have two classes, let's call them A and B, such that A has a member function f that returns an object of class B, and B has a member function g that returns an object of class A? (The text below is just to show I have "done my homework".) The problem is just how to write signatures of these fun...
Yes, Implement function definitions of class A after you declared class B class B; class A { B f(); }; class B { A g() { A a; return a; } }; B A::f(){ B b; return b; }
6,080,033
6,080,053
How to receive more than 1440 through the socket
I wrote two simple programs server and a client using sockets in C++ (Linux). And initially it was a sample client-server application (echo-message sending and receiving the answer). Next, I changed the client in order to implement HTTP GET (now I do not use my sample server anymore). It works, but whatever buffer size...
The buffer size is determined by factors outside your control (routers, ADSL links, IP stacks, etc.). The standard way to transmit large volumes of data is to call recv() repeatedly.
6,080,129
6,082,291
Trick : filling array values using macros (code generation)
Are C++ Templates just Macros in disguise? I was reading the above topic, and suddenly this idea came to my mind: why not try writing some tricky macros which can be used in our real code, (not just only as puzzles which are useless in real life)? So the first thing came to mind is : filling array values with macros: i...
If you wish to delve into Preprocessor programming, I can only recommend the Boost.Preprocessor library as a building block, you'll avoid having to rewrite things from scratch. For example, in order to create your table, I would have used (ideone): #include <iostream> #include <boost/preprocessor/repetition/enum.hpp> ...