question_id
int64
25
74.7M
answer_id
int64
332
74.7M
title
stringlengths
20
150
question
stringlengths
23
4.1k
answer
stringlengths
20
4.1k
1,666,224
1,666,232
What is the size of void?
What would this statement yield? void *p = malloc(sizeof(void)); Edit: An extension to the question. If sizeof(void) yields 1 in GCC compiler, then 1 byte of memory is allocated and the pointer p points to that byte and would p++ be incremented to 0x2346? Suppose p was 0x2345. I am talking about p and not *p.
The type void has no size; that would be a compilation error. For the same reason you can't do something like: void n; EDIT. To my surprise, doing sizeof(void) actually does compile in GNU C: $ echo 'int main() { printf("%d", sizeof(void)); }' | gcc -xc -w - && ./a.out 1 However, in C++ it does not: $ echo 'int main() { printf("%d", sizeof(void)); }' | gcc -xc++ -w - && ./a.out <stdin>: In function 'int main()': <stdin>:1: error: invalid application of 'sizeof' to a void type <stdin>:1: error: 'printf' was not declared in this scope
1,666,492
1,666,562
Multiple threads and memory
I read in the Visual C++ documentation that it is safe for multiple threads to read from the same object. My question is: how does a X86-64 CPU with multiple cores handle this? Say you have a 1 MB block of memory. Are different threads literally able to read the exact same data at the same time or do cores read one word at a time with only one core allowed to read a particular word at a time?
Not only are different cores allowed to read from the same block of memory, they're allowed to write at the same time too. If it's "safe" or not, that's an entirely different story. You need to implement some sort of a guard in your code (usually done with semaphores or derivates of them) to guard against multiple cores fighting over the same block of memory in a way you don't specifically allow. About the size of the memory a core reads at a time, that's usually a register's worth, 32 bits on a 32bit cpu, 64 bits for a 64bit cpu and so on. Even streaming is done dword by dword (look at memcpy for example). About how concurrent multiple cores really are, every core uses a single bus to read and write to the memory, so accessing any resources (ram, external devices, the floating point processing unit) is one request at a time, one core at a time. The actual processing inside the core is completely concurrent however. DMA transfers also don't block the bus, concurrent transfers get queued and processed one at a time (I believe, not 100% sure on this). edit: just to clarify, unlike the other reply here, I'm talking only about a no-cache scenario. Of course if the memory gets cached read-only access is completely concurrent.
1,666,537
1,666,713
Any issues with large numbers of critical sections?
I have a large array of structures, like this: typedef struct { int a; int b; int c; etc... } data_type; data_type data[100000]; I have a bunch of separate threads, each of which will want to make alterations to elements within data[]. I need to make sure that no to threads attempt to access the same data element at the same time. To be precise: one thread performing data[475].a = 3; and another thread performing data[475].b = 7; at the same time is not allowed, but one thread performing data[475].a = 3; while another thread performs data[476].a = 7; is allowed. The program is highly speed critical. My plan is to make a separate critical section for each data element like so: typedef struct { CRITICAL_SECTION critsec; int a; int b; int c; etc... } data_type; In one way I guess it should all work and I should have no real questions, but not having had much experience in multithreaded programming I am just feeling a little uneasy about having so many critical sections. I'm wondering if the sheer number of them could be creating some sort of inefficiency. I'm also wondering if perhaps some other multithreading technique could be faster? Should I just relax and go ahead with plan A?
With this many objects, most of their critical sections will be unlocked, and there will be almost no contention. As you already know (other comment), critical sections don't require a kernel-mode transition if they're unowned. That makes critical sections efficient for this situation. The only other consideration would be whether you would want the critical sections inside your objects or in another array. Locality of reference is a good reason to put the critical sections inside the object. When you've entered the critical section, an entire cacheline (e.g. 16 or 32 bytes) will be in memory. With a bit of padding, you can make sure each object starts on a cacheline. As a result, the object will be (partially) in cache once its critical section is entered.
1,666,580
1,666,617
What does the colon mean in struct declarations in C?
Reading the code of TeXmacs, I saw this: struct texmacs_input_rep : concrete_struct { ... }; What does that mean? This syntax is defined in the C standard, p113, but I didn't find the meaning of it, but that's because I don't know how to read grammar rules. Because concrete_struct is another struct, that contains functions looking like a constructor and a virtual destructor, and because I read elsewhere that classes in C++ are actually struct with public members by default, I guess that this is the way of doing inheritance with struct in C (because it is the C standard...). Is this correct?
It is C++ syntax and equivalent to this: class texmacs_input_rep : public concrete_struct { public: ... }; This is the normal syntax for inheritance of classes, here texmacs_input_rep is inherited from concrete_struct. About that syntax in C: The C-Standard you linked to defines (6.7.2.1): struct-or-union-specifier: struct-or-union identifieropt { struct-declaration-list } struct-or-union identifier struct-or-union: struct union So according to C it must be struct, followed by an optional identifer, followed by {. Or only struct followed by an identifer (a forward declaration). In neither case there is room for an additional : ... in there. The : mentioned later in that paragraph of the standard is about bit-field widths, like this; struct foo { unsigned a : 4; unsigned b : 3; }; Here a and b are only 4 and 3 bits wide, but that's different syntax than in the question.
1,666,581
1,666,610
How to use extended precision cmath functions by preference
My question is this: is there a way to always use the extended precision versions of mathematical functions - such as sqrt, exp, &c - without using an explicit cast when providing a single or double precision argument? For example I want this functionality, without the hassle of the casting: float x=15.0; float answer; answer=sqrt((long double)x); This comes in the context of scientific computing, where many iterations of a loop containing such functions is required. Even though at the end of the process I only require single precision, the floating point errors that result during each iteration can sum to something significant after a few thousand iterations. Thanks.
In C If you #include <math.h>, which declares such function as returning a double and accepting double arguments, the compiler will do the cast for you implicitily. #include <math.h> /* ... */ int x = sqrtl(sqrt(sqrtf(42))); /* 1 ^^ implicit cast of int to float */ /* 2 ^^^^^^^^^ implicit cast of float to double */ /* 3 ^^^^^^^^^^^^^^^ implicit cast of double to long double */ /* 4 ^^^^^^^^^^^^^^^^^^^^^^ implicit cast of long double to int */
1,666,662
1,667,219
Call a JavaScript function from C++
I have a CDHTMLDialog, with which I have 2 HTML pages and a .js file with a few fairly simple functions. I would like to be able to call one of the JS functions from my program with a simple data type passed with it. e.g. MyFunc(int). Nothing needs to be returned. I would appreciate any guidance on how I go about this, thanks. Edit: Thanks to CR for his answer, and everyone else who submitted there ideas too. Something a little like this worked in the end (stripped a little error handling from it for clarity): void callJavaScriptFunc(int Fruit) { HRESULT hRes; CString FuncStr; CString LangStr = "javascript"; VARIANT vEmpty = {0}; CComPtr<IHTMLDocument2> HTML2Doc; CComPtr<IHTMLWindow2> HTML2Wind; hRes = GetDHtmlDocument(&HTML2Doc); hRes = HTML2Doc->get_parentWindow(&HTML2Wind); if( Fruit > 0 ) { FuncStr = "myFunc(808)"; // Javascript parameters can be used hRes = HTML2Wind->execScript(FuncStr.AllocSysString(), LangStr.AllocSysString(), &vEmpty); } }
Easiest approach would be to use the execScript() method in the IHTMLWindow2 interface. So you could get the IHTMLDocument2 interface from your CDHTMLDialog by calling GetDHtmlDocument, then get the parentWindow from IHTMLDocument2. The parent window will have the IHTMLWindow2 interface that supports execScript(). There might be an easier way to get the IHTMLWindow2 interface from your CDHTMLDialog but I'm used to working at a lower level.
1,666,802
1,666,811
Is there a __CLASS__ macro in C++?
Is there a __CLASS__ macro in C++ which gives the class name similar to __FUNCTION__ macro which gives the function name
The closest thing there's is to call typeid(your_class).name() - but this produces compiler specific mangled name. To use it inside class just typeid(*this).name()
1,666,927
1,667,040
CWnd::CreateDlgIndirect leaves m_hWnd==NULL
A dialog I'm working on isn't displaying, using: CWnd::CreateDlgIndirect(LPCDLGTEMPLATE lpDialogTemplate,CWnd* pParentWnd, HINSTANCE hInst) The call to CreateDlgIndirect is in a lon-used base-class, which effectively takes the IDD of the dialog template in the resource file - it works fine for many other dialogs but I can't see what's different in my dialog. My dialog works fine when created in a more normal way, but I have to use the base class as it has loads of other functionality built in. What I find when trawling through CWnd::CreateDlgIndirect in dlgcore.cpp, is that the plain Win32 API call is failing: hWnd = ::CreateDialogIndirect(hInst, lpDialogTemplate,pParentWnd->GetSafeHwnd(), AfxDlgProc); I can't step into that function for some reason, so all I see is the HWND is NULL. Can anyone suggest what kind of problems might be causing this? I compared the two dialog resource templates and their properties are the same. edit: I have one custom control on the dialog. When I remove this, it works. No idea why, what difference might this make?
One of the more obscure ways for CreateDialogXXX to fail is for a child control on the dialog to fail creation. Usually because the application has not initialized the common controls library before attempting to effect the dialog creation. See InitCommonControlsEx One way to check this is to open the dialog in the resource editor, go to the dialog's properties, and find and turn on the DS_NOFAILCREATE flag. Usually called something obscure like "No Fail Create". Or add the DS_NOFAILCREATE directly to your dialog template in memory. This will allow the dialog to show, and the culprit should be evident by its absence. In the case that the child control is an actual custom control - well the custom window class is either not registered correctly, or at all. Check the HINSTANCE used in registration - unless the CS_GLOBAL flag is specified, window classes are identified by (hInstance, ClassName) - this prevents window classes using the same name in different dlls conflicting.
1,666,963
1,667,084
debugging templates with GDB
My gdb is GNU gdb Red Hat Linux (6.3.0.0-1.162.el4rh) and I can't debug templates. How can I debug templates with this debugger?
if your problem is just about placing breakpoint in your code. Here is a little snippet ex: main.cpp #include <iostream> template <typename T> void coin(T v) { std::cout << v << std::endl; } template<typename T> class Foo { public: T bar(T c) { return c * 2; } }; int main(int argc, char** argv) { Foo<int> f; coin(f.bar(21)); } compile with g++ -O0 -g main.cpp gdb ./a.out (gdb) b Foo<int>::bar(int) Breakpoint 2 at 0x804871d: file main.cpp, line 16. (gdb) b void coin<int>(int) Breakpoint 1 at 0x804872a: file main.cpp, line 6. (gdb) r ... debugging start otherwise you could just use (gdb) b main.cpp:16
1,667,049
1,667,070
C++ array list or vector?
I'm trying to rewrite code I've written in matlab in C++ instead. I have a long cell in matlab containing 256 terms where every term is a 2x2 matrix. In matlab i wrote it like this. xA = cell(1,256); xA{1}=[0 0;3 1]; xA{2}=[0 0;13 1]; xA{3}=[0 0;3 2]; and so on... What would be the easiest thing to use in c++? Can I give an array with the dimensions [256][2][2] all the 4 values at a time or do I have to write one line for every specific valuen in the array? /Mr.Buxley
You can certainly initialize them all at once, although it sounds like a lot of tedious typing: float terms[256][4] = { { 0, 0, 3, 1 }, { 0, 0, 13, 1 }, { 0, 0, 3, 2} ... }; I simplified it down to an array of 256 4-element arrays, for simplicity. If you wanted to really express the intended nesting, which of course is nice, you need to do: float terms[256][2][2] = { { { 0, 0 }, { 3, 1 } }, { { 0, 0 }, { 13, 1 } }, { { 0, 0 }, { 3, 2 }} ... }; That would be 256 lines, each of which has a "list" of two "lists" of floats. Each list needs braces. But, since C++ supports suppressing braces in things like these, you could also do: float terms[256][2][2] = { { 0, 0, 3, 1 }, { 0, 0, 13, 1 }, { 0, 0, 3, 2} ... }; In fact, you could even remove the braces on each line, they're optional too. I consider relying on the suppression slightly shady, though. If you want to use higher-level types than a nested array of float (such as a Matrix<2,2> type, or something), initialization might become tricker.
1,667,386
1,669,404
UBLAS Matrix Finding Surrounding Values of a Cell?
I am looking for an elegant way to implement this. Basically i have a m x n matrix. Where each cell represents the pixel value, and the rows and columns represent the pixel rows and pixel columns of the image. Since i basically mapped points from a HDF file, along with their corresponding pixel values. We basically have alot of empty pixels. Which are filled with 0. Now what i need to do is take the average of the surrounding cell's, to average out of a pixel value for the missing cell. Now i can brute force this but it becomes ugly fast. Is there any sort of elegant solution for this?
There's a well-known optimization to this filtering problem. Integrate the cells in one direction (say horizontally) Integrate the cells in the other direction (say vertically) Take the difference between each cell and it's N'th neighbor to the left. Take the difference between each cell and it's N'th lower neighbor Like this: for (i = 0; i < h; ++i) for (j = 0; j < w-1; ++j) A[i][j+1] += A[i][j]; for (i = 0; i < h-1; ++i) for (j = 0; j < w; ++j) A[i+1][j] += A[i][j] for (i = 0; i < h; ++i) for (j = 0; j < w-N; ++j) A[i][j] -= A[i][j+N]; for (i = 0; i < h-N; ++i) for (j = 0; j < w; ++j) A[i][j] -= A[i-N][j]; What this does is: The first pass makes each cell the sum of all of the cells on that row to it's left, including itself. After the 2nd pass , each cell is the sum of all of the cells in a rectangle above and left of itselt (including it's own row and column) After the 3rd pass, each cell is the sum of a rectangle above and to the right of itself, N columns wide. After the 4th pass each cell is the sum of an NxN rectangle below and to the right of itself. This takes 4 operations per cell to compute the sum, as opposed to 8 for brute force (assuming you're doing a 3x3 averaging filter). The cool thing is that if you use ordinary two's-complement arithmetic, you don't have to worry about any overflows in the first two passes; they cancel out in the last two passes.
1,667,420
1,667,477
How can I tell reliably if a boost thread has exited its run method?
I assumed joinable would indicate this, however, it does not seem to be the case. In a worker class, I was trying to indicate that it was still processing through a predicate: bool isRunning(){return thread_->joinable();} Wouldn't a thread that has exited not be joinable? What am I missing... what is the meaning of boost thread::joinable?
Since you can join a thread even after it has terminated, joinable() will still return true until you call join() or detach(). If you want to know if a thread is still running, you should be able to call timed_join with a wait time of 0. Note that this can result in a race condition since the thread may terminate right after the call.
1,667,591
4,140,600
Rotating a bitmap 90 degrees
I have a one 64-bit integer, which I need to rotate 90 degrees in 8 x 8 area (preferably with straight bit-manipulation). I cannot figure out any handy algorithm for that. For instance, this: // 0xD000000000000000 = 1101000000000000000000000000000000000000000000000000000000000000 1 1 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 after rotation becomes this: // 0x101000100000000 = 0000000100000001000000000000000100000000000000000000000000000000 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 I wonder if there's any solutions without need to use any pre-calculated hash-table(s)?
v = (v & 0x000000000f0f0f0fUL) << 004 | (v & 0x00000000f0f0f0f0UL) << 040 | (v & 0xf0f0f0f000000000UL) >> 004 | (v & 0x0f0f0f0f00000000UL) >> 040; v = (v & 0x0000333300003333UL) << 002 | (v & 0x0000cccc0000ccccUL) << 020 | (v & 0xcccc0000cccc0000UL) >> 002 | (v & 0x3333000033330000UL) >> 020; v = (v & 0x0055005500550055UL) << 001 | (v & 0x00aa00aa00aa00aaUL) << 010 | (v & 0xaa00aa00aa00aa00UL) >> 001 | (v & 0x5500550055005500UL) >> 010;
1,667,625
1,667,738
c++ vector random shuffle part of it
Whats the best way to shuffle a certain percentage of elements in a vector. Say I want 10% or 90% of the vector shuffled. Not necessarily the first 10% but just 10% across the board. TIA
Modify a Fisher-Yates shuffle to do nothing on 10% of the indices in the array. This is java code that I'm posting (from Wikipedia) and modifying, but I think you can make the translation to C++, because this is more of an algorithms problem than a language problem. public static void shuffleNinetyPercent(int[] array) { Random rng = new Random(); // java.util.Random. int n = array.length; // The number of items left to shuffle (loop invariant). while (n > 1) { n--; // n is now the last pertinent index if (rng.nextDouble() < 0.1) continue; //<-- ADD THIS LINE int k = rng.nextInt(n + 1); // 0 <= k <= n. // Simple swap of variables int tmp = array[k]; array[k] = array[n]; array[n] = tmp; } }
1,667,963
1,668,004
How portable is casting -1 to an unsigned type?
The other day, I came across this construct: static_cast<size_type>(-1) in some example C++ code, which is likely (depending on the details of where size_type is from) to be equivalent to the following C: (size_t)(-1) As I understand it, it works based on the fact that the representation of -1 in twos complement arithmetic is 11111...1, for as many bits as you have, so this is a quick way of getting the maximum value that an unsigned type like size_t can hold. However, my understanding is also that C doesn't guarantee that twos complement will be used; if the C implementation uses one's complement, this will be 1 less than the the maximum value, and if it's using signed magnitude, it will be just over half the maximum value. Is there some wrinkle that I'm missing that insures that this works right regardless of the representation of signed integers being used? Does it differ between C and C++ (many surprising things do)?
The requirements on unsigned arithmetic guarantee that casting -1 to an unsigned type will produce the largest number possible for the target type. C99, §6.2.5/9: "...a result that cannot be represented by the resulting unsigned integer type is reduced modulo the number that is one greater than the largest value that can be represented by the resulting type." This is the same in C and C++ (in the C++ standard, similar wording is found in footnote 41 -- it's not normative, but it's explaining other wording that is).
1,667,999
1,668,026
What is the most painless approach to insert an element in the middle of the std::vector
I want to be able to insert an element in the middle (or another location) in the vector without overwriting existing element. Say my vector has 3 6 9 10 and I want to insert 7 right after 6. How should it be done without causing issues? It's very infrequent operation so efficiency is not a problem here. Also, at this point, I cannot switch to another container ( for example: std::list) that are good for insertions in the middle. Will std::insert in vector do what I want? How? thanks
There is vector::insert for this operation. iterator insert( iterator _Where, const Type& _Val ); void insert( iterator _Where, size_type _Count, const Type& _Val );
1,668,023
1,668,734
Producing the fastest possible executable
I have a very large program which I have been compiling under visual studio (v6 then migrated to 2008). I need the executable to run as fast as possible. The program spends most of its time processing integers of various sizes and does very little IO. Obviously I will select maximum optimization, but it seems that there are a variety of things that can be done which don't come under the heading of optimization which do still affect the speed of the executable. For example selecting the __fastcall calling convention or setting structure member alignment to a large number. So my question is: Are there other compiler/linker options I should be using to make the program faster which are not controlled from the "optimization" page of the "properties" dialog. EDIT: I already make extensive use of profilers.
1) Reduce aliasing by using __restrict. 2) Help the compiler in common subexpression elimination / dead code elimination by using __pure. 3) An introduction to SSE/SIMD can be found here and here. The internet isn't exactly overflowing with articles about the topic, but there's enough. For a reference list of intrinsics, you can search MSDN for 'compiler intrinsics'. 4) For 'macro parallelization', you can try OpenMP. It's a compiler standard for easy task parallelization -- essentially, you tell the compiler using a handful of #pragmas that certain sections of the code are reentrant, and the compiler creates the threads for you automagically. 5) I second interjay's point that PGO can be pretty helpful. And unlike #3 and #4, it's almost effortless to add in.
1,668,088
1,668,111
Advance iterator for the std::vector std::advance VS operator +?
I found myself writing the following a lot: int location =2; vector<int> vec; vector<int>::iterator it=vec.begin(); /..../ std::advance(it, location); instead of it= it + 5; what is the Preferred/Recommended way ?
Adding will only work with random access iterators. std::advance will work with all sorts of iterators. As long as you're only dealing with iterators into vectors, it makes no real difference, but std::advance keeps your code more generic (e.g. you could substitute a list for the vector, and that part would still work). For those who care, the standard describes advance and distance as follows (§24.3.4/1): Since only random access iterators provide + and - operators, the library provides two function templates advance and distance. These function templates use + and - for random access iterators (and are, therefore, constant time for them); for input, forward and bidirectional iterators they use ++ to provide linear time implementations. Also note that starting with C++11, the standard added a parameter to std::next, so you can advance by a specified amount using it (and std::prev similarly). The difference from std::advance is that it returns the modified iterator (which std::advance doesn't), which can be convenient in some cases.
1,668,259
1,668,549
STL or Qt containers?
What are the pros and cons of using Qt containers (QMap, QVector, etc.) over their STL equivalent? I can see one reason to prefer Qt: Qt containers can be passed along to other parts of Qt. For example, they can be used to populate a QVariant and then a QSettings (with some limitation though, only QList and QMap/QHash whose keys are strings are accepted). Is there any other? Edit: Assuming the application already relies on Qt.
I started by using std::(w)string and the STL containers exclusively and converting to/from the Qt equivalents, but I have already switched to QString and I find that I'm using Qt's containers more and more. When it comes to strings, QString offers much more complete functionality compared to std::basic_string and it is completely Unicode aware. It also offers an efficient COW implementation, which I've come to rely on heavily. Qt's containers: offer the same COW implementation as in QString, which is extremely useful when it comes to using Qt's foreach macro (which does a copy) and when using meta-types or signals and slots. can use STL-style iterators or Java-style iterators are streamable with QDataStream are used extensively in Qt's API have a stable implementation across operating systems. A STL implementation must obey the C++ standard, but is otherwise free to do as it pleases (see the std::string COW controversy). Some STL implementations are especially bad. provide hashes, which are not available unless you use TR1 The QTL has a different philosophy from the STL, which is well summarized by J. Blanchette: "Whereas STL's containers are optimized for raw speed, Qt's container classes have been carefully designed to provide convenience, minimal memory usage, and minimal code expansion." The above link provides more details about the implementation of the QTL and what optimizations are used.
1,668,655
1,668,675
String Undeclared In C++
I'm sure this is a really simple thing, but I haven't worked in C++ forever. 14 C:\Dev-Cpp\mainCurl.cpp `string' undeclared (first use this function) > #include <stdio.h> > #include <curl/curl.h> > #include <string> > #include <iostream> > > int main(void) { > string url("http://www.google.com"); // > system("pause"); > > return 0; } What am I missing here? Cheers
You haven't declared your namespace. You need to either declare: using namespace std; Or tell the compiler that "string" is in the standard namespace: std::string url("..."); Or you can announce that you are specifically using std::string and only std::string from std by saying: using std::string;
1,669,017
1,670,008
How to create a MFC dialog with a progress bar in a separate thread?
My application may take a while to connect to a database. This connection is made with a single library function call, i.e. I cannot put progress updates in there and make callbacks or something similar. My idea was to create a dialog with a progress bar in a separate thread before connecting to the DB. This dialog will continually change the progress status with CProgressCtrl::StepIt() so the user sees something happening. After that dialog is set up and doing its thing I want to call the DB connection function from the main thread. After the connection function completed, I want to stop the progress bar thread. Let me paint a picture: CMyApp:: ProgressThread InitInstance() . | . | . +-Create Dialog-+ | | | Animate Connect Progress to Bar DB | | | +-Destroy Dlg---+ | . | . Is that possible? If yes, how? Maybe the whole thing would work using timers, too. Would probably be much simpler but I couldn't get that to work either. I am aware of CProgressCtrl::SetMarquee() which might do exactly what I need but I can't use it because the application does not have Unicode support. I could move the db connection call into a separate thread but that way it looks like a lot of changes to the code and extra handling of connection errors. Update 2 I got it working the way AlexEzh and Javier De Pedro suggested: Put the DB stuf into its own thread. initially I had concerns about how error handling could be done but it's actually quite similar to how it was before. In the main thread I create a struct with connection parameters, result flag and thread-running-flag. The latter is initially set to true. I create a thread and pass that struct as parameter. I create a dialog that displays a progress bar in the main thread. Also in the main thread there is a loop that runs while the thread-running-flag is set. It calls CMyDialog::Animate() which calls CProgressCtrl::StepIt() and then Sleep()s a bit. The thread executes the db-connection code and sets the running-flag to false when done. When the main thread exits the loop it can handle errors exactly as it did before. Disadvantage: Moving the mouse over the window doesn't work. It's invisible. Thus no cancel-button or other interactive dialog elements can be used. I can live with that, however. Since you liked the diagram, here is how it now looks like: CMyApp:: WorkerThread InitInstance() . | . | . Create Dialog . | . +-Start Thread--+ | | | Connect Animate to Progress DB Bar | | | +-Thread Ends---+ | . Destroy Dlg . | .
It would still be safer to move the DB connection logic to the separate thread. With DB on the dialog thread, you will be able to repaint the progress bar but not other controls in the dialog.
1,669,204
1,669,258
Need a vector that derives from a vector
Consider this simple code: class A { }; class V1: vector<A *>{ // my nice functions }; if I have a instance of V1, then any object derived from A can be inserted into the vector, ok here. Now, lets say I have two simple classes called B and C both derives from A; if I have a instance of V1, then both pointers of B and C can be inserted into this vector, I guess this is right to afirm? if so, how can I derive a vector from V1 to make sure only B pointers are inserted? I was thinking about using templates, but in this case I already know the base of the class and in tempaltes you can use anything, right? Don't know if I am being clear, my english doesn't help... Would I have to override push_back and other functions to check if the template argument is derived from A? Please, don't need to talk about boost or syntaxes I am using etc... I really just want to understand the concept of this... it is not clear in my mind yet. I have some answers to this but I guess they involve too much of casts to check stuff and I came here to know if there is a better answer to it... Thanks! Jonathan ps: Can you guys please answer comments I put? sometimes I ask stuff here and then the best answerers come and don't come back :(. Or should I just ask another question instead of comment questioning?
It's not clear from your example if inheritance is needed. You may also not realize it is dangerous, because std::vector does not have a virtual destructor. That means V1's destructor will not be called upon deletion of a pointer to the base class and you may end up leaking memory/resources. See here for more info. class A { }; class V1: vector<A *>{ // my nice functions }; if I have a instance of V1, then any object derived from A can be inserted into the vector, ok here. Yes, correct. Now, lets say I have two simple classes called B and C both derives from A; if I have a instance of V1, then both pointers of B and C can be inserted into this vector, I guess this is right to afirm? Yes, correct. if so, how can I derive a vector from V1 to make sure only B pointers are inserted? I was thinking about using templates, but in this case I already know the base of the class and in tempaltes you can use anything, right? Why not use a std::vector<B*> m_bVector; for this case? Here's how it would work: B* bInstance = new B(); A* aInstance = new A(); m_bVector.push_back(bInstance); m_bVector.push_back(aInstance); //< compiler error Maybe you have a good reason for inheriting from vector, but I don't see it right now... If you need added functionality, it may be better to have V1 wrap the std::vector, ie: class V1 { private: std::vector<A*> m_aVec; public: // use AVec }
1,669,390
1,669,434
Comparing variables in two instances of a class
i have what i hope is a quick question about some code i am building out.. basically i want to compare the variables amongst two instances of a class (goldfish) to see if one is inside the territory of another. they both have territory clases which in turn use a point clase made up of an x and y data-point. now i was curious to know why the below doesnt work please: (this bit of code compares two points: a & b, each with two points, a north-east (ne) and south-west (sw) and their x and y plots) if ((a->x_ne <= b->x_ne && a->y_ne <= b-> ne) && (a->x_sw => b->x_sw && a->y_sw => b-> sw)) { return true; } else return false; I can think of a work around (for instance, by having a get location method), and using a function in the main body to compare, but im curious to know --as a budding c++ programmer -- why the above, or a similar implementation doesnt appear to work. and also, what would be the CLEANEST and most elegant way to accomplish the above? have a friend function perhaps? many thanks edit: added some comments to (hopefully make the variables clearer) // class point { // public: // float x; // float y; // point(float x_in, float y_in) { //the 2 arg constructor // x = x_in; // y = y_in; // } // }; // class territory { // private: // point ne, sw; // public: // territory(float x_ne, float y_ne, float x_sw, float y_sw) // : ne(x_ne, y_ne), sw(x_sw,y_sw) { // } // bool contain_check(territory a, territory b) { // //checks if a is contained in b (in THAT order!) // if ((a->x_ne <= b->x_ne && a->y_ne <= b-> ne) && // (a->x_sw => b->x_sw && a->y_sw => b-> sw)) { // return true; // } else return false; ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ // }; // class goldfish { // protected: // float size; // point pos; // territory terr; // public: // goldfish(float x, float y) : pos(x,y), terr(x-1,y-1,x+1,y+1) { //constructor // size = 2.3; // } // void retreat() { //what happens in the case of loss in attack // /* // if(goldfish.size[1] - goldfish.size[2] <= 1 && goldfish.size[1] - goldfish.size[2] > 0) { // size = size - 0.2; // } // */ // } // void triumph() { // } // void attack() { // } // // void goldfish() // };
What do you mean by "doesnt work"? I does not compile? If contain_check is written as shown in your post, a problem is that you are using the arrow operator on non-pointers. Use dot instead: if ((a.x_ne <= b.x_ne && a.y_ne <= b.ne) //etc.
1,669,448
1,669,467
Unknown meta-character in C/C++ string literal?
I created a new project with the following code segment: char* strange = "(Strange??)"; cout << strange << endl; resulting in the following output: (Strange] Thus translating '??)' -> ']' Debugging it shows that my char* string literal is actually that value and it's not a stream translation. This is obviously not a meta-character sequence I've ever seen. Some sort of Unicode or wide char sequence perhaps? I don't think so however... I've tried disabling all related project settings to no avail. Anyone have an explanation? search : 'question mark, question mark, close brace' c c++ string literal
What you're seeing is called a trigraph. In written language by grown-ups, one question mark is sufficient for any situation. Don't use more than one at a time and you'll never see this again. GCC ignores trigraphs by default because hardly anyone uses them intentionally. Enable them with the -trigraph option, or tell the compiler to warning you about them with the -Wtrigraphs option. Visual C++ 2010 also disables them by default and offers /Zc:trigraphs to enable them. I can't find anything about ways to enable or disable them in prior versions.
1,669,501
1,669,565
code for subtracting 1 from a digit stored in an array using c
can any one help me with code that subtract 1 from a digit stored in an array using c++ (elementary mathematics) eg.. 100-1=99 and 98-1=97
If you have stored the digits in an array, you'll need to follow your elementary-school math on the array from right to left. "Borrow" from the next place to the left as needed.
1,669,514
1,669,550
Should I inherit from std::exception?
I've seen at least one reliable source (a C++ class I took) recommend that application-specific exception classes in C++ should inherit from std::exception. I'm not clear on the benefits of this approach. In C# the reasons for inheriting from ApplicationException are clear: you get a handful of useful methods, properties and constructors and just have to add or override what you need. With std::exception it seems that all you get is a what() method to override, which you could just as well create yourself. So what are the benefits, if any, of using std::exception as a base class for my application-specific exception class? Are there any good reasons not to inherit from std::exception?
The main benefit is that code using your classes doesn't have to know exact type of what you throw at it, but can just catch the std::exception. Edit: as Martin and others noted, you actually want to derive from one of the sub-classes of std::exception declared in <stdexcept> header.
1,669,788
1,670,045
How do I make tab control take over entire window in Qt Creator?
I want a tab control to "dock" to the entire window panel, in Qt Creator. Now in Winforms and WPF this is super easy but in Qt its not working. I've tried all the layouts, grid layouts, etc etc. it's just shrinking the tabs not making them grow to fill. So please test a solution before telling me what the SHOULD BE OBVIOUS answer is cause its not working. omg QQ this is driving me NUTS
I'm unsure what you are trying to achieve here - do you want the control to fill the client area? Are you creating a QMainWindow-derived class or a QDialog-derived one? If using QMainWindow then you'd make the tab control the central widget by calling setCentralWidget. The tab control will then fill the main window's client area. I have done this many times. Or do you want the tab 'ears' to stretch?
1,670,226
1,670,375
How do I stop automake from adding -I. to my compile line?
How do I stop automake from adding -I. to my compile line? It seems automake or libtool objects always have a compile command similar to: g++ -DHAVE_CONFIG_H -I. -I./proj/otherdir -o myprog.o myprog.c The problem is that I have two header files with the same name.... ./proj/otherdir/Header.h ./proj/thisdir/Header.h Each header has a class named Header, although each is in a different namespace. So when I am building in ./proj/thisdir, the "-I." gets included and I can't get to the header in ./proj/otherdir I don't know how to get rid of that initial "-I." that appears. Any hints? Thanks Chenz
all you have to do is set in the Makefile.am DEFAULT_INCLUDES = and then all is good in the world. Chenz
1,670,276
1,675,291
Tutorials for creating an ActiveX Control in Code::Blocks
I need to write an ActiveX control and have never written one before. I'd appreciate being pointed to some useful tutorials. I'm also wanting to implement it under Code::Blocks. Has anyone done this before? how easy is it? Note: I've found a number of tutorials, but they are either for visual basic, or visual c++ based. these tools do all the hard work for you. I need to implement it from scratch with Code::Blocks as I do not have those other tools available.
VLC has an ActiveX control made without the use of Visual C++ libraries. You can have a look at the git repository here
1,670,891
1,670,907
How can I print a string to the console at specific coordinates in C++?
I'm trying to print characters in the console at specified coordinates. Up to now I have been using the very ugly printf("\033[%d;%dH%s\n", 2, 2, "str"); But I just had to ask whether C++ had any other way of doing this. The problem is not even that it's ugly, the problem comes up when I try to make myself a prettier function like so: void printToCoordinates(int x, int y, string text) { printf("\033[%d;%dH%s\n", x, x, text); } It doesn't work, even if I typecast to (char*). Another problem is that I have to print out the \n for the page to be refreshed... I just don't enjoy using printf in general. Similarily to using cout instead of printf, I believe there should be a more recent way of doing this (ideally a way that allows me to easily write strings where I want on the screen, and ideally a way that doesn't required these weird symbols: \033[%d;%dH) So, do any of you have what I'm looking for?
What you are doing is using some very terminal specific magic characters in an otherwise pure C++ application. While this works, you will probably have a far easier time using a library which abstracts you from having to deal with terminal specific implementation details and provides functions that do what you need. Investigate whether curses or ncurses libraries are available for your system.
1,671,062
1,704,439
No thumbnails showing in Aero flip/thumbnail for full screen direct3d 9 application
I'm sure this is on the web somewhere, but I'm having trouble with the search terms (getting lots of non-relevant stuff.) Anyway, I've got a Direct3D9 application. When it runs in full screen, on Vista and Windows 7, and you hit Alt-Tab or Win-Tab, my application just shows up blank in the thumbnail/preview/live view (not sure of the correct term.) Is there an API or notification I can respond to where I can draw my backbuffer to the thumbnail?
When running a full-screen Direct3D application window compositing (of which the thumbnails are a part) is disabled. This is typically a good thing, since it can increase performance of the full-screen app. As a default this behavior is reasonable since most full-screen apps (especially those developed against XP or earlier) expect to be the sole focus of the user while the app is running. You can manually instantiate and update your thumbnail in this case if you wish, but alt-tabbing away from a full-screen app is usually and edge case. For more information about compositing in general, including overviews of the thumbnail APIs, check out this MSDN article
1,671,297
1,674,359
How do I invoke a non-default constructor for each inherited type from a type list?
I'm using a boost typelist to implement the policy pattern in the following manner. using namespace boost::mpl; template <typename PolicyTypeList = boost::mpl::vector<> > class Host : public inherit_linearly<PolicyTypeList, inherit<_1, _2> >::type { public: Host() : m_expensiveType(/* ... */) { } private: const ExpensiveType m_expensiveType; }; The Host class knows how to create an instance of ExpensiveType, which is a costly operation, and each policy class exposes functionality to use it. A policy class will always minimally have the constructor defined in the following sample policy. struct SamplePolicy { SamplePolicy(const ExpensiveType& expensiveType) : m_expensiveType(expensiveType) { } void DoSomething() { m_expensiveType.f(); // ... } private: const ExpensiveType& m_expensiveType; }; Is it possible to define the constructor of Host in such a way to call the constructor of each given policy? If the type list was not involved, this is very easy since the type of each policy is explicitly known. template <typename PolicyA, typename PolicyB> class Host : public PolicyA, public PolicyB { public: Host() : m_expensiveType(/* ... */), PolicyA(m_expensiveType), PolicyB(m_expensiveType) { } private: const ExpensiveType m_expensiveType; }; The boost::mpl::for_each algorithm looks promising, but I can't wrap my head around how to use it to solve this problem.
I could not resist the temptation to see how it could be done with inherit_linearly. Turns out to be not that bad, IMHO: template<class Base, class Self> struct PolicyWrapper : Base, Self { PolicyWrapper(const ExpensiveType& E) : Base(E), Self(E) {} }; struct EmptyWrapper { EmptyWrapper(const ExpensiveType& E) {} }; template <typename PolicyTypeList = boost::mpl::vector<> > class Host : public inherit_linearly< PolicyTypeList, PolicyWrapper<_1, _2>, EmptyWrapper >::type { typedef typename inherit_linearly< PolicyTypeList, PolicyWrapper<_1, _2>, EmptyWrapper >::type BaseType; public: Host() : BaseType(m_expensiveType) {} private: const ExpensiveType m_expensiveType; }; A warning though: Passing a reference to an uninitialized member like what is done in the Host ctor is very fragile. If, for example, one writes a Policy like this: struct BadPolicy { BadPolicy(const ExpensiveType& E) : m_expensiveType(E) {} ExpensiveType m_expensiveType; }; bad things will happen, as the copy ctor of ExpensiveType will be invoked with an uninitialized object.
1,671,469
1,671,581
Confusing Valgrind output: indirectly lost blocks but no errors?
I'm running valgrind 3.5.0 to try and squash memory leaks in my program. I invoke it as so: valgrind --tool=memcheck --leak-check=yes --show-reachable=yes After my program finishes valgrind reports that ==22926== ==22926== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 17 from 1) ==22926== malloc/free: in use at exit: 20,862 bytes in 425 blocks. ==22926== malloc/free: 25,361 allocs, 24,936 frees, 772,998 bytes allocated. ==22926== For counts of detected errors, rerun with: -v ==22926== searching for pointers to 425 not-freed blocks. ==22926== checked 91,884 bytes. Despite telling me that there are 0 errors I'm concerned that the number of allocations and frees do not match. More worrisome still is the following: ==22926== LEAK SUMMARY: ==22926== definitely lost: 68 bytes in 1 blocks. ==22926== indirectly lost: 20,794 bytes in 424 blocks. ==22926== possibly lost: 0 bytes in 0 blocks. ==22926== still reachable: 0 bytes in 0 blocks. ==22926== suppressed: 0 bytes in 0 blocks. There is additional output, pertaining to what appears to be a leak: ==22926== 20,862 (68 direct, 20,794 indirect) bytes in 1 blocks are definitely lost in loss record 9 of 17 ==22926== at 0x40269EE: operator new(unsigned int) (vg_replace_malloc.c:224) ==22926== by 0x807960B: OneTwoThree::OneTwoThree(Scenario const*) (onetwothree.cc:22) ==22926== by 0x804DD69: main (scsolver.cpp:654) At the line in question in the constructor of OneTwoThree I have the following: OneTwoThree::OneTwoThree (const Scenario* scenario) : Choice("123", scenario, new Solution (scenario->name(), scenario)), seen_(new bool [sol_->numVisits()]) { } later, in the destructor, seen_ is deleted as so: OneTwoThree::~OneTwoThree () { delete [] seen_; } There is no reallocation of memory associated with seen_; I only flip the bools to true/false during the course of running my program. I can't see a leak here and I don't understand what valgrind is trying to tell me. I've been reading through the valgrind manual (specifically, this) but I'm not being enlightened much. Can anyone help me grok this output?
The commenters to the OP were spot on; The Solution object being created in the constructor was never being deleted. I've fixed the egregious oversight and gotten rid of the ugly code creating new objects outside of the constructor of the object which is responsible for them. Thank you Artelius, Nikolai and Jonathan!
1,671,533
1,671,577
How to integrate an external process which is invoked repeatedly into a Java webapp?
I am trying to integrate a non-Java executable into a Java webapp on the server-side (Linux). Some details about the executable: Written in C++. The executable takes some input either from stdin or file and generates an output file. The executable is not designed to be a long running process i.e it generates an output and then dies out. While starting an individual process for the executable is fairly inexpensive, the number of calls made to it can be high. This can result in spawning too many processes which could degrade server performance. How can I write some wrapper or utility (in Java) around this exe, that I can run efficiently as either a thread from within my Java app a long-running external process PS: I know that I can start an external process using Runtime or ProcessBuilder in Java and could probably make it multi-threaded and use some queueing too, but that does not solve the issue of starting the process over and over again.
if you: a) Can modify the source code. I would recommend you yo create a long running process and expose it as a webservice. This way the process will only be sitting there waiting to be invoked. b) Have the source code/headers but you can't modify it. Probably a good idea would be to integrate it as library and invoke it from java, either with JNI or JNA, although this may be painfully hard. C) Don't have the source code or can't modify it. Then there are not much options, you have to create a thread queue and from there throttle the process creation.
1,671,586
1,671,703
How to create a Boost.Asio socket from a native socket?
I am merely trying to create a boost ip::tcp::socket from an existing native socket. In the assign function, the first parameter must be a "protocol_type" and the second must be a "native_type", but it never explains what these are or gives an example of its use. I'm guessing the second should be the socket descriptor, but I'd really appreciate clarification. void SendData (int socket, std::string message) { boost::asio::io_service ioserv; boost::asio::ip::tcp::socket s(ioserv); s.assign(/* what goes here? */, /* ..and here? */); s.send(boost::asio::buffer(message)); }
"Native type" is just the socket handle, in this case the int stored in "socket". "Protocol type" is the the protocol. For a TCP over standard IP using stream socket, this would be the return value from boost::asio::ip::tcp::v4(). Substitute as appropriate for datagram sockets, IPv6, etc. So: s.assign(boost::asio::ip::tcp::v4(), socket); Adjusted as appropriate for what you're trying to do.
1,671,641
1,672,723
Qt: New student to Qt questions
I've got a class I've written, and I'm trying to connect it to Qt. I've got some "best practices" questions I hope you all can help me with. When creating a mainWindow to contain data, I inherit the header file into my custom class specified above, so I can make use of the elements created within Qt Creator. Is this the proper way of doing things? I borrowed this idea from the second chapter of the official book Should I be making a NEW class that binds these together? Inside of the class itself should I be strictly encapsulating data, or making it friendly to like-classes? Does this help with accessability? Aside from the official book's chapter on MVC, and the on-line tutorial here, what are some other resources to a MVC newcomer in Qt? Thanks in advance
When creating a mainWindow to contain data, I inherit the header file into my custom class specified above, so I can make use of the elements created within Qt Creator. Is this the proper way of doing things? I assume that you mean "include the header file": when creating a widget with an associated .ui you should include the uic (created by Qt Creator in your case) generated header file in your widget class' header file, and then you have three options: Inherit from the uic generated class. Hold a pointer to said class in your class. Hold said class in a regular member variable. I prefer number 3 unless the ui class is really big because it means one less new allocation and results in less coupling. Inside of the class itself should I be strictly encapsulating data, or making it friendly to like-classes? Does this help with accessability? You should still apply OO design rules when using Qt. I generally hold the model inside the main window and pass other widgets whatever data they need as interfaces, containers, structs, delegates, etc. Sometimes I pass the entire model. Aside from the official book's chapter on MVC, and the on-line tutorial here, what are some other resources to a MVC newcomer in Qt? I have managed to successfuly use MV by reading the official book and using the Qt help together with the examples.
1,671,682
1,672,355
The reading list for scientific programmer
I am working to become a scientific programmer. I have enough background in Math and Stat but rather lacking on programming background. I found it very hard to learn how to use a language for scientific programming because most of the reference for SP are close to trivial. My work involves statistical/financial modelling and none with physics model. Currently, I use Python extensively with numpy and scipy. Done R/Mathematica. I know enough C/C++ to read code. No experience in Fortran. I dont know if this is a good list of language for a scientific programmer. If this is, what is a good reading list for learning the syntax and design pattern of these languages in scientific settings.
At some stage you're going to need floating point arithmetic. It's hard to do it well, less hard to do it competently, and easy to do it badly. This paper is a must read: What Every Computer Scientist Should Know About Floating-Point Arithmetic
1,671,728
1,671,731
C++ : cannot convert from 'char *' to 'char []' problem
im not a c/c+ programmer ( i do know delphi), anyway im trying to compile a program written in c++, i'v changed it to accept some arguments( a path to a file, which is hardcoded in the original code) from command line, the orignial line was char Filepath[50] = "F:\\mylib\\*.mp3"; and i changed it to char Filepath[50] = argv[1]; but i got "cannot convert from 'char *' to 'char []'" error, the main function is like int _tmain(int argc, TCHAR* argv[], TCHAR* envp[]) what should i do?? im using MSVC6. thanks
Use: char *Filepath = argv[1]; There's no need to allocate space for 50 characters when argv[1] already contains the string you want. Also, you don't have to decide what will be the maximum number of characters in the command line argument; that space is already allocated for you. Note, however, that the above will not make a copy of the string, so if you intend to modify the string (perhaps by appending an extension or anything), then you will have to use strcpy() or similar solution. Handling strings in C is a lot more manual character-copying work than it is in Delphi.
1,671,986
1,672,082
Which is faster, writing raw data to a drive, or writing to a file?
I need to write data into drive. I have two options: write raw sectors.(_write(handle, pBuffer, size);) write into a file (fwrite(pBuffer, size, count, pFile);) Which way is faster? I expected the raw sector writing function, _write, to be more efficient. However, my test result failed! fwrite is faster. _write costs longer time. I've pasted my snippet; maybe my code is wrong. Can you help me out? Either way is okay by me, but I think raw write is better, because it seems the data in the drive is encrypted at least.... #define SSD_SECTOR_SIZE 512 int g_pSddDevHandle = _open("\\\\.\\G:",_O_RDWR | _O_BINARY, _S_IREAD | _S_IWRITE); TIMER_START(); while (ulMovePointer < 1024 * 1024 * 1024) { _write(g_pSddDevHandle,szMemZero,SSD_SECTOR_SIZE); ulMovePointer += SSD_SECTOR_SIZE; } TIMER_END(); TIMER_PRINT(); FILE * file = fopen("f:\\test.tmp","a+"); TIMER_START(); while (ulMovePointer < 1024 * 1024 * 1024) { fwrite(szMemZero,SSD_SECTOR_SIZE,1,file); ulMovePointer += SSD_SECTOR_SIZE; } TIMER_END(); TIMER_PRINT();
In the _write() case, the value of SSD_SECTOR_SIZE matters. In the fwrite case, the size of each write will actually be BUFSIZ. To get a better comparison, make sure the underlying buffer sizes are the same. However, this is probably only part of the difference. In the fwrite case, you are measuring how fast you can get data into memory. You haven't flushed the stdio buffer to the operating system, and you haven't asked the operating system to flush its buffers to physical storage. To compare more accurately, you should call fflush() before stopping the timers. If you actually care about getting data onto the disk rather than just getting the data into the operating systems buffers, you should ensure that you call fsync()/FlushFileBuffers() before stopping the timer. Other obvious differences: The drives are different. I don't know how different. The semantics of a write to a device are different to the semantics of writes to a filesystem; the file system is allowed to delay writes to improve performance until explicitly told not to (eg. with a standard handle, a call to FlushFileBuffers()); writes directly to a device aren't necessarily optimised in that way. On the other hand, the file system must do extra I/O to manage metadata (block allocation, directory entries, etc.) I suspect that you're seeing a different in policy about how fast things actually get on to the disk. Raw disk performance can be very fast, but you need big writes and preferably multiple concurrent outstanding operations. You can also avoid buffer copying by using the right options when you open the handle.
1,672,172
1,672,300
Cannot set OdbcConnection to OdbcCommand.Connection
On the class level, I have created reference: System::Data::Odbc::OdbcConnection Connection; in some method I want to set it to odbcCommand.Connection like this: ::System::Data::Odbc::OdbcCommand Command; Command.Connection=this->Connection; It reports "cannot convert parameter 1 from 'System::Data::Odbc::OdbcConnection' to 'System::Data::Common::DbConnection ^'" I dont understand why it speaks about common::DbConnection if the Command.Connection expects OdBcConnection? Thank you
Command.Connection wants a handle (^) to a System::Data::Common::DbConnection public: property OdbcConnection^ Connection { OdbcConnection^ get (); void set (OdbcConnection^ value); } Instead try to do this: System::Data::Odbc::OdbcCommand Command; Command.Connection = %Connection; The unary % operator (Tracking reference) returns a CLI tracking references to a CLI object. Tracking references are valid to handles and value types. Response to comment: When you create a managed object this way: OdbcConnection Connection; It's a special type of C++/CLI object that are allocated on the stack and that points to the managed object on the managed heap. It isn't a valid managed reference object. To create a managed reference you need to do the following. OdbcConnection^ Connection; // In the class definition // In the class constructor do the following: Connection = gcnew OdbcConnection(); And DB connection should be deleted in the constructor to guarantee timely clean up. But it is not needed for managed object, they are delete automatically
1,672,419
1,672,896
Reading float value from string upto 6 precision
i have to read a flot value from string up to 6 precision , Current code is reading first 6 digits only. Thanks in Advance template <class T> bool from_string(T& t, const std::string& s, std::ios_base& (*f)(std::ios_base&)) { std::istringstream iss(s); return !(iss >> f >> t).fail(); } int main() { int i; float f; // the third parameter of from_string() should be // one of std::hex, std::dec or std::oct if(from_string<int>(i, std::string("ff"), std::hex)) { std::cout << i << std::endl; } else { std::cout << "from_string failed" << std::endl; } if(from_string<float>(f, std::string("1456.909"), std::dec)) { std::cout << f << std::endl; } else { std::cout << "from_string failed" << std::endl; } return 0; }
I'm quite certain it's reading all digits. The problem appears to be in what you expect. Let's put it a bit stronger: What would you expect to happen if you read 1456.90900000000000000000000000000 in a float?
1,672,550
1,672,654
How to implement server-sided applications that can process user's inputs?
There are some web-based services such as converting .flv files into .mp3 files, .doc files into .pdf files, etc. These are the servers that take files from the user and apply respected applications (such as conversion). After that, the converted file may be available to the requested user. I understand a little bit about writing a text and stores it into a server with javascript and php. What are the required tools and languages in order to achieve the above? Can some sort of C++ programs on the server side be invoked by some means? Or do I need completely different tools and methods? Please provide me some keywords for this as I do not know what to google for.
Well for PDFs this can be done using entirely PHP. See http://www.php.net/manual/en/book.pdf.php for the PDF functions and http://uk.php.net/manual/en/pdf.examples-basic.php for some examples of usage.
1,672,561
1,672,613
Getting a file path relative to a particular directory
Is there a nice way in the WinAPI to get a path relative to another path? For example: Have a list of paths relative to: a\b\c\d And I'd like to change them all to paths relative to a\b\c Is there a neat way to do this or should I get path parsing?
As far as i know there is no such functionality in the windows API, but there is e.g. an article on CodeGuru that provides that functionality. edit: I stand corrected, there is PathRelativePathTo() in the shell api as mentioned in this answer.
1,672,677
1,672,698
Print a GUID variable
I have a GUID variable and I want to write inside a text file its value. GUID definition is: typedef struct _GUID { // size is 16 DWORD Data1; WORD Data2; WORD Data3; BYTE Data4[8]; } GUID; But I want to write its value like: CA04046D-0000-0000-0000-504944564944 I observed that: Data1 holds the decimal value for CA04046D Data2 holds the decimal value for 0 Data3 holds the decimal value for next 0 But what about the others? I have to interpret myself this values in order to get that output or is there a more direct method to print such a variable?
Use the StringFromCLSID function to convert it to a string e.g.: GUID guid; CoCreateGuid(&guid); OLECHAR* guidString; StringFromCLSID(guid, &guidString); // use guidString... // ensure memory is freed ::CoTaskMemFree(guidString); Also see the MSDN definition of a GUID for a description of data4, which is an array containing the last 8 bytes of the GUID
1,672,730
1,672,738
How to get the value of a value passed by reference in C++
I have a function with the following declaration: void cleanValid(int valid[][4], int &size, int index); In implementation of this function I need to set another counter equal to the integer size passed by reference. I tried doing something like: int count; count = size; If I'm not mistaken, when I change the value of count it will change the value of size as well. I can't have this happen though. How would I go about copying the value of size into count and keeping them independent?
No, you've got it wrong. When you read from the reference into a non-reference variable, you're not setting up any kind of linkage between the two. You will have an independent copy of the value of size at that time, nothing else. If you wanted to affect the value of size, you would have to use a reference to it: int& count = size; /* ... */ count= 32; /* This will change size, too. */
1,673,183
1,673,234
C++ Unicode Encryption Library Required (Or is it?)
I need to encryption several pieces of text in a file along side unencrypted text in the same file. All the data is Unicode text. In all the encryption libraries I have looked at Crypto++ Botan Etc... None of them "appear" to provide Unicode aware methods for encrypting / decrypting data E.G. data can be passed in/out using char, string instead of wchar wstring. Does this matter? Just looking for some guidance.
Encryption libraries will use your data as a binary blob, not as characters. So it doesn't matter in what encoding the data is. Encoding only affects interpretation of the data, not the data itself. In other words: It doesn't matter
1,673,329
1,673,362
c++: pass function as parameter to another function
i am currently implementing a binary tree in c++ and i want to traverse it with a function called in_order(). is there any way to pass a function as an argument, so that i can do things like below (without having to write the code to traverse the list more than once)? struct tree_node; // and so on class tree; // and so on void print_node () { // some stuff here } // some other functions tree mytree(); // insert some nodes mytree.in_order(print_node); mytree.in_order(push_node_to_stack); mytree.in_order(something_else);
Yes, you can do this in a number of ways. Here are two common possibilities. Old-style function pointers class mytree { // typedef for a function pointer to act typedef void (*node_fn_ptr)(tree_node&); void in_order(node_fn_ptr) { tree_node* pNode; while (/* ... */) { // traverse... // ... lots of code // found node! (*fnptr)(*pNode); // equivalently: fnptr(*pNode) } } }; void MyFunc(tree_node& tn) { // ... } void sample(mytree& tree) { // called with a default constructed function: tree.inorder(&MyFunc); // equivalently: tree.inorder(MyFunc); } Using functors With a template member, works with function pointers class mytree { // typedef for a function pointer to act typedef void (*node_fn_ptr)(tree_node&); template<class F> void in_order(F f) { tree_node* pNode; while (/* ... */) { // traverse... // ... lots of code // found node! f(*pNode); } } }; struct ExampleFunctor { void operator()(tree_node& node) { // do something with node } } void sample(mytree& tree) { // called with a default constructed function: tree.inorder(ExampleFunctor()); }
1,673,445
1,673,536
How to Convert unsigned char* to std::string in C++?
I have unsigned char*, want to convert it to std::string. Can you please tell me the safest way to do this?
You just needed to cast the unsigned char into a char as the string class doesn't have a constructor that accepts unsigned char: unsigned char* uc; std::string s( reinterpret_cast< char const* >(uc) ) ; However, you will need to use the length argument in the constructor if your byte array contains nulls, as if you don't, only part of the array will end up in the string (the array up to the first null) size_t len; unsigned char* uc; std::string s( reinterpret_cast<char const*>(uc), len ) ;
1,673,764
1,673,879
freopen: reverting back to original stream
I needed to forward stdout to different files to separate some prints produced and the reverting back to normal stdout. I used freopen to switch to the file in this way: char name[80]; memset(name, 0, 80); strcpy(name, "./scripts/asm/"); strcat(name, m_func->m_name->m_value); strcat(name, ".shasm"); freopen(name, "w", stdout); And it actually works, but at the end of the process (mind that stdout is redirected many times in the previous same way) I'm not able to revert it to original stdout. I tried the following: freopen("/dev/stdout", "w", stdout); but it doesn't seem to work.. just for information I'm developing on macosx. What should I do? Thanks in advance
This can be achieved using fileno, dup and dup2 calls. I have tried this on linux not sure whether this will work on mac but I am sure you will get some equivalent functions for your setup. See if this sample code works for you. Sorry for lack of error-handling in the code. :) #include <stdio.h> main() { int fd; fpos_t pos; printf("stdout, "); fflush(stdout); fgetpos(stdout, &pos); fd = dup(fileno(stdout)); freopen("stdout.out", "w", stdout); f(); fflush(stdout); dup2(fd, fileno(stdout)); close(fd); clearerr(stdout); fsetpos(stdout, &pos); /* for C9X */ printf("stdout again\n"); } f() { printf("stdout in f()"); }
1,673,844
1,674,297
C/C++ compiler feedback optimization
Has anyone seen any real world numbers for different programs which are using the feedback optimization that C/C++ compilers offer to support the branch prediction, cache preloading functions etc. I searched for it and amazingly not even the popular interpreter development groups seem to have checked the effect. And increasing ruby,python,php etc. performance by 10% or so should be considered usefull. Is there really no benefit or is the whole developer community just to lazy to use it?
10% is a good ballpark figure. That said, ... You have to REALLY care about the performance to go this route. The product I work on (DB2) uses PGO and other invasive and agressive optimizations. Among the costs are significant build time (triple on some platforms) and development and support nightmares. When something goes wrong it can be non-trivial to map the fault location in the optimized code back to the source. Developers don't usually expect that functions in different modules can end up merged and inlined and this can have "interesting" effects. Problems with pointer aliasing, which are nasty to track down also usually show up with these sorts of optimizations. You have the additional fun of having non-deterministic builds (an aliasing problem can show up in monday's build, vanish again till thursday's, ...). The line between what is correct or incorrect compiler behaviour under these sorts of aggressive optimizations also becomes fairly blurred. Even with the luxury of having our compiler guys in house (literally) the optimization issues (either in our source or the compiler) are still not easy to understand and resolve.
1,673,931
1,674,007
How to enumerate network adapters and get their MAC addresses in Win32 API C++?
How do I enumerate network adapters and get their MAC addresses in Win32 API C++?
This code should work: { ULONG outBufLen = 0; DWORD dwRetVal = 0; IP_ADAPTER_INFO* pAdapterInfos = (IP_ADAPTER_INFO*) malloc(sizeof(IP_ADAPTER_INFO)); // retry up to 5 times, to get the adapter infos needed for( int i = 0; i < 5 && (dwRetVal == ERROR_BUFFER_OVERFLOW || dwRetVal == NO_ERROR); ++i ) { dwRetVal = GetAdaptersInfo(pAdapterInfos, &outBufLen); if( dwRetVal == NO_ERROR ) { break; } else if( dwRetVal == ERROR_BUFFER_OVERFLOW ) { free(pAdapterInfos); pAdapterInfos = (IP_ADAPTER_INFO*) malloc(outBufLen); } else { pAdapterInfos = 0; break; } } if( dwRetVal == NO_ERROR ) { IP_ADAPTER_INFO* pAdapterInfo = pAdapterInfos; while( pAdapterInfo ) { IP_ADDR_STRING* pIpAddress = &(pAdapterInfo->IpAddressList); while( pIpAddress != 0 ) { // // <<<< // here pAdapterInfo->Address should contain the MAC address // >>>> // pIpAddress = pIpAddress->Next; } pAdapterInfo = pAdapterInfo->Next; } } free(pAdapterInfos); return false; }
1,674,150
1,674,368
NULL definition problem on 64 bit system
I'm running on RHEL 5.1 64 bit platfrom using gcc 4.1.2. I have a utility function: void str_concat(char *buff, int buffSize, ...); which concats char * passed in variadic list(...), while last argument should be NULL, to designate end of the arguments. On 64 bit system NULL is 8 bytes. Now to the problem. My application includes directly/indirectly 2 stddef.h files. First one is /usr/include/linux/stddef.h which defines NULL as following: #undef NULL #if defined(__cplusplus) #define NULL 0 #else #define NULL ((void *)0) #endif The second one is /usr/lib/gcc/x86_64-redhat-linux/4.1.2/include/stddef.h #if defined (_STDDEF_H) || defined (__need_NULL) #undef NULL /* in case <stdio.h> has defined it. */ #ifdef __GNUG__ #define NULL __null #else /* G++ */ #ifndef __cplusplus #define NULL ((void *)0) #else /* C++ */ #define NULL 0 #endif /* C++ */ #endif /* G++ */ #endif /* NULL not defined and <stddef.h> or need NULL. */ #undef __need_NULL Of course I need the 2nd one, since it defines NULL as __null (8 bytes), while 1st one defines it as integer 0 (4 bytes). How do I prevent /usr/include/linux/stddef.h to be inderectly included? UPD: Compilation line is pretty straightforward: g++ -Wall -fmessage-length=0 -g -pthread Many of you advised to pass (void *)0. This of course will work. The problem that the function is used in many, I mean many places. I'd like to find solution that will give me what C++ standard promises - NULL of 8 byte size.
There's no "NULL definiton problem" in this case. There's a problem with how you are trying to use NULL in your code. NULL cannot be portably passed to variadic functions in C/C++ by itself. You have to explicitly cast it before passing, i.e. in your case you have to pass (const char*) NULL as the terminator of the argument list. Your question is tagged as C++. In any case, regardless of size, in C++ NULL will always be defined as an integer constant. It is illegal in C++ to define NULL as a pointer. Since your function expects a pointer (const char *), no definition of NULL will ever work for it in C++ code. For cleaner code you can define your own constant, like const char* const STR_TERM = NULL; and use it in the calls to your function. But you will never be able to meaningfully use just NULL for that purpose. Whenever a plain NULL is passed as a variadic argument, it is a blatant portability bug that has to be fixed. Added: your update claims that "C++ standard promises NULL of 8 byte size" (on a 64-bit platform I presume). This just doesn't make any sense. C++ standard does not promise anything like that about NULL. NULL is intended to be used as an rvalue. It has no specific size and there's no valid use of NULL where its actual size might even remotely matter. Quoting from ISO/IEC 14882:1998, section 18.1 'Types', paragraph 4: The macro NULL is an implementation defined C++ null pointer constant in this International Standard (4.10).180) 180) Possible definitions include 0 and 0L, but not (void*)0.
1,674,162
1,674,348
How to handle EINTR (interrupted System Call)
My user-space application sometimes blocks after receiving an EINTR-Signal, somehow. What I recorded with strace: time(NULL) = 1257343042 time(NULL) = 1257343042 rt_sigreturn(0xbff07be4) = -1 EINTR (Interrupted system call) --- SIGALRM (Alarm clock) @ 0 (0) --- time(NULL) = 1257343042 futex(0xb7cea80c, 0x80 /* FUTEX_??? */, 2) = ? ERESTARTSYS (To be restarted) --- SIGUSR1 (User defined signal 1) @ 0 (0) --- sigreturn() = ? (mask now [ALRM]) futex(0xb7cea80c, 0x80 /* FUTEX_??? */, 2) = ? ERESTARTSYS (To be restarted) --- SIGWINCH (Window changed) @ 0 (0) --- futex(0xb7cea80c, 0x80 /* FUTEX_??? */, 2) = ? ERESTARTSYS (To be restarted) --- SIGTERM (Terminated) @ 0 (0) --- time(NULL) = 1257343443 time(NULL) = 1257343443 futex(0xb7cea80c, 0x80 /* FUTEX_??? */, 2) = ? ERESTARTSYS (To be restarted) --- SIGWINCH (Window changed) @ 0 (0) --- futex(0xb7cea80c, 0x80 /* FUTEX_??? */, 2 Can I catch the EINTR signal and how can I repeat concerned calls such as write, read or select? How can I determine WHERE this EINTR occurred, even if I used third-party libraries working with system calls? Why my app is completely blocked after receiving an EINTR (see strace dump: I sent a SIGUSR1 which normally should be handled)? And why is futex() returning ERESTARTSYS to user space? thanks
The code which calls write (or other blocking operations) has to be aware of EINTR. If a signal occurs during a blocking operation, then the operation will either (a) return partial completion, or (b) return failure, do nothing, and set errno to EINTR. So, for an all-or-fail write operation which retries after interruptions, you'd do something like this: while(size > 0) { int written = write(filedes, buf, size); if (written == -1) { if (errno == EINTR) continue; return -1; } buf += written; size -= written; } return 0; // success Or for something a bit better behaved, which retries EINTR, writes as much as it can, and reports how much is written on failure (so the caller can decide whether and how to continue partial writes which fail for a reason other than interruption by signal): int total = 0; while(size > 0) { int written = write(filedes, buf, size); if (written == -1) { if (errno == EINTR) continue; return (total == 0) ? -1 : total; } buf += written; total += written; size -= written; } return total; // bytes written GNU has a non-standard TEMP_FAILURE_RETRY macro that might be of interest, although I can never find the docs for it when I want them. Including now.
1,674,284
1,674,442
How to produce hex output with boost::format?
Consider the following : #include <vector> #include <string> #include <iostream> #include <boost/format.hpp> #include <boost/assign.hpp> #include <boost/assign/list_of.hpp> #include <boost/assign/std/vector.hpp> using namespace std; typedef unsigned char byte; typedef vector<byte> byte_array; const byte_array bytes = list_of(0x05)(0x04)(0xAA)(0x0F)(0x0D); int main() { const string formatter = "%1%-%2%-%3%-%4%-%5%"; const string result = (format(formatter) % bytes[0] % bytes[1] % bytes[2] % bytes[3] % bytes[4] ).str(); cout << result << endl; return 0; } I'd like to see the result printed as : "05-04-AA-0F-0D" . What do I need to do to the formatter string to achieve that ?
Compiled and tested: #include <boost/format.hpp> #include <iostream> using namespace std; using namespace boost; int main() { unsigned int arr[5] = { 0x05, 0x04, 0xAA, 0x0F, 0x0D }; cout << format("%02X-%02X-%02X-%02X-%02X") % arr[0] % arr[1] % arr[2] % arr[3] % arr[4] << endl; }
1,674,445
1,674,456
Adding elements to an STL Map in a constructors Initialization List?
I was wondering if this was possible, and if so how I'd go about doing so. If it's not possible I'll just have to add the elements during the constructor body. Ideally I would like the map immutable after construction. What I'm trying to achieve is adding two pairs to the map that are created from constructor parameters.
It's possible, by copy construction: invoke a function which build the map! std::map<int,int> myFunc(int a, int b); class MyObject { public: MyObject(int a, int b): m_map(myFunc(a,b)) {} private: std::map<int,int> m_map; };
1,674,634
1,674,984
URI Escape C++ wstring
I am looking for a good way to do a URI Escape in C++ that would be reasonable for a cross platform project. I would like a function that would take a string like this: L"jiayou加油" And return: L"jiayou%E5%8A%A0%E6%B2%B9" I looked at using some thing like this, with minor modifacations to use wchar_t. However that would require converting from utf-16 to utf-8 before the printf call. This has lead me down character encoding hell. This and all the other approaches I have looked into just feel like the wrong way. Is there a good way to URI Escape a wstring in C++?
No matter what you do you're in some sort of character encoding hell (that's just the way it is with character encodings). From http://labs.apache.org/webarch/uri/rfc/rfc3986.html#characters: The URI syntax provides a method of encoding data, presumably for the sake of identifying a resource, as a sequence of characters. The URI characters are, in turn, frequently encoded as octets for transport or presentation. This specification does not mandate any particular character encoding for mapping between URI characters and the octets used to store or transmit those characters. When a URI appears in a protocol element, the character encoding is defined by that protocol; without such a definition, a URI is assumed to be in the same character encoding as the surrounding text. So, at some point you need to convert your URI to to the encoding that's appropriate to whatever you're sending the URI to. If that's UTF8 then you might as well do that conversion before you perform percent-encoding so you can use the library routine you've already found. If it's not UTF8 then you need to know what the recipient of the URI is expecting (again, that's the way it is with charset encodings - you have to know what the other guy is expecting, or be able to tell him) so you can percent-encode the characters in the character set encoding it's expecting.
1,674,864
1,674,876
How to synchronize and combine results from multiple threads in C++?
I have a data feed continuously feeding data packet in. There are 5 threads(A, B, C, D, E) processing the data packages. Note the 5 threads have totally different speed and they generate 5 different features(each thread generate 1 feature) for every incoming data package. The 5 threads are at different pace: when A has finished analyzing first 10 packages, B might only have finished package 1, package 2, and C might have not even finish a single package at all. My task is to match the results from 5 threads, and start the final analysis when all the 5 features for the first 10 data package are available. My question is: - How to combine the results from different threads making sure the analysis thread is only triggered when a certain amount of result are available? - I seems that I need a aggregator thread checking the availability of different buffers. I am thinking in terms of lock/condition. How could I implement such a condition involving different buffers? Totally newbie in multithreading. Any suggestion is welcomed. I am using GNU C++ with Boost library.
Have yourself an "aggregator" thread: this thread would get its input from the worker threads (through non-blocking thread-safe queues I suggest) and once a "batch" is ready, push it to your "analyzer" thread. Queues offer the advantage of not blocking any of the workers: the "aggregator" just has to poll the worker queues (through a condition section). You can control the rate of polling to your liking. This solution goes around the problem of "synchronize all" situations.
1,674,980
1,675,033
Who deletes the memory allocated during a "new" operation which has exception in constructor?
I really can't believe I couldn't find a clear answer to this... How do you free the memory allocated after a C++ class constructor throws an exception, in the case where it's initialised using the new operator. E.g.: class Blah { public: Blah() { throw "oops"; } }; void main() { Blah* b = NULL; try { b = new Blah(); } catch (...) { // What now? } } When I tried this out, b is NULL in the catch block (which makes sense). When debugging, I noticed that the conrol enters the memory allocation routine BEFORE it hits the constructor. This on the MSDN website seems to confirm this: When new is used to allocate memory for a C++ class object, the object's constructor is called after the memory is allocated. So, bearing in mind that the local variable b is never assigned (i.e. is NULL in the catch block) how do you delete the allocated memory? It would also be nice to get a cross platform answer on this. i.e., what does the C++ spec say? CLARIFICATION: I'm not talking about the case where the class has allocated memory itself in the c'tor and then throws. I appreciate that in those cases the d'tor won't be called. I'm talking about the memory used to allocate THE object (Blah in my case).
You should refer to the similar questions here and here. Basically if the constructor throws an exception you're safe that the memory of the object itself is freed again. Although, if other memory has been claimed during the constructor, you're on your own to have it freed before leaving the constructor with the exception. For your question WHO deletes the memory the answer is the code behind the new-operator (which is generated by the compiler). If it recognizes an exception leaving the constructor it has to call all the destructors of the classes members (as those have already been constructed successfully prior calling the constructor code) and free their memory (could be done recursively together with destructor-calling, most probably by calling a proper delete on them) as well as free the memory allocated for this class itself. Then it has to rethrow the catched exception from the constructor to the caller of new. Of course there may be more work which has to be done but I cannot pull out all the details from my head because they are up to each compiler's implementation.
1,675,021
1,675,045
Out of four std::vector objects select the one with the most elements
I have four std::vector containers that all might (or might not) contain elements. I want to determine which of them has the most elements and use it subsequently. I tried to create a std::map with their respective sizes as keys and references to those containers as values. Then I applied std::max on the size() of each vector to figure out the maximum and accessed it through the std::map. Obviously, this gets me into trouble once there is the same number of elements in at least two vectors. Can anyone think of a elegant solution ?
You're severely overthinking this. You've only got four vectors. You can determine the largest vector using 3 comparisons. Just do that: std::vector<blah>& max = vector1; if (max.size() < vector2.size()) max = vector2; if (max.size() < vector3.size()) max = vector3; if (max.size() < vector4.size()) max = vector4; EDIT: Now with pointers! EDIT (280Z28): Now with references! :) EDIT: The version with references won't work. Pavel Minaev explains it nicely in the comments: That's correct, the code use references. The first line, which declares max, doesn't cause a copy. However, all following lines do cause a copy, because when you write max = vectorN, if max is a reference, it doesn't cause the reference to refer to a different vector (a reference cannot be changed to refer to a different object once initialized). Instead, it is the same as max.operator=(vectorN), which simply causes vector1 to be cleared and replaced by elements contained in vectorN, copying them. The pointer version is likely your best bet: it's quick, low-cost, and simple. std::vector<blah> * max = &vector1; if (max->size() < vector2.size()) max = &vector2; if (max->size() < vector3.size()) max = &vector3; if (max->size() < vector4.size()) max = &vector4;
1,675,193
1,685,988
How to use array optimization in boost serialization
I have to serialize an object that contains a std::vector<unsigned char> that can contain thousand of members, with that vector sizes the serialization doesn't scale well. According with the documentation, Boost provides a wrapper class array that wraps the vector for optimizations but it generates the same xml output. Diving in boost code, i've found a class named use_array_optimization that seems to control the optimization but is somehow deactivated by default. i've also tried to override the serialize function with no results. I would like to know how to activate that optimizations since the documents at boost are unclear.
Finally, I used the BOOST_SERIALIZATION_SPLIT_MEMBER() macro and coded two functions for loading and saving. The Save function looks like: template<class Archive> void save(Archive & ar, const unsigned int version) const { using boost::serialization::make_nvp; std::string sdata; Vector2String(vData, sdata); ar & boost::serialization::make_nvp("vData", sdata); } The Vector2String function simply takes the data in vector and format it to a std::string. The load function uses a function that reverses the encoding.
1,675,508
1,675,538
Reading an std::ifstream to a vector of lines
How would I go about reading in a file where each line is a single number, then outputing that number into a vector of lines? eg: file.txt contains: 314 159 265 123 456 I have tried this implementation: vector<int> ifstream_lines(ifstream& fs) { vector<int> out; int temp; getline(fs,temp); while (!fs.eof()) { out.push_back(temp); getline(fs,temp); } fs.seekg(0,ios::beg); fs.clear(); return out; } but when I attempt to compile, I get errors such as: error C2784: 'std::basic_istream<_Elem,_Traits> &std::getline (std::basic_istream<_Elem,_Traits> &,std::basic_string<_Elem,_Traits,_Alloc> &)' : could not deduce template argument for 'std::basic_istream<_Elem,_Traits> &' from 'std::ifstream' so, obviously, something is wrong. Is there a more elegant solution than what I am trying? (Assuming 3rd party libraries like Boost are unavailable) Thanks!
I suspect you want something like this: #include <vector> #include <fstream> #include <iterator> std::vector<int> out; std::ifstream fs("file.txt"); std::copy( std::istream_iterator<int>(fs), std::istream_iterator<int>(), std::back_inserter(out));
1,675,735
1,718,322
High-performance Math library for .NET /C# and Java
We currently have a high-performance scientific application written in C++ that makes use of Intel Math Kernel Library. We are considering writing a benchmark application written in Java and .NET/C# to compare the performance difference. To do that, we also need a good (commercial is preferred) math library for both. Does anyone know of any math equivalent library for Java/C#? As a sidenote: C++ has Intel TBB library to help with multithreading. Does .NET/C# and Java have something equivalent?
Lol..why didnt I think of this before? Just use Intel MKL Math library in Java and .NET! See the following links: Using MKL in Java app How to use MKL with Java Using MKL in C# MKL 10.2 update MKL in depth
1,675,992
1,678,807
How do I set a background color for the whole window of a Qt application?
Does anyone know how one would be able to set a background color for the whole window of a Qt application? So far I am using stylesheets but can only figure out how to assign a background color to a widget such as QGroupBox or QPushButton. Basically, if I want a black background how would I make it seamless without any borders of the original background?
I would simply use a Style Sheet for the whole window. For instance, if your window is inheriting from QWidget, here is what I'm doing : MainWindow::MainWindow(QWidget *parent) : QWidget(parent), ui(new Ui::MainWindow) { ui->setupUi(this); this->setStyleSheet("background-color: black;"); } On my Mac, my whole application window is black (except the title bar). EDIT : according to comment, here is a solution without using ui files and loading an external style sheet #include <QtGui/QApplication> #include <QtGui/QMainWindow> #include <QtGui/QVBoxLayout> #include <QtGui/QPushButton> #include <QtCore/QFile> int main(int ArgC, char* ArgV[]) { QApplication MyApp(ArgC, ArgV); QMainWindow* pWindow = new QMainWindow; QVBoxLayout* pLayout = new QVBoxLayout(pWindow); pWindow->setLayout(pLayout); QPushButton* pButton = new QPushButton("Test", pWindow); pLayout->addWidget(pButton); QFile file(":/qss/default.qss"); file.open(QFile::ReadOnly); QString styleSheet = QLatin1String(file.readAll()); qApp->setStyleSheet(styleSheet); pWindow->setVisible(true); MyApp.exec(); } The style sheet file (default.qss) is as follow : QWidget { background-color: black; } This file is part of a resource file (stylesheet.qrc) : <RCC> <qresource prefix="/qss"> <file>default.qss</file> </qresource> </RCC> And here is my project file : TARGET = StyleSheet TEMPLATE = app SOURCES += main.cpp RESOURCES += stylesheet.qrc
1,676,385
1,676,414
C++ Data Member Alignment and Array Packing
During a code review I've come across some code that defines a simple structure as follows: class foo { unsigned char a; unsigned char b; unsigned char c; } Elsewhere, an array of these objects is defined: foo listOfFoos[SOME_NUM]; Later, the structures are raw-copied into a buffer: memcpy(pBuff,listOfFoos,3*SOME_NUM); This code relies on the assumptions that: a.) The size of foo is 3, and no padding is applied, and b.) An array of these objects is packed with no padding between them. I've tried it with GNU on two platforms (RedHat 64b, Solaris 9), and it worked on both. Are the assumptions above valid? If not, under what conditions (e.g. change in OS/compiler) might they fail?
An array of objects is required to be contiguous, so there's never padding between the objects, though padding can be added to the end of an object (producing nearly the same effect). Given that you're working with char's, the assumptions are probably right more often than not, but the C++ standard certainly doesn't guarantee it. A different compiler, or even just a change in the flags passed to your current compiler could result in padding being inserted between the elements of the struct or following the last element of the struct, or both.
1,677,070
1,677,193
Cross-Platform equivalent to windows events
I'm trying to port some Windows code to Linux, ideally through platform-independent libraries (eg boost), however I'm not sure how to port this bit of event code. The bit of code involves two threads (lets call them A and B). A wants to do something that only B can, so it sends B a message, then waits for B to say its done. In windows this looks something like: void foo();//thread a calls this void bar(HANDLE evt); void foo() { HANDLE evt = CreateEvent(0,FALSE,FALSE,0); bCall(boost::bind(&bar, evt)); WaitForSingleObject(evt,INFINITE); CloseHandle(evt); } void bar(HANDLE evt) { doSomething(); SetEvent(evt); } I looked at the boost::thread library, but it didnt seem to have anything that does this, the closes I could see was the boost::condition_variable, but it appears that is means in conjunction with a mutex, which is not the case here.
I think a good, cross-platform equivalent to win32 events is boost::condition, so your code could look something like this: void foo() { boost::mutex mtxWait; boost::condition cndSignal; bCall(boost::bind(&bar, mtxWait, cndSignal)); boost::mutex::scoped_lock mtxWaitLock(mtxWait); cndSignal.wait(mtxWait); // you could also use cndSignal.timed_wait() here } void bar(boost::mutex& mtxWait, boost::condition& cndSignal) { doSomething(); cndSignal.notify_one(); }
1,677,211
1,677,302
sort using boost::bind
bool pred(int k, int l, int num1, int num2) { return (num1 < num2); } int main() { vector <int> nums; for (int i=50; i > 0; --i) { nums.push_back(i); } std::sort (nums.begin(), nums.end(), boost::bind(&pred, 5, 45)); } I am a boost newbie. I was learning to use boost::bind and I wanted to sort a vector of integers and get rid of all those elements in the vector that are greater than 45 and less than 5. Had a hard time doing it. Would be great if anyone could help me do it? The reason I am facing problem is because I am trying to get rid of a vector element while iterating through the vector to sort it. I know it would be much easier if i sort it first and then remove elements from it. But I want to do it this way. Any help is appreciated.
You can't do that from sort. Remove the elements before or after sort. bool outOfRange(int low, int high, int num) { return low > num || num > high; } ... nums.erase( std::remove_if(nums.begin(), nums.end(), boost::bind(&outOfRange, 5, 45, _1)), nums.end() ); Though you really don't need boost::bind at all. Heck, we can make it a bit more generic too: template<typename T, class cmp = std::less<T> > struct outOfRange : std::unary_function<T, bool> { outOfRange(const T &low, const T &high) : low(low), high(high) {} bool operator()(const T &val) { return cmp()(val, low) || cmp()(high, val); } const T &low, &high; } ... nums.erase( std::erase_if(nums.begin(), nums.end(), outOfRange<int>(5, 45)), nums.end() );
1,677,345
1,683,136
How can I tell that a directory is the Recycling bin in VB6?
I am attempting to port the code in this article to VB6, but I'm experiencing crashing. I'm pretty sure my error is in my call to SHBindToParent (MSDN entry) since SHParseDisplayName is returning 0 (S_OK) and ppidl is being set. I admit my mechanism of setting the riid (I used an equivalent type, a UUID) is pretty ugly, but I think it more likely I'm doing something wrong with psf. Private Declare Function SHParseDisplayName Lib "shell32" (ByVal pszName As Long, ByVal IBindCtx As Long, ByRef ppidl As ITEMIDLIST, sfgaoIn As Long, sfgaoOut As Long) As Long Private Declare Function SHBindToParent Lib "shell32" (ByVal ppidl As Long, ByRef shellguid As UUID, ByVal psf As Long, ByVal ppidlLast As Long) As Long Private Sub Main() Dim hr As Long Dim ppidl As ITEMIDLIST Dim topo As String Dim psf As IShellFolder Dim pidlChild As ITEMIDLIST topo = "c:\tmp\" '"//This VB comment is here to make SO's rendering look nicer. Dim iid_shellfolder As UUID iid_shellfolder.Data1 = 136422 iid_shellfolder.Data2 = 0 iid_shellfolder.Data3 = 0 iid_shellfolder.Data4(0) = 192 iid_shellfolder.Data4(7) = 70 hr = SHParseDisplayName(StrPtr(topo), 0, ppidl, 0, 0) Debug.Print hr, Hex(hr) hr = SHBindToParent(VarPtr(ppidl), iid_shellfolder, VarPtr(psf), VarPtr(pidlChild)) 'Crashes here End Sub
I believe your call to SHBindToParent is crashing because you need to pass longs, then use the returned pointers to copy the memory into your types. I found several posts when I googled the SHBindToParent function that mentioned OS support, mostly 95 and 98. When I tried it on XP SP3 I got an error "No such interface supported." Here is how I modified your code to get past the GPF: Option Explicit Private Declare Function SHParseDisplayName Lib "shell32" (ByVal pszName As Long, ByVal IBindCtx As Long, ByRef ppidl As Long, ByVal sfgaoIn As Long, ByRef sfgaoOut As Long) As Long Private Declare Function SHBindToParent Lib "shell32" (ByVal ppidl As Any, ByRef shellguid As UUID, ByRef psf As Any, ByRef ppidlLast As Any) As Long Private Type SHITEMID cb As Long abID As Byte End Type Private Type ITEMIDLIST mkid As SHITEMID End Type Private Type UUID Data1 As Long Data2 As Integer Data3 As Integer Data4(7) As Byte End Type Private Sub Command1_Click() Dim hr As Long Dim ppidl As Long Dim topo As String Dim psf As IShellFolder Dim pidlChild As Long Dim iid_shellfolder As UUID Dim lpIDList2 As Long topo = "C:\Temp" ' create a uuid = {B7534046-3ECB-4C18-BE4E-64CD4CB7D6AC}' iid_shellfolder.Data1 = &HB7534046 iid_shellfolder.Data2 = &H3ECB iid_shellfolder.Data3 = &H4C18 iid_shellfolder.Data4(0) = 190 iid_shellfolder.Data4(1) = 78 iid_shellfolder.Data4(2) = 100 iid_shellfolder.Data4(3) = 205 iid_shellfolder.Data4(4) = 76 iid_shellfolder.Data4(5) = 183 iid_shellfolder.Data4(6) = 214 iid_shellfolder.Data4(7) = 172 hr = SHParseDisplayName(StrPtr(topo), ByVal 0&, lpIDList2, ByVal 0&, ByVal 0&) ' Debug.Print hr, Hex(hr)' hr = SHBindToParent(lpIDList2, iid_shellfolder, psf, pidlChild) 'retuns "No such interface supported" error End Sub
1,677,585
1,907,366
Pruning a static library in c++
I am trying to expose a single well defined class by building a static library and then shipping the built library with a few header files that define that class and the interfaces needed to use it. I have that working but the problem I am running into is the library is gigantic. It has every single object file from the whole project and all I need is a subset. If I make a simple main.cpp file and include and use that single class then I get a output file that is only as big as the 20% of the library I am using. Is there a way to tell the linker to start from a given place and prune everything else like in the executable case? EDIT: I forgot to mention that I am using gcc on cygwin and linux (though I would like a solution that worked with visual studio as well, we generally use that for development but deploy primarily on linux)
Make a shared library. It behaves like an executable from the point of view of linking etc. It should do the discarding you mentioned you saw on the executable.
1,677,635
1,677,648
Getting back into Windows programming
I've been out of the Microsoft stack for a while now, been focused on Linux, open source stuff and web development in PHP. I used to do some desktop app development and some DirectX stuff on Windows in Dev Studio (all C and C++). I'd like to brush up on the MS stuff just to keep up on what's going on. I've installed MSVC++ 2008 Express but I'm looking for a little side-project to play with. Given my background in C/C++ and familiarity with MFC and STL, what would be a good way to jump back in?
I've been developing on Microsoft stack since 1997, starting with C/C++/MFC/ATL, but all of the recent projects were on .NET platform (C#), so I would recommend learning .NET/C#. C/C++ still has its place, but it loses relevance rather rapidly. If not for legacy projects, we would not even bother with C/C++. Just my 2 cents.
1,677,693
1,682,233
Crash in msvcp90d.dll when retrieving an iterator from a boost::tokenizer
When I retrieve the begin() iterator of a boost::tokenizer, I get a crash in msvcp90d.dll, that says "ITERATOR LIST CORRUPTED", which looks suspiciously like issues I have run into before with the _HAS_ITERATOR_DEBUGGING compiler flag, however I have verified that my program is being compiled with this flag turned off. Here is the program: #include <sstream> #include <boost/tokenizer.hpp> #include <boost/algorithm/string.hpp> int main(int argc, char* argv[]) { std::string data("gobo;wimbley;red;moki;boober"); std::ostringstream input; input << data; std::string mystr(input.str()); boost::char_separator<char> separator(";"); boost::tokenizer<boost::char_separator<char>> tok(mystr, separator); boost::tokenizer<boost::char_separator<char>>::iterator iter = tok.begin(); } Interestingly, if I replace the instantiation of the tokenizer with the following line, it works: boost::tokenizer<boost::char_separator<char>> tok(data, separator); So it appears to be something related to the ostringstream. Any ideas?
There is a bug in Visual C++ with std::ostringstream when _HAS_ITERATOR_DEBUGGING is disabled. If I recall correctly, the std::string copy constructor copies iterators. You can get around this by using the std::string conversion constructor taking a char* instead. If you change std::string mystr(input.str()); to std::string mystr(input.str().c_str()); then no exception is thrown.
1,677,725
1,677,819
Class design ideas for state machine like object
I'm writing a state machine like object. Looks like Class A: vector<Actions> m_enter_actions; vector<Actions> m_exit_actions; public: ClassA.... ~ClassA SetEnterActions(vector<Actions> vector) SetExitActions(vector<Actions> vector) Is this the best way to handle this? I wonder if I should have like Class A: EnterActions m_exit_actions; ExitActions m_exit_actions; public: ClassA.... ~ClassA SetEnterActions(EnterActions& actions) SetExitActions(ExitActions& actions) The EnterActions class would be a container with it's own vector of actions. That way the ClassA class doesn't need to manage raw vectors. Any help is appreciated. I'm pretty bad at class design. Learning though :)
The signatures of the SetEnterActions and SetExitActions functions should be designed to prevent the caller from knowing how ClassA stores the Actions. Users of ClassA don't want to know whether ClassA stores them in a vector, or a deque, or a list, or in an EnterActions class, or whatever. They certainly don't want to have to package them up into whatever container ClassA stores them in. My first inclination would be to allow the caller to provide an iterator, and also to allow the caller to add them one at a time with a function call: template <typename InputIterator> AddEnterActions(InputIterator first, InputIterator last); AddEnterAction(const Action &action); So, if the caller has them in a vector he calls AddEnterActions(vec.begin(), vec.end());. If he has them in an array, he calls AddEnterActions(arr, arr+size);. If he has some unusual means of generating them, he doesn't have to mess around putting them into a container and then adding them all at once, and he doesn't have to write an iterator class to generate them. He can just add them as he figures out what they are. Meanwhile, if ClassA stores actions in a vector, then the implementation is just: template <typename InputIterator> AddEnterActions(InputIterator first, InputIterator last) { m_enter_actions.insert(m_enter_actions.end(), first, last); } AddEnterAction(const Action &action) { m_enter_actions.push_back(action); } If ClassA later wants to store them in something else, then you don't need to change any client code. Where possible design the interface first, based on what callers want. Then worry about the implementation. You sometimes then have to go back and tweak the interface, when you discover that it's unimplementable or it demands that the class does something horribly inefficient. But usually not.
1,677,914
1,677,921
C++ Object, Member's Memory Position Offset
Is there a better method to establish the positional offset of an object's data member than the following? class object { int a; char b; int c; }; object * o = new object(); int offset = (unsigned char *)&(object->c) - (unsigned char *)o; delete o;
In this case, your class is POD, so you can use the offsetof macro from <cstddef>. In practice, in most implementations, for most classes, you can use the same trick which offsetof typically uses: int offset = &(((object *)0)->c) - (object *)0; No need to actually create an object, although you may have to fight off some compiler warnings because this is not guaranteed to work. Beware also that if your class has any multiple inheritance, then for (at least) all but one base, (void*)(base*)some_object != (void*)(derived*)some_object. So you have to be careful what you apply the offset to. As long as you calculate and apply it relative to a pointer to the class that actually defines the field (that is, don't try to work out the offset of a base class field from a derived class pointer) you'll almost certainly be fine. There are no guarantees about object layout, but most implementations do it the obvious way. Technically for any non-POD class, it does not make sense to talk about "the offset" of a field from the base pointer. The difference between the pointers is not required to be the same for all objects of that class.
1,678,044
1,678,080
Datastructure alignment
So, I'm coding some packet structures (Ethernet, IP, etc) and noticed that some of them are followed by attribute((packed)) which prevents the gcc compiler from attempting to add padding to them. This makes sense, because these structures are supposed to go onto the wire. But then, I counted the words: struct ether_header { u_int8_t ether_dhost[ETH_ALEN]; /* destination eth addr */ u_int8_t ether_shost[ETH_ALEN]; /* source ether addr */ u_int16_t ether_type; /* packet type ID field */ } __attribute__ ((packed)); This is copied from a site, but my code also uses 2 uint8_t and 1 uint16_t. This adds up to two words (4 bytes). Depending on the source, the system prefers that structures be aligned according to multiples of 4,8, or even 16 bits. So, I don't see why the attribute((packed)) is necessary, as afaik this shouldn't get packed. Also, why the double brackets ((packed)) why not use one pair?
If your structure is already a multiple of the right size, then no, the __attribute__((packed)) isn't strictly necessary, but it's still a good idea, in case your structure size ever changes for any reason. If you add/delete fields, or change ETH_ALEN, you'll still want __attribute__((packed)). I believe the double parentheses are needed to make it easy to make your code compatible with non-gcc compilers. By using them, you can then just do this: #define __attribute__(x) And then all attributes that you specify will disappear. The extra parentheses mean there is only one argument passed to the macro (instead of one or more), regardless of how many attributes you specify, and your compiler does not need to support variadic macros.
1,678,347
1,678,392
How to read a word into a string ignoring a certain character
I am reading a text file which contains a word with a punctuation mark on it and I would like to read this word into a string without the punctuation marks. For example, a word may be " Hello, " I would like the string to get " Hello " (without the comma). How can I do that in C++ using ifstream libraries only. Can I use the ignore function to ignore the last character? Thank you in advance.
If you only want to ignore , then you can use getline. const int MAX_LEN = 128; ifstream file("data.txt"); char buffer[MAX_LEN]; while(file.getline(buffer,MAX_LEN,',')) { cout<<buffer; } EDIT: This uses std::string and does away with MAX_LEN ifstream file("data.txt"); string string_buffer; while(getline(file,string_buffer,',')) { cout<<string_buffer; }
1,678,394
1,678,403
debugging a thread process using gdb/dbx
This might be genuine question but i am asking here since i was out of any clue when i was asked this question in an interview. how could we debug a thread which was created by another thread? let's say there is a main process and it calles the function pthread_create to create a thread process which is not joinable and that means both teh main process and the newly created thread process will be eecuting their own tasks and if we start debugging the program how could we navigate to the thread that was created?. thanks in advance.
You can attach gdb to the whole process, then use gdb's thread ops to navigate between threads. It might help to print the thread id when pthread_create'ing the thread you want to debug.
1,678,653
1,679,836
Boost spirit and forward declarations issues
Could someone please give me some advice/ideas about how to deal with the situations when it's needed to have a look at further declarations to be able to make correct semantic actions on current moment? For example, it is a well-known occurrence when someone writes an interpreter/compiler of some programming language which doesn't support "forward declarations". Let's have an example: foo(123);//<-- our parser targets here. we estimate we have a function // invocation, but we have no idea about foo declaration/prototype, // so we can't be sure that "foo" takes one integer argument. void foo(int i){ //... } It is pretty clear we have to have at least two passes. Firstly we parse all function declarations and get all the needed information such as: the amount arguments the function takes, their types and then we are able to deal with function invocations and resolving the difficulties as above. If we go this way we will must do all these passes using some AST traversing mechanisms/visitors. In this case we have to deal with AST traversing/applying visitors and we must say "good bye" to the all the beauty of phoenix constructions integrated directly in our parsers. How would you deal with this?
[2nd answer, on semantics] This particular example happens to be simple. What you can do is record function calls made to yet undeclared functions, and the actual argument types. When you do encounter a function declaration later, you check if there are preceding function calls that are (better) matched to this new function. You will obviously detect errors only at the end of the parse, becuase the very last line could introduce a missing function. But after that line, any function call that hasn't been matched at all is an error. Now, the problem is that this works for simple semantics. If you look at more complex languages - e.g. with C++-like function templates - it no longer becomes possible to do such lookups in a simple table. You would need specialized tabes that structurally match your language constructs. An AST just isn't the best structure for those, let alone the partial AST during parsing.
1,678,830
1,682,392
How can I autoexpand an item in a QTreeView when it is filtered by QSortFilterProxyModel?
I have a normal QTreeView, a custom QAbstractItemModel and a custom QSortFilterProxyModel. I've reimplemented QSortFilterProxyModel::filterAcceptsRow to filter items from my model in the way I want, however now I want those filtered items to be expanded in the treeview. The obvious solution was to emit a signal from QSortFilterProxyModel::filterAcceptsRow() when an accepted item was found, then connect that signal to the QTreeView::expand(). However, QSortFilterProxyModel::filterAcceptsRow() is const, so I cannot emit a signal from inside that method. QSortFilterProxyModel doesn't have any other signals that would aid me.. and I am beginning to think I will have to subclass QTreeView, which I'd rather not do (less code == better). So, is there any way to autoexpand those items that the filtermodel accepts?
QTreeView has a "expandAll" slot, which could be called after you set the model. I would think that this should do what you want.
1,678,857
1,678,986
C++ STL for_each should take pointer to member function taking one argument
I have to pass the address of a member fn taking one argument to the std::for_each. how do i do this? class A{ void load() { vector<int> vt(10,20); std::for_each(vt.begin(), vt.end(), &A::print); //It didnt work when i tried mem_fun1(&A::print) } void print(int a) { cout<<a; } }; Thanks
When using std::mem_fun, you have to pass pointer to class as first argument. You can bind it in this case with std::bind1st. class A { public: void print(int v) {std::cout << v;} void load() { std::vector<int> vt(10, 20); std::for_each(vt.begin(), vt.end(), std::bind1st(std::mem_fun(&A::print), this)); } }
1,678,924
1,678,997
PopFront Delimma C++
Strange programming problems as of now..As you can see below i have assigned intFrontPtr to point to the first cell in the array. And intBackPtr to point to the last cell in the array...: bool quack::popFront( int &popFront ) { //items[count-1].n = { 9,4,3,2,1,0 }; nPopFront = items[0].n; if ( count >= maxSize ) return false; else { items[0].n = nPopFront; intFrontPtr = &items[0].n; intBackPtr = &items[count-1].n; } for (int temp; intFrontPtr < intBackPtr ;) { intFrontPtr++; temp = *intFrontPtr; *intFrontPtr = temp; } --count; return true; } Its just my implementation of a cross between a queue and a stack..PopFront is a public method of the class object quack..The items is a private struct type 'item', it is within the quack.h. It has one member, 'int n'..But, that is irrelevent. the comment in the code is the contents of my integer array, 'items'. I am trying to Pop elements off the front of my array. WHat im thinking is that after i get the first item, i'll just incrememnt the frontPtr and transfer the item i got previously to the frontPtr i incremented!... I cannot, for any reason, use a + or - shift by 1 or the use of stls, boosts, std's and the like.. Can someone help me with my homework assignment?
My suggestion are : 1). Put statement --count where it keeps object's state valid on exceptional condition. 2). clear your concepts of pointers which will help you a lot.
1,679,515
1,679,586
libxml2 error handling
I'm writing a small wrapper around libxml2 in C++, and I'm trying to work out how to handle errors. For now, let's say I just want to print them out. Here's what I've got at present: My error handling function: void foo(void *ctx, const char *msg, ...) { cout << msg << endl; return; } Initialised like this: xmlGenericErrorFunc handler = (xmlGenericErrorFunc)foo; initGenericErrorDefaultFunc(&handler); However, if I parse a bad XPath, I get this output: %s Without the error handling code, I get this: XPath error : Invalid expression //.@foobar ^ Obviously eventually my error handling will do more than just print out the error message (it'll log it to a database or something), but for now - how can I get that error string?
The three dots at the end of the argument list for you function foo() means it takes a variable amount of arguments. To be able to print those you could do something like this (not tested): #include <stdarg.h> #define TMP_BUF_SIZE 256 void foo(void *ctx, const char *msg, ...) { char string[TMP_BUF_SIZE]; va_list arg_ptr; va_start(arg_ptr, msg); vsnprintf(string, TMP_BUF_SIZE, msg, arg_ptr); va_end(arg_ptr); cout << string << endl; return; }
1,679,669
1,679,708
Data-structure that stores unique elements but answers queries for another ordering in C++
is there a data structure, which stores its elements uniquely (for a given compare-Functor) but answers queries for the highest element in that data structure with respect to another compare-Function ? For Example: I have a class with two properties : 1) the size 2) the value I'd like to have a data structure which stores all elements uniquely regarding its size but answers queries for the element with the highest value. Using std::set with a compare functor for the sizes gives me uniqueness but queries for the highest value will have linear runtime... Is there a better way? (I'll 'add elements then ask for the highest value' and keep iterating this until a certain termination point is reached) Any information would be appreciated (papers etc)
Boost::MultiIndex comes to mind.
1,679,768
1,679,969
Finding neighbor positions in matrix
I'v been bored so I created a small console minesweeper game and while writting it I had to find the neighbor positions of an element in a size*size matrix which is represented as an vector of elements and one variable which holds the size value. I didn't want to return the actual values of the neighbor elements but their positions so that I could use that as a public function (otherwise the client could see where the mines are at :P). For example for field eq 0 and size eq 3 the function should return {1, 3, 4}: 1 0 0 0 1 0 0 0 0 => 1 1 0 0 0 0 0 0 0 Well, basicaly it looks like this: vector<int> adjecantPositions(int field, int size) { int row = field / size; int col = field % size; vector<int> result; /* 1 0 0 1 0 0 1 0 0 */ if (col > 0) { result.push_back(calcField(row, col-1, size)); if (row > 0) result.push_back(calcField(row-1, col-1, size)); if (row < size - 1) result.push_back(calcField(row+1, col-1, size)); } /* 0 0 1 0 0 1 0 0 1 */ if (col < size - 1) { result.push_back(calcField(row, col+1, size)); if (row > 0) result.push_back(calcField(row-1, col+1, size)); if (row < size - 1) result.push_back(calcField(row+1, col+1, size)); } /* 0 1 0 0 0 0 0 1 0 */ if (row > 0) result.push_back(calcField(row-1, col, size)); if (row < size - 1) result.push_back(calcField(row+1, col, size)); return result; } calcField(int, int, int) is just converting coordinates into field number (row*size + col). This is a fast solution but it's not elegant and I bet there's some better way to do this. Any ideas?
Yeah, your code is awful. Here's a better attempt (fixed, sorry): for (int dx=-1; dx<=1; dx++) for (int dy=-1; dy<=1; dy++) if (dx || dy){ int x = row+dx, y=col+dy; if (x >= 0 && x < size && y >= 0 && y < size) result.push_back(calcField(x, y, size)); }
1,679,770
1,679,901
C++ Virtual function implementation?
If I have in C++: class A { private: virtual int myfunction(void) {return 1;} } class B: public A { private: virtual int myfunction(void) {return 2;} } Then if I remove virtual from the myfunction definition in class B, does that mean that if I had a class C based on class B, that I couldn't override the myfunction since it would be statically compiled? Also, I'm confused as to what happens when you switch around public, and private here. If I change the definition of myfunction in class B to be public (and the one in class A remains private), is this some sort of grave error that I shouldn't do? I think that virtual functions need to keep the same type so that's illegal, but please let know if that's wrong. Thanks!
The first definition with 'virtual' is the one that matters. That function from base is from then on virtual when derived from, which means you don't need 'virtual' for reimplemented virtual function calls. If a function signature in a base class is not virtual, but virtual in the derived classes, then the base class does not have polymorphic behaviour. class Base { public: void func(void){ printf("foo\n"); } }; class Derived1 : public Base { public: virtual void func(){ printf("bar\n"); } }; class Derived2 : public Derived1 { public: /* reimplement func(), no need for 'virtual' keyword because Derived1::func is already virtual */ void func(){ printf("baz\n"); } }; int main() { Base* b = new Derived1; Derived1* d = new Derived2; b->func(); //prints foo - not polymorphic d->func(); //prints baz - polymorphic }
1,679,858
1,679,972
Do interfaces solve DDD with code duplication?
AccountController can't extend BaseAccount and BaseController at the same time. If I make all BaseAccount or BaseController methods empty, I can have an interface, but if I implement that interface in two different places, that is, I make a contract to implement a method in two different places, I will have duplicated code. Do interfaces solve DDD with code duplication? interface A { function doStuff() { } } class B implements A { function doStuff() { // a code } } class C implements A { function doStuff() { // the same code!!! } }
Little bit confused with your last sentance, but if you want multiple inheritance then you need to do this: AccountController extends BaseAccount, and BaseAccount extends BaseController BaseController | BaseAccount | AccountController Using this method will enable you to access all member functions of BaseAccount and BaseController from AccountController using $this.
1,679,974
1,680,905
Converting an FFT to a spectogram
I have an audio file and I am iterating through the file and taking 512 samples at each step and then passing them through an FFT. I have the data out as a block 514 floats long (Using IPP's ippsFFTFwd_RToCCS_32f_I) with real and imaginary components interleaved. My problem is what do I do with these complex numbers once i have them? At the moment I'm doing for each value const float realValue = buffer[(y * 2) + 0]; const float imagValue = buffer[(y * 2) + 1]; const float value = sqrt( (realValue * realValue) + (imagValue * imagValue) ); This gives something slightly usable but I'd rather some way of getting the values out in the range 0 to 1. The problem with he above is that the peaks end up coming back as around 9 or more. This means things get viciously saturated and then there are other parts of the spectrogram that barely shows up despite the fact that they appear to be quite strong when I run the audio through audition's spectrogram. I fully admit I'm not 100% sure what the data returned by the FFT is (Other than that it represents the frequency values of the 512 sample long block I'm passing in). Especially my understanding is lacking on what exactly the compex number represents. Any advice and help would be much appreciated! Edit: Just to clarify. My big problem is that the FFT values returned are meaningless without some idea of what the scale is. Can someone point me towards working out that scale? Edit2: I get really nice looking results by doing the following: size_t count2 = 0; size_t max2 = kFFTSize + 2; while( count2 < max2 ) { const float realValue = buffer[(count2) + 0]; const float imagValue = buffer[(count2) + 1]; const float value = (log10f( sqrtf( (realValue * realValue) + (imagValue * imagValue) ) * rcpVerticalZoom ) + 1.0f) * 0.5f; buffer[count2 >> 1] = value; count2 += 2; } To my eye this even looks better than most other spectrogram implementations I have looked at. Is there anything MAJORLY wrong with what I'm doing?
The usual thing to do to get all of an FFT visible is to take the logarithm of the magnitude. So, the position of the output buffer tells you what frequency was detected. The magnitude (L2 norm) of the complex number tells you how strong the detected frequency was, and the phase (arctangent) gives you information that is a lot more important in image space than audio space. Because the FFT is discrete, the frequencies run from 0 to the nyquist frequency. In images, the first term (DC) is usually the largest, and so a good candidate for use in normalization if that is your aim. I don't know if that is also true for audio (I doubt it)
1,680,100
1,700,184
MFC without document/view architecture
I'd like some help on using MFC without the document/view architecture. I created a project without doc/view support, Visual C++ created a CFrameWnd and a view that inherits from CWnd. I replaced the view inheriting from CWnd with a new view that inherits from CFormView. However, when I run my program, after I close the window I get a heap corruption error.
The problem is MFC's lifecycle management. The view declaration (created by Visual C++ wizard) is: CChildView m_wndView; I replaced the above code with: CChildFormView m_wndView; CChildView inherits from CWnd, CChildFormView inherits from CFormView. Both views were created by the wizard, but only CChildFormView uses the DECLARE_DYNCREATE/IMPLEMENT_DYNCREATE macros. Since m_wndView is being created in the stack, when MFC automagically calls delete I get the error.
1,680,161
1,682,356
how can I fix xcode compiling everything all the time?
I've started to use XCode and it seems to work, well, most of it. The annoying thing is it compiles all the source files, even those that didn't change, each and every time. I'm getting the grips with openframeworks and I waste time compiling the openframeworks source files every time although they don't change. Here are my IDE and machine details: XCode Version 3.1.2 Component versions Xcode IDE: 1149.0 Xcode Core: 1148.0 ToolSupport: 1102.0 Mac OS X Version 10.5.6 Has any one experienced the same problem ? Any workarounds ?
Many (most?) build systems use the last-modified date and time of the files to determine whether a recompilation needs to be performed. I would first verify that the file dates are behaving as expected; if the files are on a network drive, for example, there could be different time settings or clock discrepancies that would make it appear that the files were modified in the future, so the build system always compiles them. For that matter, if they are on a network drive, the protocol used may not include modified date, and the system simply defaults it to "now," so it always looks like every file was just modified.
1,680,249
1,681,171
How to use SQLite in a multi-threaded application?
I'm developing an application with SQLite as the database, and am having a little trouble understanding how to go about using it in multiple threads (none of the other Stack Overflow questions really helped me, unfortunately). My use case: The database has one table, let's call it "A", which has different groups of rows (based on one of their columns). I have the "main thread" of the application which reads the contents from table A. In addition, I decide, once in a while, to update a certain group of rows. To do this, I want to spawn a new thread, delete all the rows of the group, and re-insert them (that's the only way to do it in the context of my app). This might happen to different groups at the same time, so I might have 2+ threads trying to update the database. I'm using different transactions from each thread, I.E. at the start of every thread's update cycle, I have a begin. In fact, what each thread actually does is call "BEGIN", delete from the database all the rows it needs to "update", and inserts them again with the new values (this is the way it must be done in the context of my application). Now, I'm trying to understand how I go about implementing this. I've tried reading around (other answers on Stack Overflow, the SQLite site) but I haven't found all the answers. Here are some things I'm wondering about: Do I need to call "open" and create a new sqlite structure from each thread? Do I need to add any special code for all of this, or is it enough to spawn different threads, update the rows, and that's fine (since I'm using different transactions)? I saw something talking about the different lock types there are, and the fact that I might receive "SQLite busy" from calling certain APIs, but honestly I didn't see any reference that completely explained when I need to take all this into account. Do I need to? If anyone can answer the questions/point me in the direction of a good resource, I'd be very grateful. UPDATE 1: From all that I've read so far, it seems like you can't have two threads who are going to write to a database file anyway. See: http://www.sqlite.org/lockingv3.html. In section 3.0: A RESERVED lock means that the process is planning on writing to the database file at some point in the future but that it is currently just reading from the file. Only a single RESERVED lock may be active at one time, though multiple SHARED locks can coexist with a single RESERVED lock. Does this mean that I may as well only spawn off a single thread to update a group of rows each time? I.e., have some kind of poller thread which decides that I need to update some of the rows, and then creates a new thread to do it, but never more than one at a time? Since it looks like any other thread I create will just get SQLITE_BUSY until the first thread finishes, anyway. Have I understood things correctly? BTW, thanks for the answers so far, they've helped a lot.
Check out this link. The easiest way is to do the locking yourself, and to avoid sharing the connection between threads. Another good resource can be found here, and it concludes with: Make sure you're compiling SQLite with -DTHREADSAFE=1. Make sure that each thread opens the database file and keeps its own sqlite structure. Make sure you handle the likely possibility that one or more threads collide when they access the db file at the same time: handle SQLITE_BUSY appropriately. Make sure you enclose within transactions the commands that modify the database file, like INSERT, UPDATE, DELETE, and others.
1,680,411
1,680,490
Atomic Operation C++
In C++, Windows platform, I want to execute a set of function calls as atomic so that execution doesn't switches to other threads in my process. How do I go about doing that? Any ideas, hints? EDIT: I have a piece of code like: someObject->Restart(); WaitForSingleObject(handle, INFINITE); Now the Restart() function does its work asynchronously, so it returns quickly and when that someObject is restarted it sends me an event from another thread where I signal the event handle on which I'm waiting and thus continue processing. But now the problem is that before the code reaches WaitForSingleObject() part, I receive the restart completion event and I signal the event and after that WaitForSingleObject() never returns since it is not signaled again. That's why I want to execute both Restart() and WaitForSingleObject() as atomic.
This is generally not possible. You can't force the OS to not switch to other threads. What you can do is one of the following: Use locks, mutexes, criticals sections or semaphores to synchronize a handful of threads that touch the same data. Use basic operations that are atomic such as compare-and-exchange or atomic-add in the form of win32 api calls such as InterlockedIncrement() and InterlockedCompareExchange()
1,680,538
1,680,599
C++ Separate Compilers for classes (vtables)?
I was wondering what the consequences are for compiling a class A with one compiler that doesn't allow multiple inheritance, and compiling a class B that does support it (and class B derived from class A). I don't really understand the linking process...would it be possible to use both together? What disadvantages exist for using separate compilers in this situation, with vtables? Would it be impossible for code using class B to function properly? Thanks.
As a general rule, don't ever compile parts of your C++ program with different compilers. Different compilers may use, and often do, different mangling schemas for the symbol mangling stage, so it's very unlikely that the linking between separately compiled stuff will work. See doc about mangling name_mangling
1,680,880
1,680,976
C++ array with value semantics and no allocator shenanigans?
I'm looking for a C++ container that's a cross between boost::array, boost::scoped_array and std::vector. I want an array that's dynamically allocated via new[] (no custom allocators), contained in a type that has a meaningful copy-constructor. boost::array is fixed-size, and although I don't need to resize anything, I don't know the size of the array at compile time. boost::scoped_array doesn't have a copy constructor, and that means that I need to manually add one to each and every class using std::copy (my previous copy-paste intensive solution). This is also error prone, since you better make sure when you add a field that you added the correct initializer to the custom copy constructor; i.e. loads of boilerplate. std::vector uses some pre-allocation system, and thus does not use operator new[]. This is problematic since it requires custom allocators, and worse, even that's not quite enough since there are some odd corner cases (which I don't fully understand) where return-by-value semantics are concerned that cause problems; I don't want the container to do anything fancy but simply contain a new[]'d array and copy it in it's copy constructor - and preferably overload all the usual suspects to be usable as a collection. I don't need to resize anything, but the size must be controllable at runtime. Basically, a variant of scoped_array that happens to have a sane copy-constructor (for instance via std::copy) would be fine. Is there a standard collection for something like this? Basically, I'm looking for a bog-standard dynamically allocated array with value semantics.
Inherit privately from std::vector, and then adjust appropriately. For example remove resize(), and perhaps add setsize() and a bool flag to determine if the size has been set. Your copy constructor can invoke the std::vector copy constructor, and set the flag automatically to prevent further changes.
1,680,920
1,727,559
Setting the version number in an NCBI c++ toolkit app
How can I set the version number in a NCBI C++ Toolkit Application? I mean the version number which is displayed when I start my program with the parameter -version. I read through the docs, but have not found it yet. (I know this is a highly specific question, but I figured it was worth a try)
Give it a void Init(void) method containing code along the following lines: // the last two parameters are optional CVersionInfo version_info(1, 2, 3, "My App"); SetVersion(version_info); However, this is currently broken (bug already submitted), so the workaround is to give the application class a constructor and call SetVersion from there.
1,680,971
1,681,127
Patterns for making c++ code easy to test
Should you design your code to make testing easier? And if so how to design c++ code so that it is easy to test. How do you apply dependency-injection in c++? Should I implement the classes using a pure interface class as the base in order to simplify the creation of fake test objects? That would force me into making a lot of virtual methods. Will that affect performance? What else should I think about when designing for testability in c++?
Should I implement the classes using a pure interface class as the base in order to simplify the creation of fake test objects? That would force me into making a lot of virtual methods. Will that affect performance? A workaround I often use is to templatize the class instead of hiding it behind an interface. Then I can pass test/mock objects as template parameters when testing, and the real objects otherwise. That way, the performance hit of virtual functions is avoided. Edit Ok, a simple example: With OOP and interfaces, you might write a function such as this: void Foo(IBar& someBar) { ... } This function takes a parameter which implements the IBar interface, and does something with it. If you want to pass in a dummy mock implementation, you simply write a mock object which inherits from IBar and pass that to Foo. Simple and straightforward. But you can achieve the same thing with templates: template <typename BarType> void Foo(BarType& someBar) { ... } ... and that's it. The body of Foo can be pretty much unchanged. As long as the type passed to the function exposes all the members we need, it'll work, without having to formally inherit from an interface class, and without the overhead of virtual functions and runtime polymorphism.
1,680,980
1,681,471
istream get method behavior
I read istream::get and a doubt still hangs. Let's say my delimiter is actually the NULL '\0' character, what happens in this case? From what I read: If the delimiting character is found, it is not extracted from the input sequence and remains as the next character to be extracted. Use getline if you want this character to be extracted (and discarded). The ending null character that signals the end of a c-string is automatically appended at the end of the content stored in s. The reason I would prefer "get" over "readline" is because of the capability to extract the character stream into a "streambuf".
If you have something like this, then delimiter will not get stuck in the input stream: std::string read_str(std::istream & in) { const int size = 1024; char pBuffer[size]; in.getline(pBuffer, size, '\0'); return std::string(pBuffer); } just an example if you have '\0' as delimiter and strings are not bigger than 1024 bytes.
1,681,145
1,681,186
How to initialize a shared library on Linux
I am developing a shared library using C++ under Linux, and I would like this library to use log4cxx for logging purposes. However, I'm not sure how to set this up. For log4cxx to work, I need to create a logger object. How can I make sure this object is created when my library is loaded? I suspect that it will be easiest to create the logger object as a global variable and then use it from any of the source files of my library, declaring it as extern in the headers. But how can I have the logger created automatically once an application connects to the library? I know that in DLLs for Windows, there's a thing as REASON_FOR_CALL == PROCESS_ATTACH; is there a similar thing under Linux?
In C++ under Linux, global variables will get constructed automatically as soon as the library is loaded. So that's probably the easiest way to go. If you need an arbitrary function to be called when the library is loaded, use the constructor attribute for GCC: __attribute__((constructor)) void foo(void) { printf("library loaded!\n"); } Constructor functions get called by the dynamic linker when a library is loaded. This is actually how C++ global initialization is implemented.
1,681,264
1,681,268
How do I create a native application using Visual C++ 2008?
I am getting started in C++. How can I setup Visual Studio 2008 to create native (not managed) code?
Choose a Win32 Project.
1,681,327
1,691,703
is DISPID_VALUE reliable for invokes on IDispatchs from scripts?
Continuing from this question, i am confused whether DISPID_VALUE on IDispatch::Invoke() for script functions and properties (JavaScript in my case) can be considered standard and reliable for invoking the actual function that is represented by the IDispatch? If yes, is that mentioned anywhere in MSDN? Please note that the question is about if that behaviour can be expected, not what some interfaces i can't know in advance might look like. A simple use case would be: // usage in JavaScript myObject.attachEvent("TestEvent", function() { alert("rhubarb"); }); // handler in ActiveX, MyObject::attachEvent(), C++ incomingDispatch->Invoke(DISPID_VALUE, IID_NULL, LOCALE_SYSTEM_DEFAULT, DISPATCH_METHOD, par, res, ex, err); edit: tried to clarify the question.
It should be reliable for invokes on objects from scripts if the script defines it consistently. This should be the case for JScript/Javascript in MSHTML, but unfortunately there is really sparse documentation on the subject, I don't have any solid proof in-hand. In my own experience, a Javascript function passed to attachEvent() should always be consistent- an object received that is a 'function' can only have one callable method that matches itself. Hence the default method is the only one you can find, with DISPID 0. Javascript functions don't ordinarily have member functions, although i'm sure there is a way for this to be possible. If it did have member functions, you would see them the same way as member functions on objects. Member functions in JScript will always be consistent with regard to IDispatchEx, according to the rules of expando functions, as any functions added to an object count as expandos. IDispatchEx interface @ MSDN
1,681,337
1,681,433
Inheriting friendship in C++?
Since class friendship is not inherited in C++, what's the best way to "fake" it? I was thinking about exposing the friend class's private interface through protected methods in the to-be-inherited base-class, but that results in having to write (and maintain) the same interface twice. Are there any other ways?
The use of a key is a possible solution. The idea is that you can unlock the operations only if you have a key... but an example is worth thousands on word so let's dive: // Step 1: The key class NeedAccess; namespace details { class Key { friend NeedAccess; Key() {} }; } // Step 2: NeedAccess class NeedAccess { protected: static details::Key GetKey() { return details::Key(); } }; // Step 3: The big one class BigOne { public: void lockedMethod(details::Key); }; The matter of key being copy constructable is up to discussion. I don't see what you can gain by preventing it. Another benefit is that you can have several keys, depending on which method you want to access, this way you grant 'partial' friendship, and your 'partial' friends can't mess around with your private parts, despite the famous claim! EDIT: This method is called Limited Friendship, and was discussed on comp.lang.c++.moderated. The main advantage of this method in comparison to Private Interface, is the loose coupling, since only forward declarations are necessary.
1,681,429
1,682,183
How to stop a running thread safely on user request?
I'm in a scenario when I have to terminate a thread while the thread is running according to user action on GUI. I'm using Qt 4.5.2 on Windows. One way to do that is the following: class MyThread : public QThread { QMutex mutex; bool stop; public: MyThread() : stop(false) {} void requestStop() { QMutexLocker(&mutex); stop = true; } void run() { while(counter1--) { QMutexLocker(&mutex); if (stop) return; while(counter2--) { } } } }; Please note that the above code is minimal. The run function can take upto 20 seconds before finish so I want to avoid locking and unlocking the mutex variable in the loop. Is there any other way faster than this method. Thanks in advance.
Firstly it doesn't look like you need a mutex around your entire inner loop, just around the if (stop) expression as the others say, but I may be missing some of your app context to definitively say that. Maybe you need requestStop() to block until the thread exits. If the reduced mutex scope is adequate for you, then you don't need a mutex at all if you declare your stop variable as "volatile". The "volatile" keyword causes (at least under VC++) a read/write memory barrier to be placed around accesses to stop, which means your requestStop() call is guaranteed to be communicated to your thread and not cached away. The following code should work just fine on multicore processors. class MyThread : public QThread { volatile bool stop; public: MyThread() : stop(false) {} void requestStop() { stop = true; } void run() { while(counter1--) { if (stop) return; while(counter2--) { } } } };
1,681,459
1,682,393
Boost::typeof compiler problem: mangling typeof, use decltype instead
short example: #include <boost/typeof/typeof.hpp> #include <boost/proto/core.hpp> using namespace boost; template<class T, class U> BOOST_TYPEOF_TPL(T() + U()) add2(const T& t, const U& u) { return t + u; }; int main(){ typedef BOOST_TYPEOF(add2(2.5, 1.5)) type; // get type -> works BOOST_STATIC_ASSERT((is_same<type, double>::value)); // check if double -> no error -> double double xxx = add2(1.5,1.5); // cause the problems return 0; } When i try to compile this i become a error like: g++-4.3: sorry, unimplemented: mangling typeof, use decltype instead g++-4.2: internal compiler error: in write_type, at cp/mangle.c:1648 Please submit a full bug report, with preprocessed source if appropriate. See <URL:http://gcc.gnu.org/bugs.html> for instructions. For Debian GNU/Linux specific bug reporting instructions, see <URL:file:///usr/share/doc/gcc-4.2/README.Bugs>. gcc version 4.3.2 (Debian 4.3.2-1.1) gcc version 4.2.4 (Debian 4.2.4-6) Where is the Problem or what i do wrong?a
The example in the typeof documentation first wraps the result of the BOOST_TYPEOF_TPL macro in a templated struct, then uses that when declaring the function. Does that work any better for you? template<class T, class U> struct result_of_add2 { typedef BOOST_TYPEOF_TPL(T() + U()) type; }; template<class T, class U> typename result_of_add2<T, U>::type add2(const T& t, const U& u) { return t + u; };