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 |
|---|---|---|---|---|
4,233,711 | 4,233,976 | C++11 reflection library | I'm currently going to write big project in c++11.
I'm searching for some time good c++11/c++ reflection library and I've found several different libraries, but most of them are simply not updated for last couple of years or their functionality is very limited.
Could you tell me if there is a really good library for c+... | C++ is not really the best language for reflection. C++0x doesn't really change that. You can get limited support for static reflection using type traits, and you can even use SFINAE to statically determine whether a certain class has a particular member function or member variable. But that's really it.
Dynamic r... |
4,233,726 | 4,233,794 | Limit iterations per time unit | Is there a way to limit iterations per time unit? For example, I have a loop like this:
for (int i = 0; i < 100000; i++)
{
// do stuff
}
I want to limit the loop above so there will be maximum of 30 iterations per second.
I would also like the iterations to be evenly positioned in the timeline so not something lik... |
@FredOverflow My program is running
very fast. It is sending data over
wifi to another program which is not
fast enough to handle them at the
current rate. – Richard Knop
Then you should probably have the program you're sending data to send an acknowledgment when it's finished receiving the last chunk of data... |
4,233,922 | 4,234,550 | Why is my Profiling Class extremely slow? | I have never done profiling. Yesterday I programmed a ProfilingTimer class with a static timetable (a map<std::string, long long>) for time storage.
The constructor stores the starting tick, and the destructor calulates the elapsed time and adds it to the map:
ProfilingTimer::ProfilingTimer(std::string name)
: mLocalN... | There are a couple performance issues with your code.
You're needlessly constructing an std::string in your ProfilingTimer constructor. I would recommend using a const char* as your parameter and using a custom Twine/Rope structure to do your appends.
Why does mLocalName even exist? Just refer to name directly.
As has... |
4,233,964 | 4,236,046 | What good libraries are there for solving a system of non-linear equations in C++? | In a C++ application I'm coding, I need to solve a system of non-linear equations (N equations, N unknowns).
The systems I'm solving will be rather small (up to 10 equations/unknowns), so performance is not going to be a real issue.
I've searched the web a bit for a non-linear solver library, and I couldn't get to some... | There are two options for you, you can use the sundials packages which includes a nonlinear solver, written in C I think. The only problem I've found with it is that you need to give it good initial estimates. The second option is to use NLEQ or NLEQ2 which I think are superior (writtein in FORTRAN but easy to link to ... |
4,234,092 | 4,234,230 | Why does __int16 and int (32) generate different asm with C++? | I have started learning masm assembly recently, iv been disassembling many of my programs just to have a look. I have noticed that when you use a __int16 (word) the value of it is 1st copied into eax then into the variable itself, but with int (dword/32) it is copied directly into the variable: heres the dissembled cod... | The same results would indeed be given if the instruction were mov ax,3, but the compiler probably choose mov eax,3 because the machine code is shorter and in this particular case the effect is the same. mov ax,3 would have an extra prefix byte that tells the CPU it's a 16-bit operation. (The encoding for the two instr... |
4,234,120 | 4,234,137 | Which is faster: x<<1 or x<<10? | I don't want to optimize anything, I swear, I just want to ask this question out of curiosity.
I know that on most hardware there's an assembly command of bit-shift (e.g. shl, shr), which is a single command. But does it matter (nanosecond-wise, or CPU-tact-wise) how many bits you shift. In other words, is either of th... | Potentially depends on the CPU.
However, all modern CPUs (x86, ARM) use a "barrel shifter" -- a hardware module specifically designed to perform arbitrary shifts in constant time.
So the bottom line is... no. No difference.
|
4,234,415 | 4,234,531 | C++ Function pointers with unknown number of arguments | I need some help with C++, please!
I'm writing a command parser for a small text-based game, and I've run into some problems. The parser is supposed to read and parse commands entered by the player.
The most obvious and straightforward solution to this could be something like this (written in pseudo-code):
command <- ... | A better solution would be to have all of your functions take the same arguments. A good idea would be to first completely tokenize your input (say, into a vector of strings), and then pass that array to the functions. You could then use an associative container (such as a hash table or a std::map) to map command tok... |
4,234,426 | 4,235,779 | How to display a preview of an Image in qt? | I load an image to qt using Imagemagick and then
I have several widgets that perform various actions to an image(blur, black and white, levels etc). There is an image preview that I show to the end user every time the image is manipulated.
The problem I have is that if for example I apply some blur effects(using horizo... | I think you should keep a line of your image states (after a new effect is applied you should create a new state - a copy of an image). So you can simply roll back if you need. A List structure will be good for this purpose. Using such approach you can not only roll back, but fully implement undo-redo system.
When you... |
4,234,434 | 4,234,568 | C++ Builder or Visual Studio | I own a software development company. We develop software for other companies who brand under their name/titles. And we also have a couple self branded titles in the Accounting/ERP market. Our accounting software is roughly 60% of our business and written in C++ Builder.
Those who know, realize C++ Builder has had a... | Moving to wxWidgets has its advantages one of them being that you will not be bound to an IDE like C++Builder or Visual Studio. C++ Builder has had several problems, its main strength being the VCL framework, which in my oppinion is still among the best GUI frameworks around for C++. The problem ofcourse being that it ... |
4,234,480 | 4,234,565 | Concurrent random number generation | I'm writing a parallel program using open mp in which I generate a matrix of random floating point numbers and then do a number of calculations on it. I currently want to make the step where I generate the matrix run in parallel, but I have the problem that the rand() function was not meant to run concurrently. I don't... | If you're using C++, you should consider using the Boost library random number classes. You can create a unique PRNG instance for each thread. If you require repeatability, you can initialize each instance in your main thread with repeatably generated seed values.
UPDATE: Turns out after I wrote this, C++11 was rele... |
4,234,551 | 4,234,613 | How to implement simple tick-based engine in c++? | I'm writing a text game and I need a simple combat system, like in MUDs, you issue commands, and once in a while "tick" happens, when all those commands execute, player and monsters deal damage, all kinds of different stuff happens. How do I implement that concept?
I thought about making a variable that holds last tic... | The problem with simple action stack is that the order of actions will probably be time based - whoever types fastest will strike a first hit. You should probably introduce priorities in the stack, so that for instance all global events trigger first, then creatures' action events, but those action events are ordered b... |
4,234,661 | 4,234,721 | Reading sockets wired problem - adds some wired chars to the message | When I'm sending, for example, "1234", the server, which is C++ using SFML library reads "1234╠╠╠╠╤lσ╝╝√=♦↑עσ". When sending from C++ SFML clinet to the server it's all OK. The original client written in Onj-c with Async Socket library. WTF? (All TCP)
| It sounds like the server is assuming that the data it receives is null-terminated, but one of the clients is just sending "1234" instead of "1234\0". So the weird characters you're seeing might be whatever garbage happened to be in that part of the server's memory.
You can use a tool like Wireshark to see exactly wha... |
4,234,690 | 4,234,733 | What does the parameter type void*& mean and what's its use? | I'm looking through an API written in C++ and I'm confused as to what the following parameter type means:
void*& data
Does that mean the user would pass in a reference to a void pointer? If that's true, what's the point? I mean void* is already indirected so why would you ever want to redirect it again?
| It's tough to say without seeing it's use, but you point out that a reference is a level of indirection. Would you find it weird if it was a pointer to a pointer? Those are quite common - in fact you deal with them when accepting command line arguments and get pointers to char pointers. Another example would be if you ... |
4,234,769 | 4,234,876 | C++ templates no matching function call | I have a member function of a template class declared as such:
template <class T>
int Data<T>::getPosition(vector<T> stuff, T newStuff, bool ascending)
I call this somewhere with the line
frequencies.insert(frequencies.begin() + getPosition(frequencies, current, ascending),
frequencies[i]);
Th... | Your function prototype gets templated on Data<t>, and it looks like you're performing this call on an object with type Data<double> and passing a std::vector<int> and an int, when it probably expects a std::vector<double> and a double to correspond to the initial templated type of the Data object.
|
4,234,774 | 4,234,870 | Is this a legal way to implement impure virtual functions? | By an "impure virtual function", I mean pure virtual functions that also have implementations (as described at http://www.gotw.ca/gotw/031.htm) for diagnostic purposes.
The kosher way to implement them is to do:
class Foo
{
public:
...
virtual void Bar() = 0;
};
void Foo::Bar() { assert(false); }
But this is ... | No, it's not legal. The one definition rule says that a class can have multiple definitions in a program (from different translation units), but those definitions must all consist of identical sequences of tokens (3.2/5). ABSTRACT_METHOD is a preprocessing token (prior to macro replacement), but that's not good enough.... |
4,234,847 | 4,234,937 | Dilemma about using Pointers to member functions | I have to set a function pointer in a library API, such that it calls that function whenever it needs to perform a particular action.
int (*send_processor)(char*,int);
int setSendFunctor(int (*process_func)(char*,int))
{
send_processor = process_func;
}
In my main source, I have this function defined a... | My usual way of handling this issue is to create a static function in my class that takes an explicit this pointer as a parameter and then simply calls the member function. Sometimes the static function instead needs to closely follow the type signature the C library expects for a callback, in which case I cast the vo... |
4,235,012 | 4,235,616 | Best STL data structure to find unordered elements | I'm currently trying to implement a hash table in C++ for a homework...
I've chosen to use internal linking as a solution for collisions in the table...
and I'm looking for a good STL container that will find a specific entry in an unordered set of data.
I can't use an stl container that is based on trees (set, map, tr... | As you're saying I assume the buckets can get big..., it's better to use std::list. Searching is linear in both cases, but adding elements is constant in std::list.
I guess they're all the same, since data isn't ordered - No, they are not. If they were, there would be just one container. Each container has it's own a... |
4,235,112 | 4,235,159 | Entering values from stringstream | Is there a while loop that allows me to enter in all the values for a stringstream into some datatype? For example:
stringstream line;
while(/*there's still stuff in line*/)
{
string thing;
line >> thing;
//do stuff with thing
}
| Yes:
std::stringstream line;
std::string thing;
while (line >> thing)
{
// do stuff with thing
}
if (line.fail())
{
// an error occurred; handle it as appropriate
}
Stream operations (like >>) return the stream; this is what allows you to chain stream operations, like:
line >> x >> y >> z
A stream can be use... |
4,235,128 | 4,238,152 | Windows Safe Mode runs simple programs (at least) 3 times faster? | While doing a lot of benchmarking stuff these days, I stumbled upon something very disturbing / interesting / new to me. After doing some research getting more and more to the point (which i couldnt believe), it seems that windows xp (and probably all other versions as well) runs programs around 3 times as slow as in s... | Fairly sure that this is something special with your computers.
I ran that code, compiled with MSVC 10 in Release mode, on an old XP netbook and it's a little faster in normal mode than in safe mode for me, not measuring very carefully, but it took about 8 seconds in normal mode and 10 seconds in safe mode.
A bit sur... |
4,235,235 | 4,235,240 | Sign of a floating point number | Is there an easy way to determine the sign of a floating point number?
I experimented and came up with this:
#include <iostream>
int main(int argc, char** argv)
{
union
{
float f;
char c[4];
};
f = -0.0f;
std::cout << (c[3] & 0x10000000) << "\n";
std::cin.ignore();
std::cin.get();
return 0;
}
where (c[3... | Assuming it's a valid floating point number (and not, for example, NaN):
float f;
bool is_negative = f < 0;
It is left as an exercise to the reader to figure out how to test whether a floating point number is positive.
|
4,235,306 | 4,235,386 | Strange Pattern: all functions/methods return error-code using the same type in C++ | In my last two projects I've seen the strange guideline, "All Methods/Functions should return error-code using some common ERROR_CODE type". In both projects ERROR_CODE is an int typedef.
Is there any good reason doing it in C++? Some MISRA requirement or something like that?
I can see only disadvantages:
If a functio... | I think it's a very bad style for several reasons.
Like you've said, it forces you to pass pointers/references to store the actual result of a function.
Like you've said, the unified error code is ugly because it's trying to unify all sorts of errors from all sorts of domains.
It creates an artificial dependency of al... |
4,235,510 | 4,235,704 | Get Unhandled exception at 0x00f85069 | my program breaks and says this
Unhandled exception at 0x00f85069 in Monopoly.exe: 0xC0000005: Access violation writing location 0x0000000c.
i made a win32 wrapper. i have two WndProc one is static and the other one not. the static WndProc calls the nonstatic WndProc. when i try to get messages it works fine but when... | How are you creating your window? Did you pass a valid pointer to an instance of Window to your CreateWindow() or CreateWindowEx() function via the lpParam parameter? For example, if your window wrapper has a Create() function or something like that:
void Window::Create()
{
/* ... */
// Pass a pointer to ourse... |
4,235,599 | 4,235,627 | C++ reference & const pointers in C/C++ | Recently while I was explaining the basic difference between pointers and references(in context of C++ programming) to someone, I told the usual explanations which talk about different function argument passing conventions - Call by value, Call by pointer, Call by reference, and all the associated theory about referenc... | There are two typical use-case scenarios:
First: Pointers denote optional arguments. Since, references cannot be NULL, but pointers can, document in the coding style that any argument that is notated as pointer, may be NULL, the function needs to handle that. Optional arguments can then be const or non-const, as can ma... |
4,235,747 | 4,235,757 | Cross platform simple TCP/ IP API? | I'm making a simple cross platform chat program. I'm using wXWidgets for the GUI which works well, but I need a way to create a socket and to create a server client setup. Is there an API that for example underlying uses WinSock on Windows, and Linux's native socket and osx's?
I'm not looking for boost as a solution be... | The QtNetwork module
|
4,236,314 | 4,236,497 | OpenCV jpeg format image in memory | Is there a possibility of saving an image to a string instead of a file with OpenCV?
I have found just this function in the docs:
int cvSaveImage(const char* filename, const CvArr* image)
And it can only save to files.
| How did you want to code the image in the string?
You could just store red,green,blue values as comma separated strings but coding the image binary as something like base64 would be more compact.
Edit: if you mean a jpeq format in memory see - OpenCV to use in memory buffers or file pointers
|
4,236,384 | 4,236,397 | How does this function definition work? | I generated a hash function with gperf couple of days ago. What I saw for the hash function was alien to me. It was something like this (I don't remember the exact syntax) :
unsigned int
hash(str, size)
register char* str;
register unsigned int size;
{
//Definition
}
Now, when I tried to compile with a C++ co... | 1. C++ is not a superset, although this is not standard C either.
2/3. This is a K&R function declaration. See What are the major differences between ANSI C and K&R C?
.
4. gperf does in fact have an option, -L, to specify the language. You can just use -L C++ to use C++.
|
4,236,461 | 4,236,467 | c++ linux compile error: undefined reference to `main' | I have looked for this error and tried a few of the solutions, but have not found anything, at this point I would just like to compile it.
The error I am getting is:
/usr/lib/gcc/i486-linux-gnu/4.4.1/../../../../lib/crt1.o: In function `_start':
/build/buildd/eglibc-2.10.1/csu/../sysdeps/i386/elf/start.S:115: undefined... | You have declared main() as a member function.
The main() function called when the application starts up needs to be a non-member function in the global namespace.
A good introductory C++ book would explain this.
|
4,236,473 | 4,236,481 | Do you see any kind of problem with this C++ code? | class A
{
public:
A(){}
~A(){}
void DoSomething(int x){}
};
void func(int i)
{
A *pa = new A();
pa->DoSomething(i);
delete pa;
}
Do you guys see any problem with this code?
I can only see following two:
func is only operating on object of class A and should be made member of A.
object of c... |
object of class A should be created on the stack instead of heap.
Yes, pa should be created as an automatic variable (on the stack) instead of dynamically (on the heap).
However, it's also wrong as written because it isn't exception-safe. If pa->DoSomething(i) throws an exception, you will leak the object pointed to... |
4,236,525 | 4,236,555 | Can't strip all unneeded symbols on a Mac OS X c++ application? | I'm trying to strip my mac os x application of all unneeded symbols. If I do this on my linux app using "--strip-unneeded" the symbol table on my application is empty and returns nothing.
On Mac OS X, I am seeing symbols related to the typeinfo and vtable entries for my classes, as well as some function. As best as I... | Don't have a definite solution (I'm still in the process of learning C++ (and Objective C++) and learning to deal with this stuff myself) but you could look over:
Visibility of Inline Functions
and
Technical Note TN2185: C++ Tips and Tricks for Mac OS X
What's the current setting for "Inline Methods Hidden"? (Double-c... |
4,236,526 | 4,239,937 | Looking for a High Level C++ SSL Library | I checked out quite a few SSL librarys tonight. OpenSSL looks good but lacks documentation, as most of them do. I thought I hit the jackpot when I found NetSieben's SSL C++ Library (http://www.netsieben.com/products/ssh/index.phtml) but after hours, I am unable to get it to compile. It says it needs Botan's lib, but ab... | You might like CyaSSL, which is another SSL implementation. You can download it at http://www.yassl.com.
|
4,236,736 | 4,236,744 | Do I need to nullify a member variable in the destructor? | Why one would want to explicitly clear the a vector member variable (of on in a dtor (please see the code below). what are the benefits of clearing the vector, even though it will be destroyed just after the last line of dtor code will get executed?
class A
{
~A()
{
values.clear();
}
private:
std::vector < doubl... | In class A, there is absolutely no reason to .clear() the vector-type member variable in the destructor. The vector destructor will .clear() the vector when it is called.
In class B, the cleanup code can simply be written as:
delete p_;
There is no need to test whether p_ != NULL first because delete NULL; is defined... |
4,236,747 | 4,236,820 | Visual Studio C++ linker warning: LNK4006 with C Run-Time (CRT) | I'm going to ask this question, and then answer it myself.
I'm, aware that its a newbie question, but as it took me approx. two days to find the correct answer, I'll post it anyway.
So much for disclaimers - this one is dedicated to all you newbies out there:
I've go an MFC project in VS 2010, and I needed to add some... | My happy ending is that I've stumbled across the correct answer in Microsoft support article: How to link with the correct C Run-Time (CRT) library .
Apparently, I violated the following rule, as stated in the articel:
A reusable library and all of its users should use the same CRT library types and therefore the sam... |
4,236,853 | 4,236,868 | Floating Point Exception C++ Why and what is it? | I'm building a program for the Euler projects question 3, and while that might not really matter as a result I'm current trying to make this code take a number and test if it is prime or not. Now then before I get to troubleshoot the function it gives me the error "floating point exception" right after inputting the nu... | A "floating point number" is how computers usually represent numbers that are not integers -- basically, a number with a decimal point. In C++ you declare them with float instead of int. A floating point exception is an error that occurs when you try to do something impossible with a floating point number, such as divi... |
4,236,942 | 4,237,038 | Qt/C++: Getting the data at a certain cell in a QTableView | I'm trying to get the text at a certain cell in a QTableView. For example:
QString codestring = "*" + ui->tblInventory->indexAt(QPoint(0,2)).data().toString() + "*";
This should get the text at the cell in column 0 row 2 in my QTableView. The problem is, that's not what it's doing!. Regardless of the arguments I pass ... | Resolved with:
ui->tblInventory->model()->data(ui->tblInventory->model()->index(0,2)).toString()
Not quite sure why the above doesn't work, but this does. Thanks for the help.
|
4,237,040 | 4,238,172 | What are the purpose of api specific typedefs such as GLsizei GLint GLvoid? | What are the purpose of api specific typedefs such as GLsizei GLint GLvoid?
I see this everywhere in c and c++ code. Basic types are often typdefed with the libraries prefix/suffix. What's the reasoning behind this? Is this good practice? Should my programs be doing something similar themselves?
At first glance it seem... | It's not about shortening the names, but about portability. Different platforms will need to typedef those things differently.
In Std-C, long may be 32 or 64 bits, depending on your compiler/target, so it can't be safely assumed to be a certain size. A library author will thus typedef his own type, guaranteeing a certa... |
4,237,202 | 4,237,210 | Enum declaration in Eclipse | I'm compiling a c++ project in Eclipse, Linux.
The project was compiled in Windows in the past.
I have my declaration of enums like this:
enum nameofenum:UINT32
{
one=0,
two=1
}
The result is an error in eclipse.
What is the meaning of :UINT32?
How can I switch this declaration to Linux?
Thanks!!
| That looks like a strongly typed enum, which is a C++0x feature. Basically, it specifies the underlying type of the enumeration, so one and two will be UINT32s.
To compile it, you need a compiler that supports this particular part of the C++0x language. I believe GCC 4.4 and Visual C++ supports strongly typed enums to... |
4,237,256 | 4,237,272 | Efficient way to sort a concatenation of lists (STL), merge sort hint, partially sorted | I have a situation where I get a list of values that are already partially sorted. There are N blocks in my final list, each block is sorted. So I end up having a list of data like this (slashes are just for emphasis):
1 2 3 4 5 6 7 8 / 1 2 3 4 5 / 2 3 4 5 6 7 8 9 / 1 2 3 4
I have these in a vector as a series of poin... | You could try std::merge, although this algorithm can only merge two sorted collections at a time, so you would have to call it in a loop. Also note that std::list provides merge as a member function.
EDIT Actually std::inplace_merge might be an even better candidate.
|
4,237,387 | 4,237,652 | Making QGraphicsScene bigger when a graphic item is placed against its border | I've made a QGraphicsScene with a mouseClickEvent that lets the user create blue squares inside of it. But I want to make the scene grow when an item is placed against its border so that the user never runs out of space on the graphics scene.
What's the best way to make a graphics scene bigger in this case?
| I suggest doing something like the following:
Get the bounding rect of all items in the scene using QGraphicsScene::itemsBoundingRect().
Add some padding around that rect to make sure the bounds of the items won't hit the edge of the view. Something like myRect.adjust(-20, -20, 20, 20) should be sufficient.
Use QGraph... |
4,237,428 | 4,237,442 | Two-dimensional array (matrix) memory allocation troubles | I have few lines of C++ code which has simple purpose - to store a matrix in two-dimensional array and not consume more memory, than is needed. This means I have to allocate memory for each number in matrix before putting it in matrix.
#include <cstdlib>
#include <cstdio>
using namespace std;
int main() {
int ** ... | You're code is almost correct, but the matrix allocation is wrong. You are allocating space to store a single int * while you try to initialize two elements (matrix[0] and matrix[1]) :
matrix = (int**)malloc(2 * sizeof(int *));
The outer printing loop is wrong : there are only 2 "lines" in the matrix (with 3 columns e... |
4,237,439 | 4,237,839 | Symlinks and File Redirection | In C++, how would I go about checking if a file that we are opening is being redirected through Symlinks? Here is my file opener handler:
f=fopen(addr.c_str(), "rb");
Thanks in advance
| If you use stat(), it will automatically follow the symlink. If you use fstat(), the symlink will have already been followed as the file will have been opened to get the file descriptor.
lstat() is preferable over stat() and fstat() in this particular case as it does not follow the symlink. After calling lstat(), the... |
4,237,660 | 4,237,798 | Why does the Visual Studio conversion wizard 2010 create a massive SDF database file? | I've opened a 2009 C++ sln in 2010 and run the Visual Studio 2010 conversion wizard. It seems to have done the conversion fine, but there's a 60 MB .sdf file created with the same name as my .sln file (apart from extension)! There was no sdf file before. I'm pretty sure when I've used the wizard on C# projects this fil... | It is the code browser database, it replaces the NCB file in earlier releases. In VC++ 2010 the intellisense and browsing features have been completely redesigned to provide greater functionality and accuracy.
|
4,237,817 | 4,238,875 | Configuring Vim for C++ | I would like to make vim my C++ editor. I have very little experience working with it
and need help in configuring vim to work with C++.
I need such features as
code-complete (for stl and for my classes)
switching between .cc and .h files
may be some more tricks you, C++ and vim gurus, have.
May be you could provid... |
Code complete: Omni completion or Clang autocomplete or YouCompleteMe
Real time syntax checking: Syntastic
Switching between source and header file: A plugin
Snippets: Snipmate or UltiSnip
Search for reference of variables, functions, classes, etc.: Cscope
Go to definition: Ctags or part of YouCompleteMe subcommands m... |
4,237,818 | 4,293,390 | BFS algorithm - shortest walk on grid with constrained steps | The problem is as follows: A wanderer begins on the grid coordinates (x,y) and wants to reach the coordinates (0,0). From every gridpoint, the wanderer can go 8 steps north OR 3 steps south OR 5 steps east OR 6 steps west (8N/3S/5E/6W).
How can I find the shortest route from (X,Y) to (0,0) using breadth-first search?
C... | I'm going to go ahead and answer my own question for future reference.
Psuedocode:
while (true) {
if (destination reached)
break;
addToQueue(go north);
addToQueue(go south);
addToQueue(go east);
addToQueue(go west);
getNextFromQueue;
}
It should also be noted that the execution time for... |
4,238,025 | 4,238,036 | Linked list of different classes - in a maintanable way? | Yo people,
My problem is, I have to find a way to easily maintain the next situation:
I have a linked list of different classes. I use void pointers, every class has "int type" as its first member.
Now when I want to call a class member function, I have to do this:
- Read the int, so I know the type of the class.
- I c... | If you find yourself writing code like "if A is of type X, then do something, and if it's of type Y, then do something else", then you are likely to be able to use polymorphism: introduce an abstract base class for those.
You would then have the list of objects of that abstract base class, and on each object you'd call... |
4,238,029 | 4,242,994 | OpenCV: how to be capable to capture frames from same camera with 2 different apps? | So I have 2 diffrent apps that use web-cameras (on Windows) I created tham bouth but I need them to be separate, stand alone apps. I want tham bouth to be capable to capture from same camera. What should I add to my capturing OpenCV code?
| You can't. Only one application can access any device at a time - even with common I/O devices like hard disks.
If multiple applications could access a device simultaneously, it would be confused whose instructions to follow.
You can use SplitCam, though. It will connect to the webcam (and no other application can). Bu... |
4,238,063 | 4,239,059 | Is an "if(...) return ...;" without "else" considered good style? | This code:
if( someCondition )
return doSomething();
return doSomethingElse();
versus this code:
if( someCondition )
return doSomething();
else
return doSomethingElse();
In essence, they are the same, but what is best style/performance/... (if there is any non-opinionated part to the answer of course)? A... | When you have multiple return statements in a function, this is referred to as "early return." If you do a Google search for "early return" you will find link after link that says it is bad.
I say nonsense.
There are two primary reasons and one secondary reason that people claim that early return is bad. I'll go thro... |
4,238,122 | 4,238,167 | Hash function for floats | I'm currently implementing a hash table in C++ and I'm trying to make a hash function for floats...
I was going to treat floats as integers by padding the decimal numbers, but then I realized that I would probably reach the overflow with big numbers...
Is there a good way to hash floats?
You don't have to give me the ... | It depends on the application but most of time floats should not be hashed because hashing is used for fast lookup for exact matches and most floats are the result of calculations that produce a float which is only an approximation to the correct answer. The usually way to check for floating equality is to check if it ... |
4,238,141 | 4,238,173 | how to initialize function arguments that are classes with default value | I'm working on Linux gcc environment and I need to initilize function arguments that are classes with default values.
When I do that with temporary instance of the class it makes an error like this: "default argument for [function argument] has type [class name].
for example:
void foo(std::wstring& str = std::wstring()... | This is supposed to not compile. You are trying to bind an rvalue to a non-const reference. Say std::wstring const & str and it should work.
|
4,238,204 | 4,238,240 | Is it possible to mix template-derived C++ classes with Qt's Q_OBJECT? | In my application, I have the following class hierarchy:
class Word
{
...
}
template <typename T> class Dictionary
{
...
};
class WordDictionary : public Dictionary<Word>
{
Q_OBJECT
...
}
The WordDictionary class parses a dictionary which takes a long time. I am running the parsing function from wit... | You can't do this directly but there are usable work-rounds. See the article here.
While it is theoretically possible for
moc to handle templates, it would be
extremely complex to implement, and
would be highly impractical to use:
For each template instantiation, moc
would have to generate the appropriate
... |
4,238,282 | 4,238,290 | Do you really need a main() in C++? | From what I can tell you can kick off all the action in a constructor when you create a global object. So do you really need a main() function in C++ or is it just legacy?
I can understand that it could be considered bad practice to do so. I'm just asking out of curiosity.
| If you want to run your program on a hosted C++ implementation, you need a main function. That's just how things are defined. You can leave it empty if you want of course. On the technical side of things, the linker wants to resolve the main symbol that's used in the runtime library (which has no clue of your special i... |
4,238,384 | 4,238,392 | Java equivalent of cin (C++) | how would you code this in Java?
char c;
int n;
cin >> c >> n;
So that I can get this kind of inputs:
X123123
| You can use Scanner with System.in. E.g.
Scanner s = new Scanner(System.in);
char c = s.findInLine(".").charAt(0);
int n = s.nextInt();
|
4,238,395 | 4,238,409 | Unique word count in C++ help? | I would like to do a function which can count the unique words. For example:
"I like to program something useful. And I like to eat. Eat ice-cream now."
In this case, each unique words:
I occurs 2
like occurs 2
...
I will ignore the case later on. Please help
EDIT:
I have finished write the functions. It works perfect... | Sounds like you want to use an std::map with a key string and data of int.
If an item doesn't exist in the map already you add it with an int value of 1. If the item does exist in the map already you simply add 1 to its associated value.
|
4,238,565 | 4,238,587 | what is a virtual method in c++? | what is a virtual method in c++?
| A virtual function allows derived classes to replace the implementation provided by the base class. The compiler makes sure the replacement is always called whenever the object in question is actually of the derived class, even if the object is accessed by a base pointer rather than a derived pointer. This allows algor... |
4,238,697 | 4,240,279 | How do I move a QPixMapImage around a qgraphicsview | I can add a QPixMapImage to a QGraphicsScene, but then I have two issues.
First I cannot create a pointer to my QPixmapItem declared in the header, where i can with QGraphicsScene.
I get an error "error: no matching function for call to 'QGraphicsPixmapItem::QGraphicsPixmapItem(MainWindow* const)" ... When I create my ... | Issue #1:
There error you're getting means there is no such constructor declared for QGraphicsPixmapItem; you use either one of these:
QGraphicsPixmapItem(QGraphicsItem *parent = 0
#ifndef Q_QDOC
// ### obsolete argument
, QGraphicsScene *scene = 0
#endif
);
Q... |
4,238,710 | 4,238,740 | Specializing template for enum | Could anyone tell me why this doesn't work?
enum CompCriteria{ByKey,ByValue,ByeKeyAndValue};
template<class T>
struct X;
template<>
struct X<CompCriteria>
{
};
int _tmain(int argc, _TCHAR* argv[])
{
X<CompCriteria::ByeKeyAndValue> x;
return 0;
}
| You have specialized X for a type, but you're trying to use it with the integer CompCriteria::ByeKeyAndValue.
You can specialize template class for the enum CompCriteria underlying type - int in this case, as follows:
enum CompCriteria{ByKey,ByValue,ByeKeyAndValue};
template<int>
struct X;
template<>
struct X<ByeKeyA... |
4,238,978 | 4,254,643 | How to use cv::imencode on IplImage? | I have an image saved in a variable fo type IplImage like this:
IplImage* fIplImageHeader;
fIplImageHeader = cvCreateImageHeader(cvSize(width, height), 8, 3);
fIplImageHeader->imageData = (char*) memblock;
How can I use the cv::imencode function on that image?
cv:imencode looks like this:
bool imencode(const string& e... | See my other question:
OpenCV - could not find encoder for the specified extension
Where I have solved the problem.
|
4,239,113 | 4,239,162 | Iterating over lines in a string? | I am trying to do something like this:
BOOST_FOREACH (const std::string& line, allLinesOf(someFileLoadedIntoString))
{
...
}
I wonder how to implement the allLinesOf function? Thanks!
UPDATE: Thanks for the answers. Sorry but I forgot to mention one important detail: in my case the newlines are \r\n.
| You can use std::getline.
std::string line;
while(std::getline(file, line)) {
// Ohai!
}
|
4,239,196 | 4,239,259 | Getting absurd errors in using template template arguments | I have been trying to create a templated class(Test2) that takes 2 template arguments,Type1 and Type2. It is known that the second argument would also be a templated class that takes 2 template arguments(TypeA and TypeB).
Now, for constructing an object of Test2, I want the user to be able to use either of 2 types of c... | It doesn't work like that. Test<int, char> is a full blown type, instead of a template. So you need type parameters
template<class Type1,
class Type2 >
struct Test2
{
Type1 t1obj;
Type2 t2obj; //Line 17
Test2(const Type1& t1,
const Type2& t2) //Line 20
: t1obj(t1), t2obj(t2) { st... |
4,239,224 | 4,239,240 | How to draw a round corner window a border? | in win32, we can use SetWindowRgn to give the window a round corner, how to draw a border for this rigon? it's not a rect.
| Handle the WM_NCPAINT message and you can draw the window frame and borders by yourself.
|
4,239,253 | 4,239,291 | C++: Is it possible to use a reference as the value in a map? | Is it possible to use a reference as the value in a standard map container in C++?
If not - why not?
Example declaration:
map<int, SomeStruct&> map_num_to_struct;
Example usage:
...
SomeStruct* some_struct = new SomeStruct();
map_num_to_struct[3] = *some_struct;
map_num_to_struct[3].some_field = 14.3;
cout<<some_struc... | No. STL container value types need to be assignable. References are not assignable. (You cannot assign them a different object to reference.)
|
4,239,336 | 4,239,355 | When is the v-table created for a class? | I know that, how to implement virtual function call resolution is not part of C++ standrads nor it says anything about vptr or v-table, but let me ask this question here.
I've heard that v-table is a common technique used by compilers to implement virtual function call resolution. My understading about this is that the... | The v-table is statically allocated and is never deleted, nor is it explicitly allocated. The pointers within any given specific object are constants.
|
4,239,454 | 4,239,516 | Why am I getting error C2061 (syntax error: identifier)? | Okay... I've been wrestling this error for at least an hour now. I have my StaticSprite class inherit from my Component class. However, when I try to instantiate a StaticSprite instance, I get error c2016.
Here's my relevant code, I'll post more if need be.
Thanks in advance.
StaticSprite.h
#ifndef STATICSPRITE_H_
#def... | What is the point of the declaration class Component; if you include Component.h, anyway? You cannot inherited from an incomplete type, so this declaration makes no sense.
A wild guess is circular include issues, but it's really hard to tell without more information. I recommend reading this article on Organizing Code ... |
4,239,498 | 4,239,945 | Is it possible to trace Xcode C++ compile dependencies? | I'd like to identify all the include files of a particular file that I chose as a starting point in a C++ project, and then all the include files of those include files and so on until I have everything that I require to compile the file I chose as my starting point.
The background: I am trying to take a file from the ... | I'm not aware of any support in Xcode itself for doing this. However, it's not too difficult to do yourself, especially if it's only one file you're interested in.
You can add the -E flag to g++ to have it stop after preprocessing your source file. The preprocessed source file will have comments mentioning all the #inc... |
4,239,509 | 4,239,525 | Tokenizing String C++ compiler/logic error | At the following first line of code I get this
error: cannot convert ‘std::string’ to ‘char*’ for argument ‘1’ to ‘char* strtok(char*, const char*)’
void ToToken( ) {
TokenLine.reserve(30);
char * tmp;
TokenLine[0]= strtok (Line," ");
while(tmp!=NULL)
for(int i=0;i<TokenLine.size();i++){
... | strtok needs mutable C string, not std::string. To get a C string from std::string use c_str() method. However you should not pass it to strtok because it should not be changed. You'll need to make a copy of the string.
In order to create a copy possible way would be:
std::string strToTokenize;
char * tmpStr = new char... |
4,239,549 | 4,239,592 | Should shortcuts, brevity, and cleverness be routinely skipped in favor of clarity? | This question came to mind after seeing this simple piece of code:
if (!x%y)
{
// do something
}
Maybe it's the influence of early C books (K&R?), but isn't the following always preferred, if not as cute?
if (x%y != 0)
{
// do something
}
| This quote answers your question.
"Debugging is twice as hard as writing
the code in the first place.
Therefore, if you write the code as
cleverly as possible, you are, by
definition, not smart enough to debug
it." – Brian W. Kernighan
|
4,239,566 | 4,239,711 | How to setup a makefile in eclipse (C++)? | I have a project in Eclipse and I want to use my own makefile.
I went to
project -> properties -> C/C++ Build
and unchecked "Generate Makfiles Automatically". I have a makefile named Makefile in the project base dir which just contains:
all:
g++ *.cpp -o Simulator.exe
When I try to build, I get the following er... | You probably don't have MINGW configured properly, and Eclipse can't run "make". This might be useful: Setting up a compiler
|
4,239,646 | 4,239,667 | Questions about a array of pointers in c++ | Hi there i have some questions about pointers and arrays in c++:
when i want to pass an array of pointers in a function i must write:
foo(test *ptest[])
right?
when i want to delete a array of pointers, does
delete ptest;
all for me?
when i pass a pointer to another class and the first class make a delete, the point... | First of all, forget about arrays and pointers and tell us what you really want to achieve. You are probably better off using std::vector<T> and pass that around by (const) reference, saving you all the headaches of manual resource management and crazy array-to-pointer-decay rules inherited from C.
Now to answer your q... |
4,239,686 | 4,239,788 | Code's not compiling because of nested anonymous blocks? | (Taken from Accelerated C++)
Why does the following code not work:
#include <iostream>
#include <string>
int main() {
{
const std::string s = "a string";
std::cout << s << std::endl;
{
const std::string s = "another string";
std::cout << s << std::endl;
}
... | You appear to be linking against 2, or more, object files (or .a files) that define the same things. If you link against one or the other your linker problem will go away.
|
4,239,695 | 4,239,728 | string::find returning a value of -1 when it's expected to return a value of 0 [C++] | I have the following code that doesn't work:
string line;
string line_sub;
size_t open_tag_start;
const string open_tag = "<image>";
const int open_len = open_tag.length() + 1;
open_tag_start = line.find(open_tag);
line_sub = line.substr(open_tag_start, open_len);
When I try to run this code, I get the following erro... | Unless you've left out some code, line is an empty string, so of course find fails. It is your expectation that is in error, not the find function—that's all!
As a side note, you don't need to compensate for '\0' when using C++ strings. Get rid of the + 1.
|
4,239,770 | 4,239,823 | What are the rules governing C++ single and double precision mixed calculations? | For example, these variables:
result (double)
a (double)
b (float)
c (float)
d (double)
A simple calculation:
result = a * (b + c) * d
How and when are the types converted and how do I figure out what precision each calculation is performed at?
| All operations are done on objects of the same type (assuming normal arithmetic operations).
If you write a program that uses different types then the compiler will auto upgrade ONE parameter so that they are both the same.
In this situations floats will be upgraded to doubles:
result = a * (b + c) * d
float tmp... |
4,239,809 | 4,239,924 | What is the purpose of __in __out __in_opt __allowed(), how do they work? Should I use similar constructs in my own code? | Some of these Preprocessor definitions are in the WinMain function and other windows library functions. What is their purpose? How do they work? and is it good practice to write them into your implementations or function calls?
My initial research suggests they're simply set up equlivalent to:
#define __in
#define __... | They are SAL annotations in the Source-code Annotation Language. Microsoft tooling depends on it. The MSDN Library article is here. A good example is Code Analysis. Another quite unrelated tool, but empowered by these annotations is the Pinvoke Interop Assistant.
|
4,239,860 | 4,239,885 | How do I rotate a gluCynlinder in OpenGL? | For context, I'm trying to model a simple 1x1 lego brick in OpenGL. I setup my camera to look at the origin and 'up' is in the Y direction. I'm trying to draw a cylinder for the little nub on the cube, and cannot figure out how to rotate it. C++ code:
//draw cylinder
glPushMatrix();
glTranslated(0.0, 0.4 , 0.0);
//glRo... | Worked well for me:
glPushMatrix();
GLUquadricObj * qobj = gluNewQuadric();
glTranslated(0.0, 0.4 , 0.0);
glRotatef(angle * 10, 0.0f, 1.0f, 0.0f);
gluCylinder(qobj, 1.24, 1.24, 1.18, 16, 16);
gluDeleteQuadric(qobj);
glPopMatrix();
No matter which order of glRotate and glTranslate i've used.
|
4,239,867 | 4,240,746 | Adding xmllite.lib to Visual Studio 2008 | I'm trying to compile an Intel Appup sample program 'SlideshowexampleApplication', which requires Xmllite.lib. I searched and see that I'm supposed to add this file to the linker options in Visual Studio 2008, but I don't see the linker option under Project properties->Configuration properties. I tried adding 'C:\Prog... | It sounds like the sample app is using a relative path for the library file, prepending XMLLite\Lib to the library filename.
This could be happening as a result of a #pragma in the sample app code, can you run findstr on the source code to see if there are any references to XmlLite.lib?
http://msdn.microsoft.com/en-u... |
4,239,895 | 4,240,004 | Forward Declarations/Includes with Template Classes - "invalid use of incomplete type" | I am trying to make a template class where there is a function that takes in a specific instance of that template. I have made the following contrived example to illustrate this.
Let's say, I have a world of Individuals marked with a templated (generic) type of Data. I have a specific Individual, called a King. And all... | Your two classes King and Individual are very tightly coupled.
Having it in two headers like that won't work because both need each other.
If your classes have to be designed that way then:
First define class Individual but do not implement KneelBeforeTheKing, just declare that function.
Then define King
Then implemen... |
4,240,111 | 4,240,128 | error C2229: class 'VectorRemake<T>' has an illegal zero-sized array | template <class T>
class VectorRemake
{
private:
T* list[];
int count;
int capacity;
public:
VectorRemake() :capacity(DEFAULT_CAPACITY) :count(0) {list = new T[capacity];}
VectorRemake(int capacity) :capacity(capacity) :count(0) {list = new T[capacity];}
~VectorRemake() {delete [] list;}
...
}... | It's not the constructor. It's T* list[] which defines a member list as an array of pointers to T without giving the array's size.
You probably want T* list; instead.
Also note that, according to the Rule of Three, your class, having a destructor, will also need a copy constructor and an assignment operator.
Implement... |
4,240,138 | 4,240,515 | How to deserialize a class hierarchy without a class enumerator | I'm using this approach to serialize and deserialize a class hierarchy:
// Enumeration of classes.
struct Type {
enum TypeEnum { A, B }
TypeEnum t;
Type(TypeEnum te) : t(te) { }
bool operator == (TypeEnum te);
void saveToStream(Stream& stream);
void loadFromStream(Stream& stream);
};
... | This seems like a good candidate for a Factory Pattern.
Basically, it consists of delegating the responsibility of instantiating the correct type based on a given identifier. A search on Stack Overflow brought up this answer which provides a nice example of implementation in C++. Note that all objects that can be creat... |
4,240,431 | 4,240,474 | Valgrind C++ memory leaks | I have this demonstrable piece of code:
#include <cstdlib>
#include <cstdio>
int main() {
int ** matrix = NULL;
int c = 1, input = 0;
printf("Enter first row of the matrix:\n");
while (!feof(stdin)) {
input = fgetc(stdin);
matrix = (int**) realloc(matrix, 1 * sizeof (int*));
i... | matrix[0] = (int *) realloc(matrix[0], c * sizeof (int));
You are passing matrix[0] as a parameter without initializing it beforehand.
|
4,240,439 | 4,240,738 | How do I know it's a valid gdi region handle? | or other gdi handle, such as pen brush. how do i know is it valid?
| You should never get yourself into a situation where you might be holding onto a handle that isn't valid. If necessary, set the handle to NULL after calling DeleteObject() so it is completely obvious. Assuming that a GDI function will give you a FALSE return value because you passed a bad handle isn't safe.
|
4,240,547 | 4,240,587 | error C2955: 'ListRemake' : use of class template requires template argument list | template <class T>
class ListRemake
{
...
friend ostream& operator << (ostream& out, const ListRemake& obj);
};
template <class T>
ostream& operator << (ostream& out, const ListRemake& obj)
{
for (int i = 0; i < obj.size; i++)
out << obj[i] << '\n';
return out;
}
Gives the error C2955: 'ListRe... | Replace
ostream& operator << (ostream& out, const ListRemake& obj)
with
ostream& operator << (ostream& out, const ListRemake<T>& obj)
|
4,240,554 | 4,240,578 | C/C++ getting struct size | Today, with my great surprise, I discovered that
When the sizeof operator is applied to a class, struct, or union type, the result is the number of bytes in an object of that type, plus any padding added to align members on word boundaries. The result does not necessarily correspond to the size calculated by adding t... | What you want is the #pragma pack command. This allows you to set the packing to any amount you want. Typically you would set the packing value to 1 (or is it 0? ) before your structure definition and then return it to the default value after the definition.
Note that this does not do anything to guarantee portabilit... |
4,240,615 | 4,240,734 | C++ LibCurl to Send HTTPS Request | I have a plugin that I have been using for quite some time, and it basically just uses Sockets to send a request. The problem is, when you use the plugin on a game server, you have to login to SteamCommunity.com on the machine first to store the cookie. I want to convert it to C++ to alleviate that step by connecting t... | You appear to be sending a user header and probably want CURLOPT_HTTPHEADER. You should use curl's slist to create this.
If you want to write in C++ by the way rather than C you should learn to use strings properly. As it is you cannot write into a const char *, but using new with a "hope it's big enough" buffer size i... |
4,240,727 | 4,240,870 | about custom window title bar in win32 programming | How to prevent paint client area in wm_ncpaint.
| AFAIK during processing of WM_NCPAINT the client area isn't painted.
Did you mean title bar (instead of client area)? If so - it seems you should process the WM_NCPAINT in your custom way, doing what's necessary.
|
4,240,756 | 4,240,773 | How to get a C-string out of a string that contains \0 without losing the \0 | I currently have a pretty huge string. I NEED to convert it into a C-string (char*), because the function I want to use only take C-string in parameter.
My problem here is that any thing I tried made the final C-string wayyy smaller then the original string, because my string contains many \0. Those \0 are essential, s... | You cannot create a C-string which contains '\0' characters, because a C-string is, by definition, a sequence of characters terminated by '\0' (also called a "zero-terminated string"), so the first '\0' in the sequence ends the string.
However, there are interfaces that take a a pointer to the first character and the ... |
4,240,850 | 4,255,212 | Shadow volumes - finding a silhouette | Im working on my OpenGL task, and next stage is loading models and producing shadows using shadow volumes algorithm. I do it in 3 stages -
setConnectivity - finding
neighbours of each triangle and
storing their indices in neigh
parameter of each triangle,
markVisible(float* lp) - if lp
represents vector of light's
p... | I've found it. It looks like if you dont see an obvious algorithm mistake for a few days, then you've made a f*cking stupid mistake.
My triangle index variable is called t. Guess what? My extending vector length is also called t, and they are in the same scope, and i set t=100 after FIRST visible triangle :D So now vol... |
4,240,879 | 4,240,894 | How is the C++ vector class implemented to allow for dynamically re-sizing of arrays? | How is the C++ vector class implemented to allow for dynamically re-sizing of arrays?
Is it done through a linked-list type of implementation?
Is a new array created from scratch each time an element is added or taken away?
Thanks,
R
| Typical behaviour: Internally, a std::vector has a contiguous array of length capacity. At any given point, only size elements are actually being used. If at any point size would exceed capacity (let's say you called push_back() a lot), a new, bigger, internal array is allocated (capacity might double, say). Then al... |
4,240,916 | 4,240,950 | How to copy elements of a vector to a stack in c++ | I want to make a stack of cards using a special Card class I created myself.
Now what I want to do is:
I want the cards in a stack for easier later use, but the cards have to be shuffled and that's not possible on a stack.
Here's the code
Card dummyCard;
vector<Card> dummyVector;
initializeCards( dummyVector, dummyCard... | What about this?
#include <stack>
#include <vector>
using namespace std;
int main()
{
vector<int> x;
x.push_back(10); x.push_back(20); x.push_back(30);
stack< int,vector<int> > stack(x);
return 0;
}
|
4,240,984 | 4,241,076 | src/ folder structure in C++? | i'm coming into C++ from Java/AS3-land, and i'm used to the package-cum-folder structure for my classes. and i like it.
i understand the very basics of namespaces in c++, and i'm happy to leave it at just the basics. but, as my project gets more complex, i'd like to keep my folder structure organized in a way i can k... | I've always liked the namespace for each folder. Mostly because when I have to maintain somebody else's code, the namespace helps me find where the class was originally defined.
Well named header files can also help with this though. I also wouldn't suggest going more than 2-3 namespaces, as then it just becomes obnoxi... |
4,241,198 | 4,241,221 | ArrayList-style indexOf for std::vector in c++? | i'm coming into C++ from Java, and have a common design situation in which i have an element (a non-primitive) that i'd like to remove from a std::vector.
in Java, i'd write something like:
arrayList.remove(arrayList.indexOf(myClassInstance));
in C++, with a std::vector, what's the best / most performant / cleanest way... | #include <algorithm>
std::vector<Foo>::iterator it = std::find(vec.begin(), vec.end(), foo_2b_found);
if (it != vec.end()) vec.erase(it);
|
4,241,262 | 4,241,276 | Qt 4.6 and OpenGL: how to capture keyboard presses with three different widgets at once? | I created a form in Qt Creator, and added three custom QWidgets (all are the same class called Renderer) into the form. I want all of the three widgets besides the form to get notified when a user presses the Alt key, but I cannot even get one to work at the moment.
I added the void keyPressEvent(QKeyEvent *) and void ... | What's your focusPolicy? Keyboard events will only go to the widget with focus (you can then call the other handlers yourself).
|
4,241,581 | 4,241,599 | program skipping a line of code | I have been working on this program for a while and I finally got rid of the compile errors. But when I tried it, the program basically skipped a line of code.
#include <iostream>
#include <cstdlib>
#include <cstring>
using namespace std;
int main(){
string nameOfFile = "";
char index;
char title[100];
char nam... | When the user entered the index, they also typed a newline, but your cin didn't remove it from the input stream. So, your call to cin.getline returns immediately because of the leftover newline.
Add a call to cin.ignore before the cin.getline to flush it out.
|
4,241,680 | 4,254,554 | c++ convert/play videos and images | I'm looking for build in library for converting videos/images. i heard something about DirectShow. Do you know any library you have used to convert videos/images?
| For transcoding (converting one video format to another) using Directshow is bit tricky, you want to use Media Foundation for this job.
There is Transcode API available in Media Foundation to achieve this task. This link has more details on Transcode API, tutorials and samples to get you started.
|
4,241,700 | 4,486,463 | Possible conflicts between Lua C++ bindings | I am currently working on a project. One library I would like to consider using in the future uses ToLua++ as a method of binding Lua. Currently, the library I am looking at is CEGUI, and it uses ToLua++. I am currently considering using LuaBind for the implementation in the project I'm working on. I was wondering if a... | As long as you don't define the same Lua entities with both tools, LuaBind and ToLua++ coexist nicely. You can use either tool to add more functions and classes to a module, but you can't add more methods to a class defined by the other tool.
|
4,241,703 | 4,247,845 | "Hello World" fails to run. Eclipse (Galileo) CDT plugin problems with MinGW and Cygwin on Windows Vista | Trying to run a simple Hello World C++ program on Eclipse (Galileo) CDT plugin on Windows Vista. Following the "Before You Begin" instructions for Eclipse/CDT...
1) Downloaded and installed the latest Cygwin. However, could not compile with Cygwin.
Internal Builder: Cannot run program "g++": Launching failed
the Ecl... | The simplest solution was to install the latest Eclipse (Helios SR1) and the CDT plugin.
I needed to also delete the old projects/import old source into new projects.
For Galileo, see:
http://sourceware.org/ml/cygwin/2010-03/msg00510.html
http://dreamlayers.blogspot.com/2010/01/eclipse-incompatibility-with-cygwin-17.ht... |
4,241,714 | 4,241,777 | Update Value in Vector | void Record::Update() {
string choice;
cout << "Enter ID: " << endl;
cin >> IDValue;
for(Itr = List.begin() ; Itr !=List.end() ; Itr+) {
if(Itr->GetID() == IDValue)
{
cout << Transit->GetID() << endl;
cout << "Would you like to set Name ? (y/n) :";
cin >> choice;
if ( choice == 'y' )
... | void RecordList::UpdateLocation() {
int IDValue;
char* strName;
char opt;
cout << "Enter ID number to update: " << endl;
cin >> IDValue;
for(Transit = List.begin() ; Transit !=List.end() ; Transit++) {
if(Transit->GetID() == IDValue)
{
cout << Transit->GetID() << ... |
4,241,864 | 4,262,549 | How can I make MinGW case-sensitive for included header file names | I want to make MinGW validate that the file names specified in #include directives are case correct. MinGW is case insensitive by default, probably because windows is case insensitive when it comes to filenames, but I am working in a cross platform environment, and want to make sure that gcc doesn't complain under Lin... | I don't think MinGW has any such option. If you assume you're running on NTFS, at least, it would probably not be too difficult to code it up and contribute a patch. But the easiest solution by far is to simply remind people to be case correct, and fix the (hopefully rare!) instances where they slip up.
Sometimes the b... |
4,241,946 | 4,241,960 | cannot override static initialization in derived class | i'm trying to provide different static initializations for classes in a hierarchy, but when i tried with this code:
#include <iostream>
using namespace std;
struct base {
static const char* componentName;
};
const char* base::componentName = "base";
struct derived : public base {};
const char* derived::componentNam... | You need to declare it in your subclass too.
struct derived : public base {
static const char* componentName;
};
|
4,242,107 | 4,253,335 | Using a DLL with unmanaged code in Visual Studio 2010? | I'm fairly new to C++ and an trying to figure out to use the TagLib library for a project I am working on. I'm working with unmanaged C++ in Visual Studio 2010 on Windows 7 64bit. I've never used an external library before so I'm very confused on how to go about this.
From this blog entry I got the libtaglib.a and tagl... | I seem to have gotten it working successfully. Here's a rough outline of what I did:
1.) I used CMake to generate the Visual Studio solution.
2.) I attempted to build the tag project in the VS solution, but it failed.
3.) I made the corrections to a few source files as outlined here: http://old.nabble.com/taglib-fails-... |
4,242,186 | 4,242,226 | what is a type in C++? | What all constructs(class,struct,union) classify as types in C++? Can anyone explain the rationale behind calling and qualifying certain C++ constructs as a 'type'.
| A variable contains a value.
A type is a specification of the value. (eg, number, text, date, person, truck)
All variables must have a type, because they must hold strictly defined values.
Types can be built-in primitives (such as int), custom types (such as enums and classes), or some other things.
|
4,242,469 | 4,243,583 | Detect when a Module (DLL) is unloaded | Is there a way to progammatically detect when a module - specifically a DLL - has been unloaded from a process?
I don't have the DLL source, so I can't change it's DLL entry point. Nor can I poll if the DLL is currently loaded because the DLL may be unloaded and then reloaded between polling.
RESULTS:
I ended up using ... | Maybe a less bad way then Necrolis's would be to use Microsoft Research's Detours package to hook the dll's entry point to watch for DLL_PROCESS_DETACH notifications.
You can find the entry point given an HMODULE (as returned by LoadLibrary) using this function:
#include <windows.h>
#include <DelayImp.h>
PVOID GetAdd... |
4,242,543 | 4,242,557 | How to get the iterator for a successful binary_search? | I want to get the iterator for the element I'm testing for in binary-search. But it only returns a bool indicating whether it found the value or not. How to get the iterator?
| You want either lower_bound, upper_bound, or equal_range.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.