question_id
int64
25
74.7M
answer_id
int64
332
74.7M
title
stringlengths
20
150
question
stringlengths
23
4.1k
answer
stringlengths
20
4.1k
3,927,196
3,927,212
C++ string - how to swap a string with two characters?
Given a C++ string, str("ab"), how do I swap the content of str so that it becomes "ba"? Here is my code: string tmpStr("ab"); const char& tmpChar = tmpStr[0]; tmpStr[0] = tmpStr[1]; tmpStr[1] = tmpChar; Is there a better way?
Like this: std::swap(tmpStr[0], tmpStr[1]); std::swap is located in <algorithm>.
3,927,362
3,927,373
When saving to a file is there a way to not override whats already in the file?
When saving something to a text file is there a way to not override whats in the file already? EX. blah.txt this is an example fout << "of saving to a file."; i want the "of saving to a file" to be added on to "this is an example" not to override it.
use the append flag, like this: fstream fout("blah.txt", ios::app); if you are opening it after declaration, use something like this: fout.open("blash.txt", fstream::app);
3,927,382
3,927,404
How do I determine the number of bits in a template non-type integral constant parameter?
I would assume that this is covered in the C++ Standard, but I've not been able to find it. I am writing some templates that are going to do arithmetic on their non-type integral parameters, and I find I need the equivalent of MAX_INT for the parameter 'x' in a template like template <int x> Foo. Ideally someone could ...
See here: http://www.boost.org/doc/libs/1_41_0/libs/integer/integer_traits.html Edit: Actually it's not giving you any information about the standard however you can get the min and max value on compile time for certain types. Edit2: According to your update I can suggest you to use boost.mpl, boost.type_traitsand the ...
3,927,456
3,927,598
Security exploits in "safe" languages
I just recently finished reading Secure Coding in C and C++ by Brian Seacord, who works for CERT. Overall, it's an excellent book and I would recommend it to any programmer who hasn't yet read it. After reading it, it occurs to me that for all the various types of security vulnerabilities (such as exploit code injec...
Of course a book focused on C / C++ will focus on the most common exploit. Memory tricks on the stack and so forth. As for the "obvious" example of a language with plenty of security cavats without any direct memory access... hows PHP? Aside from the usual XSS, CSRF and SQL injection, you've got remote code injection ...
3,927,554
3,927,568
Function Declaration/Function Definition
Does it matter if the function definition is before the int (main) or after the int main? I've seen it both ways and am trying to find the proper way to display the function definition and declaration.
No .. it doesn't. Its a matter of preference. Choose which you prefer and be consistent!
3,927,656
3,927,712
Open source portable/cross-platform video camera capture library
I like to know if there's a open-source, cross-platform library for capturing web-cam data. Any other suggestions are welcome in case such solutions are not available. I am looking for something similar to portaudio if possible but this is not absolutely mandatory. Also open-source & cross-platform projects falling int...
Give a look at opencv and its highgui project.
3,927,698
3,927,754
C++ - Multidimensional Arrays
When dealing with multidimensional arrays, is it possible to assign two different variable types to the array... For example you have the array int example[i][j] is it possible for i and j to be two completely different variable types such as int and string?
Sounds like you're looking for: std::vector<std::map<std::string, int> > myData1; or perhaps: std::map<int, std::map<std::string, int> > myData2; The first would require you to resize the vector to an appropriate size before using the indexing operators: myData1.resize(100); myData1[25]["hello"] = 7; ...while the se...
3,927,810
3,927,875
How to prevent macro redefinition
After working some time on my project, this warning begins to appear: 2>Game.cpp 2>c:\program files\microsoft sdks\windows\v6.0a\include\windef.h(126) : warning C4005: 'APIENTRY' : redefinición de macro 2> c:\users\ferran\directo\gameprojects\dev-libs\glfw\include\glfw.h(72) : vea la definición anterior de 'APIE...
The error message itself is telling you the incorrect order. It says that windef.h and wingdi.h are redefining symbols that were defined in glfw.h. Put glfw.h after the Windows include files.
3,927,861
3,927,878
How to call child object's overloading function in polymorphism?
Consider the following simple polymorphism ... class Parent { public: someFunc() { /* implementation A */ }; }; class Child : public Parent { public: someFunc() { /* implementation B */ }; }; int main () { Parent* ptr; ptr = new Parent(); ptr->someFunc(); delete ptr; ptr = new Child(); ...
Try: class Parent { public: virtual someFunc() { /* implementation A */ }; //^^^^^^^ }; Though technically not required. I always find it good style to also declare the derived function virtual: class Child : public Parent { public: virtual someFunc() { /* implementation B */ }; }; U...
3,927,936
3,927,973
When is the segfault thrown?
Suppose I have a class like class A { int x; int y; public: getSum1() const { return getx() + y; } getSum2() const { return y + getx(); } getx() const { return x; } } And then I have int main(int argc, char **argv) { A *a = 0; switch(argc) { case 0:...
When you called those functions on a null pointer, you got undefined behavior. That's really all that should be said; anything can happen, don't do it. The reason it segfaults is because there is no A at null. Attempting to access those members is attempting to access an invalid address. (This happens in getx and getSu...
3,927,980
3,928,054
g++ typedef templates in inheritor class
simplifying my problem we can consider: template <class T> class Base{ typedef typename std::pair<T, T> pair; }; template <class T> class Inheritor : public Base<T> { pair *p; // mean that we want to use constructor of std::pair. // say: std::pair withou argument list Inh...
When a type name depends on a template parameter, it is a dependent name. You have to use typename to indicate you're naming a type. Read that article, and you'll see your use of typename doesn't make sense, except in the last case. Here's how your code should probably look: template <class T> class Base { public: // y...
3,927,986
3,928,170
Difference between C++ const references and consts?
What is the difference between: const double& pi = 3.14; and (no ampersand): const double pi = 3.14; They both seem to have the same L and R values so what is the difference?
For your particular example there's no difference. And that means, no way to tell them apart, whatsoever. However, since the first binds a reference to a temporary, when the type is of class type the temporary can be of a derived class, e.g. produced by a function! And it then has its destructor properly called at the ...
3,927,992
3,928,012
Which non-shared Smart Pointer for class member variables
When I have a class that contains pointers as member variables what type of smart pointer should they have if I want don't want to use plain pointers? They do not need to be shared (so no shared_ptr necessary). scoped_ptr won't work since I often need to build the objects outside of the initialization list. Or is it ma...
If you're just wanting to store member pointers in a smart pointer type class so you can't/won't forget to delete them, then a standard choice would be auto_ptr. It's in the STL and is easily "reset" with the reset() function when you need to release the current memory allocated to it and replace it with a new object....
3,928,076
3,928,095
Does a C++ method definition in a class have to specify the return type?
Just saw this question relating to a segmentation fault issue in a C++ class and program. My question relates to the class definition. Here it is as it was posted: class A { int x; int y; public: getSum1() const { return getx() + y; } getSum2() const { return y + getx()...
Yes, the ints have to be there. The original code sample is not valid (as someone else mentioned the code may have originally been C instead of C++). Firstly, the class declaration needs a terminating semicolon to stand a chance of compiling. g++ reports: foo.cpp:3: note: (perhaps a semicolon is missing after the defin...
3,928,223
3,928,349
copy using istream_iterator
What would be end of source in this case when getting a string input from console? int main() { std::vector<std::string> str; copy (istream_iterator<std::string>(std::cin), istream_iterator<std::string>(), std::back_inserter(str)); }
Terminal input or EOF . Ctrl+D in Unix. Ctrl+Z in Windows.
3,928,235
4,203,596
Visual Studio environment alternative
I use Visual C++ (7.1 and 8.0) on huge C++ project. The solution contains thousands of files. Visual Assist helps in jumping to function and class definitions. The problem is that it sometimes becomes too slow. I just can't edit a single letter without delay. Is there some alternative to this environment? I mean someth...
It seems there is no alternative to MS Visual studio. I've added separate HDD for source files and it works much better.
3,928,318
3,928,371
Is there a decompiler that will work on Visual Studio 6 C++
I have a project that I am trying to fix from a guy that left (let go) from my company. He has violated every fundamental principle of software engineering, not using source control, not backing up the source before you make more changes, etc. etc. I need to make changes to an application that is in the field and I do...
Well there's the Decompiler from Hex-Rays: https://www.hex-rays.com/products/decompiler/ It is pretty good for the fact that it is creating C code from Assembler but it works pretty good. It's also pretty expensive Edit: Additional note it is combined with IDA Pro the pretty well-known disassembler from them. That alre...
3,928,453
3,928,721
Developing an RSS Feed Reader in C++
I wanna write a simple RSS Feed reader in C++. I understand that the basic requirement is to understand XML parsing ( at the low level), opening, reading/writing, closing sockets and stuff like that. I don't need help in coding for sure. But It would be great if someone can help in getting started with RSS Protocol. E....
If you want to "do everything from scratch" as a learning exercise then go for it. However, if your goal is a to write an app to solve a problem then I'd suggest using off-the-shelf librarys as much as possible. Assuming you're after the learning experience... Make a socket connection to port 80 on the server hosting...
3,928,480
3,928,517
total template specialization
I'm reading the book of Meyers about effective c++ programming, in item 25 I found total template specialization, but I can't understand it, what does that it mean? he also gives example: namespace std { template<> void swap<Widget>(Widget& a, Widget& b) { swap(a.pimpl, b.pimpl); } }...
Typically you use templates because you have a piece of code that is generic enough that it can be applied to different types. However, for some types you may want to do something different (e.g. because there's a more efficient way of doing it). This is when template specialization comes to the rescue (you can think o...
3,928,571
3,929,016
ignore punctuation using manipulator
Is it possibile to ignore punctuacion using std manipulator on cin? For example suppose you have an input stream (in the actual case a file) like: "one, two three". I want to be able to do: f >> ignore_punct >> a; f >> ignore_punct >> b; f >> ignore_punct >> c; at the end a=="one", b=="two", c=="three".
Try this: It uses the local to filter out punctuation. This allows the rest of the code to remain unchanged. #include <locale> #include <string> #include <iostream> #include <fstream> #include <cctype> class PunctRemove: public std::codecvt<char,char,std::char_traits<char>::state_type> { bool do_always_noconv() co...
3,928,612
3,928,977
wait command wont wait for child process to finish c cpp c++
I am trying to write a c++ program that creates a child process, runs a command and pipes the output back to the input of a command the parent is running. I have the parent execute the wait(NULL) or wait((void*)pid) command but it does not wait. here is the code: #include <string.h> #include <fstream> #include <iostrea...
I see four problems: 1) execlp() is failing: execlp() (or any of the exec family of functions) completely replaces the currently running process image if successful - it is not expected to return, unless something goes wrong. But you are seeing the "Child: Done sleeping, returning" message, so it cannot have succeeded...
3,928,835
3,928,870
Templated function pointer?
I want to do something like this: I want the user to provide a return type and an argument (there will always only be one) then I want the user to be able to provide the pointer of a function that matches this criteria. I will be using this to create a timed event. The issue here is that usually with templates you must...
Well boost.function + boost.bind is something you can use for this: int explodeFunc( std::string const & someString ) { std::cout << someString << " exploded" << std::endl; return 1; } and later... boost::function< int() > timeEvent = boost::bind(explodeFunc, "The world"); int retVal = timeEvent(); But I a...
3,928,853
3,928,874
How can I achieve something similar to a semaphore using boost in c++?
I noticed that boost does not seem to support semaphores. What's the easiest way to achieve a similar effect?
You either need Boost Interprocess semaphore or Boost Thread synchronization primitives. Mutex/Lock and condition are primitives that are commonly used to synchronize access to shared resources across multiple threads of a single process. There are exclusive, readers-writer and recursive/reentrant types of mutexes. Mut...
3,928,935
3,928,963
size of linked list in c++ function
Can someone please tell what is the code for checking the size of a linked list(number of nodes).This is what my code is(inserting nd deleting head + printing info of all nodes) struct node { int info; node *nextptr; }; class list { private: node *L,*tail; int count; public: list() { ...
Well the simplest would beto add in the function InsertHead add ++count and in the RemoveHead do --count Otherwise you could use a loop to go through the list e.g. node* p = L; while (p != NULL) { ++count; p = p->nextptr; }
3,928,966
3,931,461
Boost condition deadlock using wait() in producer-consumer code
I have implemented a basic threaded producer-consumer (thread 1 = producer, thread 2 = consumer) using Boost threads and conditions. I am getting stuck in wait() indefinitely quite often. I can't really see what could be wrong here. Below is some pseudo-code: // main class class Main { public: void AddToQueue(...some...
I did something similar recently even though mine uses the STL queue. See if you can pick out from my implementation. As wilx says, you need to wait on the condition. My implementation has maximum limit on the elements in the queue and I use that to wait for the mutex/guard to be freed. I originally did this on Windows...
3,928,968
3,929,045
C++ Outputting to an Excel file
Is there a way to output to an excel file but to assign what you're outputting to a specific cell in the excel file? For example have an array be cell x 1-50 or something like this.
There are some C++ libraries for that. An example of a free one is xlsstream and a commercial one would be LibXL. Google is your friend to find more.
3,929,179
3,929,213
trouble pipeline three commands "dmesg|sort|more" c++
I have successfully piped the output of one command into the input of another and then show the output of the second command to the screen. I want to do this with three successive commands. (actually eventually I want to do it with N commands passed into the program at run time. This is my attempt at pipelining three c...
pipe(2) only provides 2 file descriptors for 1 pipe. The 3rd file descriptor (pfd[2]) is junk and is never getting initialized. If you want to create a pipeline with 3 commands in it, you need to call pipe() twice to get two pipes: one for connecting the first and second processes, and one for connecting the second a...
3,929,398
3,929,411
creating a std::vector of a templated class?
I currently have a class that uses template arguments. I need an array of these. How could I do this (without boost). ex: template <typename RET, typename T> class AguiTimedEvent { RET (*onEvent)(T arg); double timeStamp; public: RET call(T arg); bool expired(); AguiTimedEvent(); AguiTimedEvent(...
std::vector<AguiTimedEvent<int, int> > v; If you need to store objects of different AguiTimedEvent types that have different template arguments, you need to create a base class (e.g., AguiTimedEventBase) and store pointers in the vector.
3,929,448
3,929,454
Assigning a depth to each node
I read a few other articles on here that looked similar, but didn't quite answer my problem. I've been given a question for an assignment to assign every node in a binary tree its respective depth. I just can't quite get it. For reference this is my code: struct treeNode { int item; int depth; treeNode *left; ...
You don' t need else //leaf return depth--; You also don't want to increment the depth variable, just pass depth+1 to the next interation. Also there's no need to return a value. Try this: void assignDepth(Tree T, int depth) { if(T!=NULL) { assignDepth(T->left, depth+1); T->depth = dept...
3,929,487
3,929,501
c++ compress byte array
Greetings all, I load set of images and generate volume data.I save this volume data in a unsigned char *volume array. Now I want to save this array in a file and retrieve.But before saving I want to compress the byte array since the volume data is huge. Any tips on this? Thanks in advance.
volume in your example is not an array. As for compression, there are books written on the topic. For something quick and easy to use with C++, check out the boost.iostream library, which comes with zlib, gzip, and bzip2 compressors. To offset my nitpicking, here's an example (changing to char because it's a lot more v...
3,929,493
3,932,354
Is there a disadvantage to using boost::interprocess::interprocess_semaphore within a single multithreaded c++ process?
The disadvantage would be in comparison to a technique that was specialized to work on threads that are running within the same process. For example, does wait/post cause the whole process to yield, rather than just the executing thread, even though anyone waiting for a post would be within the same process? The semaph...
Use Boost.Thread condition variables as shown here. The accompanying article has a good summary of Boost.Thread features. Using interprocess semaphores will work but it's likely to place a tax on your execution due to use of unnecessarily heavyweight underlying OS locking primitives (named kernel objects in Windows, fo...
3,929,563
3,929,593
C++0x Smart Pointer Comparisons: Inconsistent, what's the rationale?
In C++0x (n3126), smart pointers can be compared, both relationally and for equality. However, the way this is done seems inconsistent to me. For example, shared_ptr defines operator< be equivalent to: template <typename T, typename U> bool operator<(const shared_ptr<T>& a, const shared_ptr<T>& b) { return std::les...
This was a defect in drafts of C++11; a defect report was opened to change the std::unique_ptr relational operator overloads to use std::less: see LWG Defect 1297. This was fixed in time for the final C++11 specification. C++11 §20.7.1.4[unique.ptr.special]/5 specifies that the operator< overload: Returns: less<CT>(...
3,929,622
3,929,649
Bug in Programming Interviews Exposed: Linked Lists
I was going through the Programming Interviews Exposed book. There's a code given for inserting an element at the front of linked lists. bool insertInFront( IntElement **head, int data ){ IntElement *newElem = new IntElement; if( !newElem ) return false; newElem->data = data; *head = newElem; retur...
I'm not sure what kind of interview book you're reading, but this code example is terrible c++. Yes, you need to point newElem->next to the old head before overwriting head. Also, there's no reason to check if newElem is NULL - if it couldn't be allocated, C++ throws an exception. Also, insertInFront should be a me...
3,929,774
3,930,197
How much overhead is there when creating a thread?
I just reviewed some really terrible code - code that sends messages on a serial port by creating a new thread to package and assemble the message in a new thread for every single message sent. Yes, for every message a pthread is created, bits are properly set up, then the thread terminates. I haven't a clue why anyone...
...sends Messages on a serial port ... for every message a pthread is created, bits are properly set up, then the thread terminates. ...how much overhead is there when actually creating a thread? This is highly system specific. For example, last time I used VMS threading was nightmarishly slow (been years, but fr...
3,929,920
3,930,167
C++ and SDL: How does SDL_Rect work exactly?
I'm working on some SDL stuff and I've run into some trouble when trying to set the location of a loaded BMP. Here's the code. while(event.type != SDL_QUIT) //The game loop that does everything { SDL_Rect *location; location = SDL_Rect(600,400,0,0); SDL_PollEvent(&event); //This "polls" the event //Draw...
SDL is written in C so SDL_Rect is just a simple struct. To dynamically allocate it you'd have to use new otherwise the compiler will interpret your code as a call to a regular function called SDL_Rect that returns a SDL_Rect*. In this case I see no reason to use dynamical allocation; just use the struct initializatio...
3,930,013
3,930,015
Stack overflow - static memory vs. dynamic memory
If you write int m[1000000]; inside the main function of C/C++, it will get a runtime error for stack overflow. Instead if you write vector<int> m; and then push_back 1000000 elements there, it will run fine. I am very curious about why this is happening. They both are local memory, aren't they? Thanks in advance.
Yes, the vector itself is an automatic (stack) object. But the vector holds a pointer to its contents (an internal dynamic array), and that will be allocated on the heap (by default). To simplify a little, you can think of vector as doing malloc/realloc or new[] calls internally (actually it uses an allocator). EDIT:...
3,930,185
7,836,203
FreeImage dll nor working for batch process
I need to load batches of image files and change their dimensions. I'm doing it through FreeImage.dll in C++. Each batch contains JPG and TIF files. The problem is the exe processes the first batch accurately but for further batches it starts skipping some files, specially JPG files. I tried Initializing and Uninitiali...
It sounds as if FreeImage is leaking memory or memory gets fragmented in the code calling FreeImage. Early in the lifetime of your process, enough contiguous memory is still available and everything works fine. Later on, things start to fail on larger color images. The reason why specifically jpegs are failing is becau...
3,930,300
3,930,561
How to add an error logger to a class
I would like to use a generic error msg handler so I can GetLastError and SetError easily for any class. I came up with this scheme. But I have a couple of questions. Please note this implementation is just for testing. But I want to get the basic design right. #include <iostream> #include <stdarg.h> class ErrorHandle...
Error Handler and logger are two different entities. Error handler decides what to do with the errors. Should it be send to logger immediately, should it be saved in databases, or should it be simply saved in some buffer till someone asks. Logger decides how to log the given message. Should it be shown on the console o...
3,930,344
3,930,377
make file issue : always spits out "Nothing to be done for `make.w'."
I have 3 files Head.cpp , Head.h and Hello.cpp . I am trying to build a make for the compilation process. My makefile is make.w Hello : Head.o Hello.o g++ -o Head.o Hello.o Head.o : Head.cpp g++ -o Head.cpp Hello.o: Hello.cpp g++ -o Hello.cpp every time I type the command make make....
Since you are calling the make with a non-default make file which is makefile or Makefile you need to use the -f option as: make -f make.w ^^ Looks like you are currently calling it as: make make.w which does not work. It tell make to make the target make.w in the default makefile. Also When converting from .c t...
3,930,379
3,930,720
Comparing typenames in C++
I typed this into a template function, just to see if it would work: if (T==int) and the intellisense didn't complain. Is this valid C++? What if I did: std::cout << (int)int; // looks stupid doesn't it.
Just to fit your requirement you should use typeid operator. Then your expression would look like if (typeid(T) == typeid(int)) { ... } Obvious sample to illustrate that this really works: #include <typeinfo> #include <iostream> template <typename T> class AClass { public: static bool compare() { retu...
3,930,447
3,930,469
Stack memory is being referred by dynamically allocated object member variable
I have following code class Test { public: int &ref; int a; Test(int &x) :ref(x) { cout<<"Address of reference "<<&ref<<endl; cout<<"&a : "<<&a<<endl; cout<<"this = "<<this<<endl; } }; int main() { Test *pObj = NULL; { int i = 10; cout<<"Addr...
Why [does the] heap object have a reference to stack memory? Because you passed the local variable i by reference into the constructor of the Test object that you created dynamically, then the constructor stored that reference. Why is this allowed? In C++, you the programmer are responsible for ensuring that any p...
3,930,452
4,687,711
Using Thread for Taking input in one of them and Displaying output in the other one
I am making a chat application for my homework which runs within a Linux Terminal. So, I need to take from the user some input and display the output from all the users as well in a well organized manner. So, I made two threads. One thread have a cin command and the other thread is having a display function which basic...
Simulate a scrolling window? As text is received, store the last 10 lines. Then loop through the last 10 lines of text received and print them on lines 1-10 on the screen using gotoxy.
3,930,492
3,930,499
#include <Header.h> is not compiling while #include "Header.h" is compiling
Don't understand why #include <Header.h> is not compiling while #include "Header.h" is compiling with Visual Studio 2008. Am I missing something?
The two forms of #include search for headers differently. You can find which paths are searched for each form in the #include MSDN documentation.
3,930,630
3,930,668
How is C++ VIRTUAL function not redundant?
Possible Duplicates: Overriding vs Virtual How am i overriding this C++ inherited member function without the virtual keyword being used? I am learning C++ at this moment, but I'm not completely in the dark when it comes to programming languages. Something makes no sense to me. My understanding is that a VIRTUAL fun...
Virtual functions are useful when dealing with polymorphism. Non-virtual functions are looked up at compile time, so creating a variable of type Color and calling its Declare() method will always result in Color::Declare() being called, even if the object in the variable is a Purple.
3,930,813
4,002,917
optimization of access to members in c++
I'm running into an inconsistent optimization behavior with different compilers for the following code: class tester { public: tester(int* arr_, int sz_) : arr(arr_), sz(sz_) {} int doadd() { sm = 0; for (int n = 0; n < 1000; ++n) { for (int i = 0; i < sz; +...
I disassembled the code with MSVC to better understand what's going on. Turns out aliasing wasn't a problem at all, and neither was some kind of paranoid thread safety. Here is the interesting part of the arradd function disassambled: for (int n = 0; n < 10; ++n) { for (int i = 0; i < sz; ++i) 013C101C ...
3,930,841
3,931,028
Is there a way to make a C++ struct value-initialize all POD member variables?
Suppose I have a C++ struct that has both POD and non-POD member variables: struct Struct { std::string String; int Int; }; and in order for my program to produce reproduceable behavior I want to have all member variables initialized at construction. I can use an initializer list for that: Struct::Struct() : ...
The cleanest way would be to write the auto-initialzed template class initialized<T>: EDIT: I realize now it can be made even more flexible by allowing you to declare initialized<Struct>. This means that you can declare initialization without modifying the original Struct. The default initialization 'T()' was inspired ...
3,930,875
3,930,937
Managing a priority queue?
I have a structure struct state{ int cur[10]; int next[10]; int priority; }; and a priority queue of these states.How can I manage the priority queue so that front element is the element with the minimum value of 'priority' ?
Never mind I found the answer http://www.cplusplus.com/reference/stl/priority_queue/priority_queue/ I'll just have to use an external comparator function. But can someone explain this? bool operator() (const int& lhs, const int&rhs) const <<========== { if (reverse) return (lhs>rhs); else return (lhs<...
3,931,026
3,932,064
How can I synchronize three threads?
My app consist of the main-process and two threads, all running concurrently and making use of three fifo-queues: The fifo-q's are Qmain, Q1 and Q2. Internally the queues each use a counter that is incremented when an item is put into the queue, and decremented when an item is 'get'ed from the queue. The processing inv...
An example of how I would adapt the design and lock the queue access the posix way. Remark that I would wrap the mutex to use RAII or use boost-threading and that I would use stl::deque or stl::queue as queue, but staying as close as possible to your code: main-process: ... start thread Monitor ... while (!quit) { ...
3,931,167
3,931,202
Why reference variable inside class always taking 4 bytes irrespect of type? (on 32-bit system)
I have below code, running on 32-bit windows, visual-studio. template <class T> class Test { public: T &ref; Test(T &x) :ref(x) {} }; int main() { cout<<"sizeof Test<int> : "<<sizeof(Test<int>)<<endl; cout<<"sizeof Test<double> : "<<sizeof(Test<double>)<<endl; cout<<"sizeof Test<char> : "<<sizeof(Test<char>)<<...
Those for bytes are the reference. A reference is just a pointer internally, and pointers typically use 4 bytes on a 32bit system, irrespective of the data types because it is just an address, not the value itself.
3,931,229
3,935,848
Is there such a thing like a Printer-Markup-Language
I like to print a document. The content of the document are tables and text with different colors. Does a lightwight printer-file-format exist, which can be used like a template? PS, PDF, DOC files in my opinion are to heavy to parse. May there exist some XML or YAML file format which supports: Easy creation (maybe wi...
I noticed you’re using MFC (so, Windows). In that case the answer is a qualified yes. In recent versions of Windows, Microsoft offers the XPS Document API which lets you create and manipulate a PDF-like document using XML, which can then be printed using the XPS Print API. (For earlier versions of Windows that don’t su...
3,931,292
3,931,310
std::rel_ops functionality as a base class. Is that appropriate solution?
I've implemented the functionality of std::rel_ops namespace as a template base class (it defines all comparison operators using only operators < and ==). For me it's a bit weird that it works (so far) properly, also I'm concerned about the 'hacks' used. Can anyone assess the following code and say if I'm just lucky it...
Well, why not use Boost.Operators?
3,931,312
3,931,589
Value initialization and Non POD types
An hour ago I posted an answer here which according to me was correct. However my answer was downvoted by Martin B. He said You're just lucky and are getting zeros because the memory that i was placed in happened to be zero-initialized. This is not guaranteed by the standard. However after reading Michael Burr's answ...
Visual Studio has known bugs in all current versions (2005, 2008, 2010) where it doesn't correctly implement value-initialization for non-POD types that don't have a user declared constructor. By the language rules none of you asserts should fire but do exhibit the compiler issues. These are some of the bug reports, no...
3,931,342
3,935,607
Help compiling and using boost c++ libraries
I am working on a C++ project where I'd like to use boost's serialization libraries. I downloaded and installed the latest boost libraries from boost's home page. When I tried to compile and run the one of boost's demo serialization examples, I got all sorts of errors that looked like this: /usr/local/include/boos...
Thank you everyone for all your help. I finally got my problem solved, though my solution is fairly anti-climactic, and probably not that informative. I had tried to install the boost libraries manually, by downloading them from boost's website directly, and found that all the libraries had been installed in /usr/loca...
3,931,535
9,437,778
Boost Serialize - Serialize data in a custom way
If I'm using Boost Serialization to serialize an Integer: #include <boost/archive/text_oarchive.hpp> #include <iostream> int main() { boost::archive::text_oarchive oa(std::cout); int i = 1; oa << i; } The result will be the following: 22 serialization::archive 5 1 Now I'm curious if and how I could chang...
You can write your own archive, something like this: #include <cstddef> // std::size_t #include <string> #include <typeid> template <typename T> std::string printName() { // Unmangle for your platform or just specialise for types you care about: return typeid(T).name(); } /////////////////////////////////////////...
3,931,607
3,931,740
What should we consider to use either static linking and dynamic linking?
Possible Duplicates: Static linking vs dynamic linking C++ application - should I use static or dynamic linking for the libraries? What point we should take care before selecting static and dynamic linking?
static linking is used for libraries which are trivial and which needs to be linked in order to execute your binary. dynamic linking is used when you can load library on demand and once task is done, you can unload it. To Apply patches or use updated versions, dynamic linking will be useful, if binary compatibility is ...
3,931,805
3,931,917
how to resolve ftp site using boost.asio?
Boost.asio documentation doesn't support any ftp examples. `boost::asio::io_service io_service; tcp::resolver resolver(io_service); tcp::resolver::query query("www.boost.org", "http"); tcp::resolver::iterator endpoint_iterator = resolver.resolve(query);` that resolve http site and get an HTTP endpoint. but tcp::resol...
For one you've still got the ftp:// in your host name, AFAIR your host name should be "ftp.remotesensing.org" #include "stdafx.h" #include <iostream> #include <boost/asio.hpp> using namespace boost::asio::ip; using namespace std; int _tmain(int argc, _TCHAR* argv[]) { try { boost::asio::io_service io_servic...
3,931,809
3,931,862
Shared object symbol resolution
Suppose I have 2 static Libs S1 and S2 which are different versions of the same lib and have the same C (not C++) interface though implementations are different. 2 shared libs D1 and D2 each of which links to S1 or S2 only. Suppose an application A links with S2 which is the more recent of the static libs and dynamical...
Will D1 just use S1s functions or is there any way to enforce it to use S2s functions? Yes, D1 will use S1 functions. No, you cannot enforce it to use S2 functions. Can anything go wrong in this setup? It depends on what is inside your libraries.
3,931,845
3,931,945
C++ - binding function
I have some (library API, so I can't change the function prototype) function which is written the following way: void FreeContext(Context c); Now, at some moment of my execution I have Context* local_context; variable and this is also not a subject to change. I wish to use boost::bind with FreeContext function, but I ...
You could use Boost.Lambda which have overloaded the * operator for _n. #include <boost/lambda/lambda.hpp> #include <boost/lambda/bind.hpp> #include <algorithm> #include <cstdio> typedef int Context; void FreeContext(Context c) { printf("%d\n", c); } int main() { using boost::lambda::bind; using boost::l...
3,931,909
3,932,514
Force QWebView to download web page content in a separate thread?
How can i force QWebView into downloading the webpage and related content in a separate thread?
You cannot easily. You could implement your own QNetworkAccessManager (see createRequest()) that offloads the work to a QNetworkAccessManager in another thread. What is your exact problem? Maybe it can be solved differently or a bug to Qt can be reported?
3,932,081
3,932,123
Is there any physical part of memory with the address of NULL(0)?
I know there's an old saying when you want to indicate this specific pointer doesn't point to anything it should be set to NULL(actually 0), but I'm wondering isn't there actually a physical part of memory with the address of NULL(0) ?
There is always a physical address of 0 (but it may not necessarily map onto physical RAM), but on a typical platform any accesses will typically be performed in a virtual address space (as jweyrich points out below, you can use mmap and so on to directly map the physical address space), so any attempt to read/write to...
3,932,287
3,933,894
Is i += ++i undefined behavior in C++0x?
I'm very convinced with the explanation I've found that said that i = ++i is not undefined as far as C++0x is concerned, but I'm unable to judge whether the behavior of i += ++i is well-defined or not. Any takers?
The reasoning that makes i = ++i well-defined can equally be used to prove that i += ++i must also be well-defined. i += ++i is equivalent to i += (i += 1) and the new sequencing rules require that the assignment takes place before the value-computation of the i += 1 sub-expression. This means that the result of the ex...
3,932,332
3,933,501
How to disable automatic indenting when typing ':' in Visual Studio 2008
When i write a classes constructor typing : to start the initialization list of a C++ constructor Visual Studio indents the line when it is right after a namespace directive. Also when i type :: (scope resolution) Visual Studio indents the line, which i found very annoying since the indentation was correct in the first...
The reason for this is behaviour is the preceding namespace directive: namespace XY { MyClass::MyClass() So MSVC wants to indent the constructor definition. Mea culpa.
3,932,367
3,932,402
How to safely delete multiple pointers
I have got some code which uses a lot of pointers pointing to the same address. Given a equivalent simple example: int *p = new int(1); int *q = p; int *r = q; delete r; r = NULL; // ok // delete q; q = NULL; // NOT ok // delete p; p = NULL; // NOT ok How to safely delete it without multiple delete? This is especial...
The answer, without resorting to managed pointers, is that you should know whether or not to delete a pointer based on where it was allocated. Your example is kind of contrived, but in a real world application, the object responsible for allocating memory would be responsible for destroying it. Methods and functions wh...
3,932,487
3,932,674
Can I add MFC support to an Existing ATL COM project
I have created a Shell Extension using ATL COM Object . But during creation I haven't added MFC support. Can I change the setting now to add MFC support
Yes, but I believe that doing this won't auto-add all the required headers and #defines - of course, you could try this first, and check to be sure. If that does not work, you could use 'File->New->Project from Existing Code' to create a new project in your solution that uses both MFC and ATL, using the code in your o...
3,932,641
3,932,689
Memory layout question
Do these two structs have the same memory layout? (C++) struct A { int x; char y; double z; }; struct B { A a; }; Further can I access x, y, z members if I manually cast an object of this to an A? struct C { A a; int b; }; Thanks in advance. EDIT: What if they were classes instead of structs?
Yes and yes. The latter is commonly used for emulating OO inheritance in C.
3,932,693
3,932,970
c++ syntax of create an instance
class class_name instance; class_name instance; The above all work with cl.exe, but is it standard,is it the same with all other compilers?
class class_name instance; is allowed by the elaborated-type-specifier nonterminal in the C++ grammar. It's hard to point to a particular section of the standard that tells you this, since even in the appendix that gives the C++ grammar it's rather spread out, but the production basically goes (with many steps elided):...
3,932,936
3,939,750
How to Convert CString LPStr
I want to read a value from registry using the following method: char* cDriveStatus=ReadFromRegistry(HKEY_CURRENT_USER,_T(NDSPATH),m_szDriveName); I tried converting using GetBuffer,m_szDriveName.GetBuffer(0) but this again shows error: error C2664: cannot convert parameter 3 from 'wchar_t *' to 'LPSTR' Edit: Decla...
This is what worked for me: char* cDriveStatus=ReadFromRegistry(HKEY_CURRENT_USER,_T(NDSPATH),(LPSTR)m_szDriveName.GetBuffer(m_szDriveName.GetLength()));
3,933,006
3,933,120
Is it good practice to make member variables protected?
Asking this question because I feel that member variables of my base will be needed later in derived classes. Is there a drawback of making them protected? EDIT: Edited to better show my intention. EDIT: @sbi : Is this also wrong? This class will be used for error recording and retrieving in other classes. Is it better...
Encapsulation is one of the main features of OO. Encapsulating your data in classes means that users of the class can not break the class' data's invariants, because the class' state can only be manipulated through its member functions. If you allow derived classes access to their base class' data, then derived classe...
3,933,027
3,939,495
How to get the GL library/headers?
#include <gl\gl.h> #include <gl\glu.h> #include <gl\glaux.h> This is an example, but where to get GL headers?
Windows On Windows you need to include the gl.h header for OpenGL 1.1 support and link against OpenGL32.lib. Both are a part of the Windows SDK. In addition, you might want the following headers which you can get from http://www.opengl.org/registry . <GL/glext.h> - OpenGL 1.2 and above compatibility profile and extens...
3,933,637
3,933,712
Why cannot a non-member function be used for overloading the assignment operator?
The assignment operator can be overloaded using a member function but not a non-member friend function: class Test { int a; public: Test(int x) :a(x) {} friend Test& operator=(Test &obj1, Test &obj2); }; Test& operator=(Test &obj1, Test &obj2)//Not implemented fully. just for test. { return...
Because the default operator= provided by the compiler (the memberwise copy one) would always take precedence. I.e. your friend operator= would never be called. EDIT: This answer is answering the Whats the inherent problem/limitation in supporting = operator ? portion of the question. The other answers here quote the...
3,933,744
4,406,934
How to Notice Close of MySql Server in Qt
When I closed MySql server, how can I understand that mysql server is gone away from my Qt program? Edit: Here my trial: When I close MySql, I get these results, and I can't catch that MySql is closed. My Code Snippet is QSqlQuery query(db); query.exec("SELECT * From RequestIds"); qDebug()<<query.lastError(); qDebug()<...
There is a bug related with QSqlDatabase::isOpen() in Qt. https://bugreports.qt.io/browse/QTBUG-223
3,934,290
3,934,357
Calling an executable's function code
I have the location/offset of a particular function present inside an executable. Would it be possible to call such a function (while suppressing the CRT's execution of the executable's entry point, hopefully) ?
In effect, you can simulate the Windows loader, assuming you run under Windows, but the basics should be the same on any platform. See e.g. http://msdn.microsoft.com/en-us/magazine/cc301805.aspx. Load the file into memory, Replace all relative addresses of functions that are called by the loaded executable with the a...
3,934,569
3,934,618
MFC DLL using C++ with Visual Studio 2008
I can't seem to find any walk-trough on how to create a MFC DLL using Visual Studio 2008. My problem is the following. I need to use wininet.h with my DLL and my solution to that was to use MFC DLL. Anyhow trying to link my project gives me 5 Link errors I believe that the error is of a kind that I need to add Addition...
Add Crypt32.lib to your lib dependencies under Linker/Input - Additional dependencies:
3,934,630
3,950,208
Writing XML Nodes in QtXML (QDomElement)
I would like to write Nodes like <name>Peter</name> (with start and end tag) into a QDomDocument. When I create QDomElements and append them as child to a parent element: QDomElement node = doc.createElement("node"); parent.appendChild(node); They are added as <node/> to the parent element. The parent automaticall...
Create a text node using DOM Document, and add it to your newly created element as a child: QDomElement node = doc.createElement("name"); parent.appendChild(node); // Now, add a text element to your node node.appendChild( doc.createTextNode( "Peter"));
3,934,692
3,934,753
C++ typename and inner classes
I tried googling this, but I was unable to come up with a suitable answer. Could any C++ gurus tell me why C++ requires you to declare OuterClass<T>::Innerclass with the typename keyword? I am a TA for a data structures course and I see this error all of the time. I know to tell my students that they need to put typen...
That's because of the two-phase name lookup in templates. When the compiler sees Innerclass it must know whether that name is a type or not (is could, for example, be a static member of type int for some specialization of OuterClass). So it supposes it is NOT a type name unless you say so. typename must be used in temp...
3,934,769
3,934,932
how casting of return value of main() function works?
I am using Visual studio 2008. For below code double main() { } I get error: error C3874: return type of 'main' should be 'int' instead of 'double' But if i use below code char main() { } No errors. After running and exiting the output window displays The program '[5856] test2.exe: Native' has exited with cod...
The answer to your first question is sort of yes. A char is essentially a very small integral type, so the compiler is being (extremely) lenient. Double isn't acceptable because it's not an integral type. The 0xCCCCCC is memory that never got initialized (except for the purposes of debugging). Since ASCII character...
3,934,775
3,934,822
How to initialize a pointer to a specific memory address in C++
An interesting discussion about this started here but no one have been able to provide the C++ way of doing: #include <stdio.h> int main(void) { int* address = (int *)0x604769; printf("Memory address is: 0x%p\n", address); *address = 0xdead; printf("Content of the address is: 0x%p\n", *address); return 0...
In C++, always prefer reinterpret_cast over a C-cast. It's so butt ugly that someone will immediately spot the danger. Example: int* ptr = reinterpret_cast<int*>(0x12345678); That thing hurts my eyes, and I like it.
3,934,862
3,934,947
Can a using-declaration appear at block/function scope?
My question is pretty much the title. Example #include <iostream> int main() { using std::cout; //legal? { using std::cin; //legal? } }
7.3.3 The using declaration A using-declaration introduces a name into the declarative region in which the using-declaration appears. And, since someone asked in a comment about using namespace: 7.3.4 Using directive A using-directive shall not appear in class scope, but may appear in namespace scope or in block...
3,934,898
3,935,400
Detecting child processes
Is there a way (in C++ & windows XP) to detect if one process spawns any other processes? for example, write.exe in system32 spawns wordpad.exe then disappears, is there a function that tells me if the process is about to do this? for those interested i solved the problem using this section of msdn: http://msdn.microso...
Nothing in the Win32 API for this. However, it is supported through WMI with the Win32_ProcessStartTrace query. You'll find some C# code that demonstrates the query in my answer in this thread. Writing WMI code in C++ is fairly painful, you'll find a link to boilerplate code you have to write in the MSDN Library art...
3,934,933
3,934,964
Templated Functions.. ERROR: template-id does not match any template declaration
I have written a function template and an explicitly specialized templated function which simply takes in 3 arguments and calculates the biggest among them and prints it. The specialized function is causing an error,whereas the template works fine. But I want to work with char* type. This is the error I get=> error: t...
You need to take the pointers by reference: template <> void Max(char*& a,char*& b,char*& c) That said, it would be better not to use an explicit specialization and instead just overload the function: void Max(char* a, char* b, char* c) It's almost always a bad idea to specialize function templates. For more, see ...
3,935,183
3,935,468
Forward declaration include, on top of declaration include (ClassFwd.h + Class.h)
In Effective C++ (3rd edition), Scott Meyers, in Item 31, suggests that classes should have, on top of their classic Declaration (.h) and Definition (.cpp) files, a Forward Declaration Include File (fwd.h), which class that do not need the full definition can use, instead of forward declaring themselves. I somewhat see...
I used forward declaration header files for all my libraries. A library would typically have this structure: lib/ include/ class headers + Fwd.h src/ source files + internal headers The lib/include directory would contain all public classes headers along with one forward declarations header. This made the libr...
3,935,222
3,935,343
How to remove pointer from boost::ptr_vector without object being deleted?
How to exclude pointer from boost::ptr_vector without his deletion? =)
ptr_vector<A> v; v.push_back(new A); A *temp=v.release(v.begin()).release(); At this point you own the object exclusively through temp. If you don't need it, use this instead: v.release(v.begin()); [code credit: see here]
3,935,421
3,935,456
Function template specialization
While reading this, I'm confused by the following examples: // Example 2: Explicit specialization // template<class T> // (a) a base template void f( T ); template<class T> // (b) a second base template, overloads (a) void f( T* ); // (function templates can't be partially // special...
Yes, it's because of the ordering of the declaration. When the compiler encounters (c) in the second set, the only defined template to specialize is (a). This is why you must be careful in ordering your template specializations. The C++ Programming Language goes into quite some detail about this (Section 13.5.1). I hig...
3,935,446
3,936,299
Finding unique path name for a given input
I'm working on a problem where I need to have a way to convert a user inputted filename to a unique path name. Let's say I let the user specify a path name that points to a file that contains some data. I can then do Data* pData=Open(PathName). Now if the user specifies the same path name again, I'd like to be able ...
For Windows, PathCanonicalize() is your friend. The shell path handing package in Windows has a few additional routines that'll help you out. Unfortunately, I'm not sure what the Unix equivalents to this package is.
3,935,648
3,935,818
Compilation error in Makefile, includes not showing up
I have a makefile as follows: CC = gcc CFLAGS = -fmessage-length=0 -MMD -MP -MF"$(@:%.o=%.d)" -MT"$(@:%.o=%.d)" $(INCLUDES) ifdef DEBUG CFLAGS += -g3 endif INCLUDES = \ -I../config.include \ -I../log.include \ -I../services.include SRC_DIR = src BIN_DIR = bin BINARY = report SRCS = $(shell ls $(SRC_DIR)/*.cpp) OBJS...
You have to redefine CXXFLAGS and CXX and not CFLAGS and CC for .cpp files. Check the output of make -p and search for %.o: %.cpp rule.
3,935,681
3,935,700
Can I define a map whose key is a structure?
and how can I do it in C++?
You can use any type as a map key, as long as it implements an operator< (plus the usual copy-and-assign requirements for values stored in containers). For instance: struct example { int x; } bool operator < (const example &l, const example &r) { return l.x < r.x; } std::map<example, int> values; Alternatively, you...
3,935,819
3,935,966
What's a good Wordpress extension for coloring C/C++/script code?
My research group uses a Wordpress blog. Frequently I want post snippets or even entire short programs I've been working on to it, with most of my code being written in C/C++ or scripting languages (Bash, TCL, etc). I figure that there have to be some good extensions to Wordpress to colorify code since so many peopl...
This was the first I investigated when I started a Wordpress blog. You can use Wordpress' sourcecode shortcode, as exemplified here. It requires JavaScript on the client side (otherwise it renders as just preformatted text). Cheers & hth.,
3,935,853
3,935,876
C++: Is it possible to call an object's function before constructor completes?
In C++, is it possible to call a function of an instance before the constructor of that instance completes? e.g. if A's constructor instantiates B and B's constructor calls one of A's functions.
Yes, that's possible. However, you are responsible that the function invoked won't try to access any sub-objects which didn't have their constructor called. Usually this is quite error-prone, which is why it should be avoided.
3,935,874
3,942,241
boost::filesystem relative path and current directory?
How can I use boost::filesystem::path to specify a relative path on Windows? This attempt fails: boost:filesystem::path full_path("../asset/toolbox"); // invalid path or directory. Maybe to help me debug, how to get the current working directory with boost::filesystem?
getcwd = boost::filesystem::path full_path(boost::filesystem::current_path()); Example: boost::filesystem::path full_path(boost::filesystem::current_path()); std::cout << "Current path is : " << full_path << std::endl; To access current_path one needs to add #include <boost/filesystem.hpp>.
3,935,916
3,936,024
Out of class constructor definition for a specialized class template
I am trying to define a constructor for an explicitly specialized class template outside the class definition, as so: template <typename T> struct x; template <> struct x<int> { inline x(); /* This would have compiled: x() { } */ }; template <> // Error x<int>::x() { } But it seems to be an e...
Don't specify template<> for the definition: template <typename T> struct x; template <> struct x<int> { x(); }; inline x<int>::x(){} Edit: The constructor definition isn't a specialization, so template<> is unnecessary. It's the definition of the constructor of a specialization. So, you just need to specify the t...
3,936,019
4,082,659
Boost MSM only processing internal transitions
I'm using the new Boost 1.44.0 MSM library to produce a state machine. In this state machine there are two classes of events class1 and class2. class1 events can be processed by either states S1 or S2 while class2 events can only be processed by state S2. A special class1 event upgrade_req requests an upgrade from sta...
Your problem is that the priority of internal transitions is higher than those defined in the transition table. And update_req being a class1, the internal transiton fires. This is actually conform to the UML standard. MSM offers you a second solution, you can define S1's internal transition with a Row with none as tar...
3,936,038
3,938,091
Vector handling bullets in DirectX
I have a vector to hold objects of a bullet class. Is this the correct way to add bullets to the vector structure? std::vector<Bullet> bullets; Bullet newbullet(thisPlayer.x+PLAYERSPRITEWIDTH,(thisPlayer.y-(PLAYERSPRITEHEIGHT/2))); bullets.push_back(newbullet); I don't think the bullets get added this way.
Thats a perfectly valid way to add "Bullet"s to a std::vector. Make sure your vector is defined outside of the scope of the function. Otherwise the vector drops out of scope and is deallocated. Some links that may help your understanding a bit: http://www.cs.umd.edu/class/sum2003/cmsc311/Notes/Mips/stack.html http:/...
3,936,212
3,936,267
C++ assign const to environment variable or default value
For an application that uses a number of environment variables, is there some kind of a convention or "best practice" when it comes to grabbing environment variables and putting them into either a struct or a bunch of const's? Obviously, I want to fallback to a default value for each and every environment variable. Rig...
How about: std::string GetEnvironmentVariableOrDefault(const std::string& variable_name, const std::string& default_value) { const char* value = getenv(variable_name.c_str()); return value ? value : default_value; } Used as: const std::string some_variable = GetEnvi...
3,936,420
3,970,887
ALSA: How to tell when a sound is finished playing
I have a c++ object that accepts sound requests and plays them with ALSA. There is thread that processes the sound requests. Some sounds are periodic and are rescheduled after the wav file contents have been written to the ALSA library. Is there a way I can find out when all the data has been played? The function snd_p...
Might not be correct (i've done very little work in this area), but from looking at the ALSA docs here: http://www.alsa-project.org/alsa-doc/alsa-lib/pcm.html It looks like snd_pcm_status_t holds the status information that should give you an indication of whether the stream is currently processing data or not.
3,936,468
3,936,573
DelayLoading a DLL and the associated .lib file
I am attempting to delay load wintrust.dll and crypt32.dll in my application (these are used to perform digital signature/publisher checks in a DLL). I am using VS2008. After adding these two DLLs as entries in the Delay Load property in the Linker section of my project properties, I still get LNK4199 warnings that not...
There is no static .lib for these. The SDK libraries are always import libraries, not static .libs because the corresponding Windows API lives in a DLL. No need to worry about this.
3,936,483
3,939,485
Why doesn't "Attach to Process" allow other transport types? VS 2008
A co-worker posted this on an MS forum but was not able to get an answer. He's using Win7, VS 2008 (C++) pro - not the express version. When he selects Tools->Attach to Process the dlg box with the dropdown for "Transport" shows only "default" and the Qualifier field is greyed out and only shows his machine name. H...
Are you sure your co-worker has VS 2008 Pro and not Standard? Standard doesn't support remote debugging.
3,936,919
3,936,962
Checking whether every list in a list is null in Common Lisp
I know that I can check whether a list of lists only contains null lists like this CL-USER> (null (find-if (lambda (item) (not (null item))) my-list)) where my-list is a list of lists. For example: CL-USER> (null (find-if (lambda (item) (not (null item))) '(nil (bob) nil))) NIL CL-USER> (null (find-if (lambda (item) (...
The higher order function every takes a predicate function and a list and returns true iff the predicate returns true for every element in the list. So you can just do: (every #'null my-list)
3,937,007
3,937,023
"Recursive on All Control Paths" error when implementing factorial function
For class I have an assignment: Write a C++ program that will output the number of distinct ways in which you can pick k objects out of a set of n objects (both n and k should be positive integers). This number is given by the following formula: C(n, k) = n!/(k! * (n - k)!) Your program should use two value-returning ...
There are two critical elements to a recursive function definition: a recursive call to itself a termination condition You appear to be missing the termination condition. How would factorial() quit calling itself forever?
3,937,093
3,937,278
Automatic inclusion of runtime library/framework into the installation package VS2008
Project1: A C++ EXE project with code generation option "runtime library" set to "Multithreaded Debug Dll". Project2: A C# EXE project developed with .Net Version, say, 3.5 Suppose I want to write an installer project for these projects. I naturally include their primary outputs (the exe's) in the installation packag...
It is already automatic afaik. Every time I tinkered with a Setup project, it already figured out the prerequisites from the projects I added. From your Setup project, use Project + Properties and click Prerequisites. Verify that the right Visual C++ Runtime Libraries and .NET Framework are ticked.
3,937,152
3,937,522
Looking for PostMessage functionality in Qt
The Win32 API has a PostMessage function that posts a message to the end of the GUI message queue to be processed later from the GUI thread, as opposed to SendMessage which sends and processes the message synchronous with the calling thread. Is there a Qt solution for PostMessage functionality? A coworker suggested tha...
Check QCoreApplication::postEvent().