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 |
|---|---|---|---|---|
5,796,766 | 5,796,913 | C++: How to read input from a text file in CodeBlocks | When I running from console I do the following:
./a.out < Input.txt
How can I do the same in CodeBlocks while debugging?
| I'm not sure you can (but see my comment above). The only way of setting the command line for an app in CB is on a per-project basis and does not seem to easily allow redirection. This seems to me to be a major deficiency in most of the widely used IDE's - I'd like to see a dialog pop up on run which allowed you to sp... |
5,797,252 | 5,797,283 | Get text using SendMessage() C++ | I am trying to get text from a textbox in a specific window. For this I'm using SendMessage Api function, I dont know if this is the corect way:
SendMessage(hwnd, WM_GETTEXT, 0, 0);
But I dont know how to print the text. For the argument 3 and 4 in msdn site it says: Additional message-specific information. So i dont ... | You should use GetWindowText. More information here.
|
5,797,356 | 5,797,568 | How to find out if path meets certain parent? | So we have a parent like somepath/** so if any one sends to us somepath/myfolder/file we would receive true and if we would receive someotherpath/ we would get false. So how to find out if a path meets certain parent?
| You need to normalize both paths, then you do a simple substring comparison to see if your path in question starts with the normalized reference path.
Normalizing includes adding the current working directory to a relative path, case normalization if your file system is case-insensitive, probably resolving symbolic lin... |
5,797,683 | 5,797,954 | memcpy - int variable to BYTE | I am trying to create a data packet, using memcpy. I expect to see the output in pOutBuffer, whose first four bytes will have 999, followed by 111 followed by 12; But currently i am getting some garbage.
The problem is that instead of copying the value, it copies the address, I think. How can i copy these values in to... | Your code works correctly. On a little-endian machine with sizeof(int)==4, the number 999 will be stored as the four bytes 0xe7, 0x03, 0x00, 0x00.
You said you saw the character 'ç': That is because you are trying to view the array as a string, and ç has the character code 0xe7, which is indeed the first byte written. ... |
5,797,769 | 5,797,803 | keeping track of changing pointers | I have a red black tree algorithm which is working fine. When a node is inserted into the tree, the insert() method returns to the caller a pointer to the node that was inserted. I store all such pointers in a STL vector.
The problem is, within the operation of the RB tree, sometimes these pointers are invalidated. ... | It seems more reasonable to keep the data in some opaque data structure pointed by node, and to keep external pointers to this structures instead of nodes.
Basicly it means adding a level of indirection between the tree and actual data.
|
5,797,814 | 5,797,895 | Date to Day of the week algorithm? | What is the algorithm that, given a day, month and year, returns a day of the week?
| This can be done using the std::mktime and std::localtime functions. These functions are not just POSIX, they are mandated by the C++ Standard (C++03 §20.5).
#include <ctime>
std::tm time_in = { 0, 0, 0, // second, minute, hour
4, 9, 1984 - 1900 }; // 1-based day, 0-based month, year since 1900
std::time_t ti... |
5,797,837 | 5,797,901 | How to pass a vector of strings to execv | I have found that the easiest way to build my program argument list is as a vector of strings. However, execv expects an array of chars for the second argument. What's the easiest way to get it to accept of vector of strings?
| execv() accepts only an array of string pointers. There is no way to get it to accept anything else. It is a standard interface, callable from every hosted language, not just C++.
I have tested compiling this:
std::vector<string> vector;
const char *programname = "abc";
const char **argv = new const char* [vector.si... |
5,798,107 | 5,798,121 | C++ throwing an exception from a destructor | This isn't a question on whether it's safe to throw an exception from a destructor.
http://www.parashift.com/c++-faq-lite/exceptions.html#faq-17.9 states:
"During stack unwinding, all the local objects in all those stack frames are destructed. If one of those destructors throws an exception (say it throws a Bar object)... | Your Component destructor is safe. The rule you're quoting only applies if the exception is thrown out of the destructor (i.e., to the destructor's caller.)
EDIT: Here's one relevant quote from the standard (emphasis added)
Note: If a destructor called during
stack unwinding exits with an
exception, std::terminate... |
5,798,228 | 5,798,379 | Dereferencing C++ STL list iterator | I'm looping through two STL lists (L1, L2) like so:
list<int>::const_iterator itr1 = L1.begin();
list<int>::const_iterator itr2 = L2.begin();
for (itr1; itr1 != L1.end(); itr1++) {
if (*itr1 < *itr2) {
//some code
}
}
It compiles fine but when I run it, it says "Expression: list iterator not dereferencabl... | while ( *itr2 < *itr1 ) {
itr2++;
}
That code has no check for running off the end of L2. Maybe add a check for itr2 != L2.end() to that.
|
5,798,231 | 5,798,255 | Why won't this C++ program compile? | This is the program I'm trying to compile.
#include <iostream>
#include <string>
#include <vector>
#include <unistd.h>
using namespace std;
vector<string> paramlist;
const char *programname = "abc";
const char **args = new const char* [paramlist.size()+2]; // extra room for program name and sentinel
args [0] = prog... | You at least need an int main function.
|
5,798,278 | 5,798,306 | What is my indentation style called. Is there an emacs style for it? | I tend to write code like:
void myfunc()
{
}
if (statement){
dostuff();
}
else{
dootherstuff();
}
switch (var){
case 1:
{
stuff();
}
break;
case 2:
stuff();
break;
};
Is there a formatting mode for this? what's it called?
If not, or there is one that is close to... | Looks like K&R style.
|
5,798,322 | 5,798,346 | Will execv run this in the foreground or background? | I have this in my program:
execv (programname, (char **)argv);
I'm not sure if the command is actually being executed correctly. How can I find out? Is this being run in the background?
| Since execv replace the current process, the command will be run on the same state as the parent process.
One way to know if your command is executed is to make the command print something on the console, if it is possible.
|
5,798,380 | 5,798,455 | Help with breaking up code? | I have this program I've been working on for a while, which is basically a checkers game where somebody can either decide to play against a player or watch a computer simulation. Now both of these are basically the same code, except for the fact that the computer simulation takes randomized values. Both of these code ... | You could do something like
if (x == 1)
{
#include "player.cpp"
}
else if (x == 2)
{
#include "simulation.cpp"
}
And have the individual .cpp files contain the logic for each major section. This is a bit clunkier though that just wrapping the functionality in some functions and call those from your if-if-else... |
5,798,573 | 5,798,698 | Does the C++ spec allow an instance of a non-virtual class to include memory for a vtable pointer? | Does the C++ spec allow an instance of a non-virtual class to include memory for a vtable pointer? I am asking this, because a colleague said he once used a C++ compiler where the following happened:
class MyClass
{
public:
HeaderStruct header; //This had extra words
BodyStruct message_body;
... | I'm unable to find an online reference for it with a quick search, but I'm pretty sure a compiler is permitted to do ANYTHING with the layout of any class; in particular, in classes without any virtual methods, it's allowed to put a vftp or not, depending on how it's feeling that day, whether it's declared as class or ... |
5,798,611 | 5,798,772 | How to break whenever a class is entered | I've read the thread break whenever a file(or class) is entered. And I now understood the basic mechanism how to automatically set breakpoints in the classes. However, the solution that thread provided is focused on .net framework. My problem is how to deal with it in standard C++. We use vc 10 compiler on windows 7 pl... | You can do it from the IDE:
http://blogs.msdn.com/b/habibh/archive/2009/09/10/class-breakpoint-how-to-set-a-breakpoint-on-a-c-class-in-the-visual-studio-debugger.aspx
|
5,798,616 | 5,798,734 | help with insert on first BST | EDIT there a small thing that I am missing!! the error is still there
So I am attempting to learn how to code my first BST, and it is hard.... I am already having trouble with just a few lines of codes. the problem is in the insert, but I have included everything so that I could get some feedback on my style/other erro... | I copied some of your code and this is working fine for me:
main:
#include <iostream>
#include <stack>
#include <queue>
#include <string>
#include "tree.h"
int main()
{
Tree test;
test.insert(100, "blah");
test.insert(50, "fifty");
test.insert(110, "one hundred ten");
return 0;
... |
5,798,683 | 5,798,820 | Tag-dispatch structure cannot insert object types | I send an object instants name apple a("Apple") to an eat function on a tag_dispatch namespaces. Why an eat function cannot accepted by instants objects.
..\tag_dispatch.hpp: In function 'void eat(const T&)':
..\tag_dispatch.hpp:52: error: template argument 1 is invalid
..\tag_dispatch.hpp:52: error: invalid type in de... | The tag template class is not defined anywhere in your code. The tag template class must be defined before you attempt to use tag<T>::type.
You must provide specializations of the tag template for each of your tagged types:
template <typename T>
struct tag {};
template <>
struct tag<apple> {typedef apple_tag type;};
... |
5,798,938 | 5,825,326 | Calling C++ member function from Luabind causes "No matching overload found" | I've got some classes exported to Luabind in a DLL, and everything is working fine for those 2 classes (LuaScriptManager, EventManager).
I can call their functions from Lua and all is well, but now I'm trying to setup some new class in my client executable which links with the DLL and so far no luck at all.
Here's the ... | This is a copy of a mail I sent to the Luabind mailing list.
http://sourceforge.net/mailarchive/message.php?msg_id=27420879
I am not sure if this applies to Windows and DLLs, too, but I had a similar
experience with GCC and shared modules on Linux: classes registered
with Luabind where only valid within that shared lib... |
5,799,010 | 5,799,013 | Will delete[] with void* cause memory leak? |
Possible Duplicate:
Is it safe to delete a void pointer?
Will the following code cause memory leak?
void *ptr = new long [10];
delete[] ptr; // note: ptr is a void*
[EDIT]
The code above will generate a warning message during compiling to specify it "undefined".
I ask this cause I'm wondering how does C++ handle me... | No. Leaving delete[] out will cause a leak. BTW, it should be long* ptr. I don't think the delete[] will even compile with a void* argument.
|
5,799,072 | 5,799,089 | C++ compile error with templates | I have this function:
template <typename T>
List<T>::ListNode *List<T>::find(int index) const
{
if ( (index < 1) || (index > getLength()) )
return NULL;
else
{
ListNode *cur = head;
for (int skip = 1; skip < index; ++skip)
cur = cur->next;
return cur;
}
}
Tha... | It should be
template <typename T>
typename List<T>::ListNode *List<T>::find(int index) const
// ...
typename tells the compiler that List<T>::ListNode represents a type. When inside a template, there is a parsing ambiguity when :: is encountered. You therefore have to use the typename keyword when whatever follows ::... |
5,799,188 | 5,799,324 | Convert a string to and unsigned char [] | I currently have a Packet set up like so:
struct Packet {
unsigned short sequenceNumber;
unsigned short length;
unsigned char control;
unsigned char ack;
unsigned short crc;
unsigned char data[];
Packet copy(const Packet& aPacket) {
sequenceNumber = aPacket.sequenceNumber;
le... | You haven't specified the size of the data array.
unsigned char data[];
This is legal, but rather difficult to use. The data array will follow the rest of the Packet structure in memory, but the compiler doesn't know how much space to allocate for it. So you have to allocate the extra space yourself:
size_t datalen ... |
5,799,206 | 5,799,221 | How to get the pid of a program started with fork and execv | In this program, I start another process with execv.
if (fork() == 0) {
struct rlimit limits;
limits.rlim_cur = 10000000; // set data segment limit to 10MB
limits.rlim_max = 10000000; // make sure the child can't increase it again
setrlimit(RLIMIT_DATA, &limits);
execv(...);
}
How do I get the pid ... | It's returned by the fork() call in the parent, so you need to capture fork()'s return value in a variable.
pid_t child_pid = fork();
if (child_pid == -1) {
// fork failed; check errno
}
else if (child_pid == 0) { // in child
// ...
execv(...);
}
else { // in parent
// ...
int child_status;
waitpid(child_... |
5,799,294 | 5,799,376 | I have to call Destructor explicitly | class TsDatabasePool
{
private:
TsDatabasePool(int numDBConn, std::string& DBName, std::string& DBType);
static TsDatabasePool* objInst_;
public:
~TsDatabasePool();
QSqlDatabase* borrowFromPool();
void returnToPool(QSqlDatabase*);
static bool createI... | I believe what you are trying to do here is destroy a singleton object.
It can be done as follows in a Singlethreaded Enviornment:
void TsDatabasePool::Destroy()
{
if (objInst_)
{
delete objInst_;
objInst_= 0x0;
}
}
Ideally, You can use something like shared_ptr t... |
5,799,348 | 5,799,368 | insert on first BST giving end of no-void function errror? | So I am attempting to learn how to code my first BST, and it is hard.... I am already having trouble with just a few lines of codes. the problem is in the insert, but I have included everything so that I could get some feedback on my style/other errors. I was suggested to use a pointer to pointer implementation, but w... | cc1plus: warnings being treated as errors
tree.cpp: In member function âbool Tree::insert(Tree::Node*&, int, std::string)â:
tree.cpp:34: warning: control reaches end of non-void function
This just says that you don't return something on every possible path. Try this:
bool Tree::insert(Node*& currentRoot, int k, string... |
5,799,492 | 5,801,428 | How can I test if the boost shared memory object is removed or not? | I'm using boost::interprocess::shared_memory_object between the processes.
A process (server) creates a shared memory object, and other processes (clients) open that shared memory object. But, how can client processes determine if that shared memory object is removed by server process?
As boost documentation states, wh... | You could include a flag in your shared memory object that indicates if your server process is still using it.
Set this flag to false before your server process attempts to delete the shared memory. When the client processes see that the flag is false they can close their references to the object.
Also, I don't think ... |
5,799,538 | 5,799,567 | GUI Development - Language and Builder | I have a nice piece of software written in Erlang, over the past few weeks I have developed a gui using wxWidgets. Its decent at best, the nightmares come from the fact that there is no gui wysiwyg type of a program that writes erlang.
So..
I am looking to code my gui in another language and link it somehow (the someh... | It sounds like you've covered the range of modern C++ GUI options (two you're considering, and two you're not). Qt is an excellent choice, but I've never used C++ Builder.
|
5,799,553 | 5,799,945 | C++: Alternative to STL and Boost? | C++ is a multi-paradigm language and STL and Boost are built towards the functional paradigm of the language. STL is composed of containers (to hold data), iterators (to access data) and algorithms (functions to manipulate data). Algorithm functions are applied on containers by using iterators. As a side-effect, these ... | Take a look at Qt's approach, I have always been a fan of it.
updated the link.
|
5,799,590 | 5,799,904 | How to debug static dependency loading problems? | How can I debug a scenario where a Visual C++ 2010 SP1 application is unable to completely load its dependencies, and quits prematurely, without showing its UI?
I am interested in a good guides to Fusion Logs, dependency walker, and remote debugger, if you think they are relevant. Is it something that can be easily v... | Is it possible to launch a process on a remote machine with remote debugger attached?
Sure you can. For example in Visual Studio 2008, right-click your project -> Properties -> Configuration Properties -> Debugging, select "Remote Windows Debugger" in the "Debugger to launch" dropdown list. Then type the full path of y... |
5,799,626 | 5,799,707 | Inline function performance | I am having a slight performance issue with inline function.
Consider the following code:-
inline int left(int x) {
return 2*x;
}
inline int right(int x) {
return 2*x+1;
}
main() {
for(int i=0;i<200000000;i++) {
int L=left(i);
int R=right(i);
}
}
This when compiled and executed (with a... | Inlined functions and macros should be the same performance so your functions are probably not getting inlined. Try adding
__attribute__((always_inline))
to your function declaration. (Also see gcc docs here):
Generally, functions are not inlined
unless optimization is specified. For
functions declared inline,... |
5,799,699 | 5,800,670 | Erlang and C/C++ Threading | If I use erlang as say a spawner process, it does major functions things that are not too speed critical like communicating with a server and handling server-client communication messages.
Then I choose to spawn a process in erlang and run c/c++ code from it, will this make my code faster?
Will erlang more efficiently ... | You talk about two different concepts in your question: Erlang processes running C/C++ code and C nodes.
C or C++ code run from inside Erlang is not scheduled at all. In fact, it will block the Erlang scheduler for the current CPU core, so having long run times in C-land will most likely mess up your (Erlang) schedulin... |
5,799,968 | 5,807,167 | representation of 6 byte MACID | I am working on Client Server application where I need to send 6 byte mac id (FFF000 - FFF1FF) to the server from the client.
I wanted to know the how best to represent in c++.
I thought of declaring it as unsigned long and then covert it in 6 bytes and send it to the server.
Is this correct do this.
Any Other alternat... | I don't think I'd use an integral type for this, since we would never treat the value as a number. I would represent it as a sequence of 6 bytes. Some possibilities are:
unsigned char macid[6];
typedef unsigned char macid[6];
struct macid {
unsigned char data[6];
};
But in the end, I'd probably opt for:
std::tr1::... |
5,800,060 | 5,800,170 | ListView notify Column drag | I want to be notified when column drag-n-drop operation is ended to update "column order".
I have found that LVN_COLUMNDROPDOWN is suported from Windows Vista.
What is the WinXp way of doing that ?
| Found the answer. HDN_ENDDRAG.
Sorry for noise :)
|
5,800,167 | 5,800,650 | Displaying image in WIN32, Why its not displayed? | I want to load a BitMap image in a pic box I created inside a window...picBoxDisp is created using following mechanism..
picBoxDisp = CreateWindow("STATIC", "image box",
WS_VISIBLE |WS_CHILD | SS_BITMAP |WS_TABSTOP | WS_BORDER,
50, 50, 250, 300, hwnd , (HMENU)10000, NULL, NUL... | You misunderstood the STM_SETIMAGE usage. Do this:
hBitmap = (HBITMAP)::LoadImage(NULL, szFileName, IMAGE_BITMAP,
0, 0, LR_LOADFROMFILE| LR_DEFAULTSIZE);
if (hBitmap != NULL)
{
::SendMessage(picBoxDisp, STM_SETIMAGE,
(WPARAM)IMAGE_BITMAP, (LPARAM)hBitmap);
}
EDIT:... |
5,800,280 | 5,800,600 | How to grow a buffer without invalidating pointers to it? | The terms 'pool' and 'buffer' may be used interchangeably here.
Suppose I have a pool I want to allocate at the beginning of the programm, as to not always call new all the time.
Now, I don't want to artificially limit myself on the size of the pool, but if I reallocate a bigger pool, all pointers to the old one will b... | You're talking about something that reminds me of a std::deque. I'm not really sure if you can use a std::deque as is, or if you'll simply need to use its basic design to implement some kind of allocator.
|
5,800,286 | 5,800,341 | Why is WEXITSTATUS even needed? | The following code will wait for a child process to finish and then print its return code.
int status;
wait(&status);
cout << "return code = " << WEXITSTATUS(status) << endl;
Why can't the return code just be stored in the int variable? Why does it have to be converted with the function WEXITSTATUS? What does the valu... | The int holds more than just the exit code - it also stores information about how the process terminated, for example if it was signalled (WIFSIGNALED) or if exit() was called (WIFEXITED), etc.
The W macros are used to extract the various pieces of information from the int.
|
5,800,466 | 5,871,344 | How to show hypertext in QTableView's default view? | I am having a grid which inherits the QTableView with my Custom model set for view. I have also created the delegates for editing items in table cell. they all work fine (as per my requirement at least).
but my problem is , when the user click inside the cell, and if the delegate for that item is let's say QTextEdit (w... | By default the editor displayed is associated with the type of that particular column (e.g. int, double, QDateTime). That editor is controlled by the delegate assigned to the view. In particular, take a look at its createEditor() and setEditorData() functions.
It's likely that your model is using a QString type and pa... |
5,800,585 | 5,800,598 | Regarding struct initialization in c++ | I have Struct like these
typedef struct sample
{
double x,
double y,
double z
}s1;
s1 s;
will the content in s variable initialized or not?
What will be the values of x,y,z?
thanks
| x, y and z won't be initialized if s is defined in a function scope. They would be containing some unspecified values. At file scope the data members would be initialized to their default values.
In C++ however you can have a constructor initializer list to initialize the data members
For example
struct ABC
{
int x;... |
5,800,594 | 5,805,727 | Get UNC path from mapped drive-letter after impersonation | If I call function WNetGetUniversalName() to get UNC path from drive mapped in current session, the function succeeds.
But...
If I create a new logon sesssion by calling LogonUser() (The logon user is same as the process creator)
Impersonate with the logged on user by calling ImpersonateLoggedOnUser() function
And aga... | If I recall correctly I believe these drive mappings are stored in the logon session. Since LogonUser() creates a new logon session it will not have the drive mappings; you would have to use ImpersonateLoggedOnUser() with an existing token.
|
5,800,894 | 5,882,453 | 64 bit features in a 32 bit application? | I have a 32 bit application which I plan to run on 64bit Windows 7.
At this stage I cannot convert the entire application to 64 bit due to dependencies to thirdparty functionality.
However, I would like to have access to the xmm9-xmm15 registers in my SSE optimizations and also use the additional registers which 64 bi... | It seems to me that the best way would be to divide your program in more than one executable. The EXE compiled as 64bit can communicate with another 32-bit EXE used the 32-bit thirdparty DLL which you need. You will have some overhead in the communication and will have to implement Starting/Stopping of depended process... |
5,800,925 | 5,801,379 | How do I link to Qwt libraries on Ubuntu? | I have installed the Qwt library on Ubuntu 10.04. The Qwt plotting widgets have appeared in QtCreator but when I try to use any of them I get the error:
"qwt_plot.h" no such file or directory.
Can anyone help?
Edit:
I've solved this by implementing Begemoth's answer as follows:
Open the project file (.pro)
Add the ... | Ubutu like Debian provides several versions of qwt (for qt4 and qt3), so include files for qwt reside in /usr/include/qwt-qt3 or /usr/include/qwt-qt4 directory, you need to add this directory to the list of the include search path, e.g. with -I gcc flag.
PS: I assume that you have installed the development package for ... |
5,800,959 | 5,802,126 | A c++ function that periodically gets called | In my c++ program I want to make a function that gets called periodically, like once every second. How can I do that?
I am creating a shell in OSX. It should also work the same in Linux. The purpose of this function is to watch spawned programs, and terminate them when they start using too much memory or cpu time.
| Ok--here's a pthread solution. Someone may want to check my pthread API usage for correctness, but I verified this works:
#include <stdio.h>
#include <pthread.h>
#define false (0!=0)
static void * TimerRoutine(void *) ;
int main( int argc, const char ** argv)
{
pthread_t thread ;
pthread_attr_t attr ;
pt... |
5,801,162 | 5,897,149 | Is there any way to prevent a user from registering/using his own signal handler and always use a particlar handler? | My requirement is:
I have a signal handler in my tool, which is registered and used between some particular interval (i am using timer).
Now this signal handler should NOT allow any other handler to be registered after this handler is once registered. (But this restriction is only for a short duration... | This can be achieved, and in fact i have done that by writing a sigaction wrapper around the actual one, and using the dlsym and RTLD_NEXT technique.
Here is the code snippet of my wrapper:
enter code here
int sigaction(int sig, const struct sigaction *act, struct sigaction *oact)
{
struct sigaction sa;
printf("My s... |
5,801,242 | 5,801,276 | When does an c/c++ project need a configure file? | Almost every c/c++ open source project I see ships with it a configure file.
But in our own c/c++ project I haven't seen this file so far,
when is it needed?
| I think you are speaking about configure script which is used, when autotools are used to build the project.
The main purpose of the configure file is to generate Makefiles appropriate to your system configuration and to check various preconditions (installed libs, for example).
|
5,801,601 | 5,801,765 | Why is std::string not a valid type for a template constant parameter? | I'm trying to create a class where a user can store different type of data in maps. I've created a map for bool, int and std::string and created template functions so that I don't have to rewrite the get and set functions for each type.
Here's a minmal version of my code:
#include <map>
#include <string>
#include <stde... | Two points:
The specialization should be outside the class (important), otherwise it will not compile
The correct syntax of the specialization is as follows:
//outside the class definition
template<>
std::map<std::string, bool>& Options::GetMap<bool>() {
//^^^^^^^^^ dont forget this!
... |
5,801,723 | 5,801,759 | convert strange hex phone number to normal digits | I have a phone number represented as: AA A3 AA A1 A3 A7 A9 A7 A4 A9 and I want to convert it to normal digits: 0301379749?
| int main()
{
std::string str = "\xAA\xA3\xAA\xA1\xA3\xA7\xA9\xA7\xA4\xA9";
for(unsigned i = 0; i < str.size(); i++)
{
if(str[i] == '\xAA') str[i] = '\x00';
str[i] = (str[i]&'\x0F') + '0';
}
//or
std::for_each(str.begin(), str.end(), [](char &c)
{
if(c == '\xAA') c =... |
5,801,813 | 5,801,940 | c++, usleep() is obsolete, workarounds for Windows/MingW? | I already found out with another question that Windows/MingW doesn't provide the nanosleep() and setitimer() alternatives to the obsolete usleep().
But my goal is to fix all warnings that cppcheck gives me, including the usleep() style warnings.
So, is there a workaround to somehow avoid usleep() on Windows without usi... | usleep() works with microseconds. In windows for getting microsecond precesion you should use QueryPerformanceCounter() winapi function. Here you can find how get that precesion using it.
|
5,802,005 | 5,802,078 | Does DLL new/delete override the user code new/delete? | guys,
If I override the global new and delete in my dll code, will this override the user code new and delete?
I made a test, and it shows the user new and delete will not be impacted.
If I want to make user code new and delete be replaced by mine sdk new/delete, how to do that.
What's the case of template class. Temp... | No, on Windows each DLL has its own operator new()/operator delete(). However you should be careful - if some DLL news an object that object should be deleted using the same operator delete() - otherwise you run into undefined behavior.
|
5,802,077 | 5,802,122 | Strange GCC error: expected primary-expression before ',' token | I'm still trying to migrate from MSVC to GCC, but I can't seem to find a solution to the following problem:
template < typename A, typename B, typename C, typename D >
class Test
{
public:
Test (B* pObj, C fn, const D& args) : _pObj(pObj), _fn(fn), _args(args)
{
}
A operator() ()
{
return _... | Try return _args.template operator() < A, B, C > (_pObj, _fn);.
Without the template keyword the parse would be different. Without that extra use of template, the compiler does not know that the less-than token (<) that follows is not really "less than" but the beginning of a template argument list.
14.2/4
When the n... |
5,802,250 | 5,802,385 | Missing symbol error (undefined reference) | I have trying to define a class DS with the declaration in DS.h and implementation at DS.cpp
The code is very small so here is the listing:
/*
* DS.h
*/
#ifndef DS_H_
#define DS_H_
#include "Node.h"
template<class T>
class DS
{
public:
static const int BST;
static const int SLL;
... | Now, if I remove all the code from DS.cpp and paste it into DS.h, everything compiles fine. Any idea what am I doing wrong?
See this entry in the C++ FAQ about separate compilation.
|
5,802,266 | 5,802,413 | Correct way to use decltype as trailing return type | I very often see example of this form:
template <typename T, typename U>
auto add(T&& t, U&& u) -> decltype(std::forward<T>(t) + std::forward<U>(u))
{
return std::forward<T>(t) + std::forward<U>(u);
}
but I dare to say that this is better more correct way:
template <typename T, typename U>
auto add(T&& t, U&... | In general, I cannot think of a sensible use case where there will be a difference, but I guess that you could find some case where the operation has different implementations for rvalue-references and rvalues, and the language rules do not dictate that the return type of the different overloads has to be the same (eve... |
5,802,313 | 5,802,394 | QT4 QstringListModel in QListView | This is my first QT question - I'm generally a C# programmer so forgive me for asking a stupid question for which I'm sure there's a very simple answer, which I just can't seem to find:
I want to add items to a list, for the moment let's say they're strings.
I have a QListView: UI->listView, a QStringList, and a QStrin... | You've modified the QStringList, you need to modify the model:
stringList->append("xyz");
listModel->setStringList(*stringList);
|
5,802,347 | 5,802,517 | non recursive check of variable length string content | I have a function which takes a char* of variable length and the length.
I want to check if its contents are all white spaces.
It being a variable length, means I cant use a memcmp because I dont know how long to make the second parameter.
Any thoughts on a neat way to check it with out iterating over each character of... | A reasonably efficient way to answer this exact requirement is:
bool is_whitespace(const char* p, size_t n)
{
while (n--)
if (!isspace(static_cast<unsigned char>(*p++)))
return false;
return true;
}
More generally, it's a good idea to try to store such data in std::string variables, which m... |
5,803,126 | 5,842,452 | Can't Compile C++ Code on NetBeans 7.0 | I just installed NetBeans 7.0 with C++ package. It asked for C++ compiler - I installed MinGW. I added it to NetBeans (so it recognize it). I think that it's all correct...
I wrote very simple C++ application in main.cpp and tried to compile it...
#include <cstdlib>
#include <iostream>
int main( int argc, char** argv... | I guess you didn't add msys to your PATH variable. See this entry in the Netbeans forum, as the error reported there is essentially the same as the one you pasted in your question. So, the error message you received does not complain about make, it complains that it can't find mkdir, which is supposed to be in a direct... |
5,803,150 | 5,803,200 | List Iterator Access Violation | I have a list of pointers to SomeClass objects in a Main class. Whilst in Main I can iterate over the list using list::begin() and list::end().
When I do the same from an instance of SomeClass (bearing in mind that the list is a public member of the Main class) I get the following exception:
0xC0000005: Access violati... | 0xC0000005: Access violation reading location 0xbaadf0ad.
I think that was 0xbaadf00d until you overwrote something in it, which indicates uninitialized heap memory. So, maybe you're dereferencing a non-existant Main*? E.g. main->someClasses.begin() may throw your exception, if main wasn't initialized yet.
And indeed... |
5,803,623 | 5,803,942 | C++: How to trigger a compiler error when function return value is unused? | Let's say I have a normalize function defined as:
Vec3f Vec3f::getNormalized() const {
return (*this)/this->length();
}
Is it somehow possible to create a compile-time error if this function is used without something storing it's return value? ;
v.getNormalized(); // which most definitely is a typo
..instead of..
... | In GCC, use -Wunused-result to trigger the warning when a function's return value is ignored. And if you want an error instead of warning, use -Werror to convert all warnings into errors. For more information see GCC Warning Options.
There does not seem to be an equivalent warning for the Visual C++ compiler. (If I am ... |
5,803,835 | 5,821,711 | Compute OpenCV functions server side on image sent from Android | --EDIT--
I wasn't very well understood with the initial question, so allow me to rephrase.
I am working in an image processing application for Android.
Let's admit I will send an image from android to some server.
What I want to know is how to process this image with opencv (c/c++) on the server and return the results... | Look into setting up a web service if you're just trying to offload the processing to a server and send back some processed data. There's a ton of examples and sample setups based on the server environment (OS, speed, bandwidth needs, etc) out there that should help you get started. You would then setup the OpenCV envi... |
5,803,953 | 5,804,024 | What is a static constructor? | This question was asked to me in an interview:
What is a static constructor?
Does it exist in C++? If yes, please explain it with an example.
| C++ doesn’t have static constructors but you can emulate them using a static instance of a nested class.
class has_static_constructor {
friend class constructor;
struct constructor {
constructor() { /* do some constructing here … */ }
};
static constructor cons;
};
// C++ needs to define stat... |
5,804,287 | 5,804,693 | Process and Thread related question | I am developing an application based on one library.
I am facing problem related to communication in between Parent Process and Forked Process from Parent process.
I need to access Function in the library, and pointer for library is in Parent process and i am calling functins of library from Forked process using pointe... | After the fork, both your processes have the library loaded and any existing pointers are valid in both of them, but there's no further connection between them in terms of function calls or access to data. If the parent calls a function, the parent will run the function. If the child calls a function, the child will ... |
5,804,453 | 5,807,879 | C++ Regular Expressions with Boost Regex | I am trying to take a string in C++ and find all IP addresses contained inside, and put them into a new vector string.
I've read a lot of documentation on regex, but I just can't seem to understand how to do this simple function.
I believe I can use this Perl expression to find any IP address:
re("\b(25[0-5]|2[0-4][0-... | Perhaps you're looking for something like this. It uses regex_iterator to get all matches of the current pattern. See reference.
#include <boost/regex.hpp>
#include <iostream>
#include <string>
int main()
{
std::string text(" 192.168.0.1 abc 10.0.0.255 10.5.1 1.2.3.4a 5.4.3.2 ");
const char* pattern =
... |
5,804,460 | 5,804,490 | Derived class type in template argument doesn't compile | This is the code snippet I have been hopelessly stuck on.
template <class T, T nt>
class C;
struct base{
int i;
} b;
struct derived : base{} d;
C<base*,&d> obj;
Why this giving error could not convert template argument &d to base*?
| When matching an argument to a parameter that is a pointer/reference, derived to base conversions are not considered even if the conversions are valid in other circumstances.
14.3/5 [Standard quote just for reference]
If a non-type template-argument cannot be converted to the type of the corresponding template-paramet... |
5,804,632 | 5,804,832 | BST keep getting Segmentation fault | EDIT: running it through the gdb gives
Program received signal SIGSEGV, Segmentation fault.
0x0000000000400e4c in Tree::findKey(std::basic_string<char, std::char_traits<char>, std::allocator<char> >&, int, Tree::Node*) ()
Need some help with my first BST code, I keep getting a segmentation fault, i think that it is a... | bool Tree::findKey(string& s, int k, Node* currentRoot)
{
if (currentRoot->key == k){
s = root->data;
return true;
}
else if (root->key < k)
return findKey (s, k, root->right);
else if (root->key > k)
return findKey (s, k, root->left);
else
return false;
}
Yo... |
5,804,663 | 5,805,005 | Sort singly linked list on when inserting into istream c++ | Im the most basic person in the world when it comes to c++ and I was wondering if you guys could help me out if that would be ok. Im trying to do sorting on nodes read into an istream but AS they are read in. The code on the web is very complex and I was wondering if there was a very basic way to acheive this.
Here is ... | See if this gets you thinking properly about the problem:
You start with a deck of cards face up. You want to sort the deck of cards but you have to follow some strange rules.
You place the unsorted deck of cards so that you can only see the top card. Start by moving the first card to your sorted pile (one card is a... |
5,804,759 | 5,804,799 | how to remove directory in linux which is not empty |
Possible Duplicate:
How to remove a non-empty directory in C++?
I have the directory name. i am trying remove(dir_name), but as the directory is not empty its returning false.
How can i delete the directory. Is there any built-in function which i can call??
| To recursively remove a directory and all it's contents, use the following command in a terminal:
rm -rf /path/to/dir
Edit: Seems I was confused by your mention of built-in function, I was assuming a function "built into" linux. Obviously this is not C++ code. If that's what you want, see the question linked to in Fre... |
5,804,895 | 5,805,072 | Sorting of vector containing structure | I was trying to sort a vector of struct.The following is my code.I am not able to sort it properly...Can anyone help me..?I need to sort according to the mmNo.Sorry ...i missed some part of the code...
typedef struct MMInfo
{
std :: string strMmNo;
std :: string strMmName;
std :: string strMmsPlace;
std :: stri... | Your code has no problems. I mean, the usage is right but the structure definition seems not correct. It's not compilable at least in Visual C++ 9.0 Please make a proper initialization list. The following code worked fine for me
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespa... |
5,805,081 | 5,805,173 | Qt: how to make decorated rich popup window instead the default QSystemTrayIcon popup window | I have simple notification application, and I'm using Qt 4.7.1 with C++ to write an application that sits in the system tray. Every time a message comes; I need it to pop-up a window. But, I need it to be rich (i.e., I want to add color and pictures to it). However, all I have is the default pop-up message box. How can... | All the qt widget classes can be styled via stylesheets, depending where create your popup (designer, or in code) assign it a stylesheet with the look that you want it to have. You can test stylesheets in designer by assigning a style to a widget using the context menu of the widget
After further review, the QSystemTra... |
5,805,099 | 5,805,626 | inventory class question | I'm trying to calculate the total cost of inventory items using the inventory class, i'm getting a few error messages and i can't figure out why, the errors are undeclared identifiers in the imp file of my ... Here's what i have so far.
Inventory.h
#include <string>
#include <iostream>
using namespace std;
class Inve... | Aside from the main problem that forsvarir addressed, your other errors seem to revolve around undefined variables. You actually define them but misspell them in a couple of places.
Start training yourself to use some convention (it really doesn't matter what so long as you are consistent) that differentiates between ... |
5,805,292 | 5,805,710 | reading from ComboBox | how can i read the text of a selected value of a comboBox in windows aplication(borland C++) for example:
i have combobox which contains 2 values (sum and mult) i want to see if it is sum i have to add the numbers and if it mult i have to multiplicate the numbers so how can i read the value of combobox in this case.
| I never work with c++ with winapplication but i tried it with the c# and hopefully that you want the desired output as i got through your question if it is not right then you should edit your question.
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (comboBox1.Text == "ADD... |
5,805,400 | 5,805,610 | Is a macro with variables always defined with the variable or constants? | If I have a macro like this in a function:
void SomeFunc(int arg1, int arg2)
{
float value1, value2;
float range;
//#define MatrixBlock MyMatrix.block<arg1,arg2>(value1, value2)
//#define BlockRange MatrixBlock.block<arg2, range>
#define MatrixBlock MyMatrix.block(value1, value2, arg1, arg2)
#defi... | A Macro is just a text substitution.
In your code you have defined the substitutions but never actioned them. You will need to do something like:
void SomeFunc(int arg1, int arg2) {
float value1, value2;
float range;
#define MatrixBlock MyMatrix.block<arg1,arg2>(value1, value2)
#define BlockRange MatrixBlo... |
5,805,801 | 5,805,857 | c++, MingW, undefined reference to `libiconv' | I'm getting these errors with MingW:
undefined reference to `libiconv_close'
undefined reference to `libiconv_open'
undefined reference to `libiconv'
I have the libiconv package from MingW installed. What is causing this? If this is of some importance, I'm trying to get tinygettext working.
| You must have forgotten to add -liconv to the link line. Adding that there should resolve those problems.
|
5,806,144 | 5,898,744 | Asp.net calling C# layer calling Managed C++ calling Native C++ | My project structure is as follow:
ASP.NET calling C# layer calling Managed C++ calling Native C++
(i'm trying to avoid using interop so this is why the managed c++ layer)
I wrote unit test that test the C# layer and it works fine.
When I try to run the asp.net page i'm getting: "Could not load file or assembly..." er... | I had to flip a bool in the ApplicationPoolIdentity. One of the filed in the properties says "enable 32bit" and that did the trick :) the default is False
My server is 64bit and i build my native with 32bit.
|
5,806,205 | 5,806,251 | const member function clarification needed | I'm a little confused as to why this code compiles and runs:
class A
{
private:
int* b;
public:
A() : b((int*)0xffffffff) {}
int* get_b() const {return this->b;}
};
int main()
{
A a;
int *b = a.get_b();
cout<<std::hex<<b<<endl;
return 0;
}
Output of running this code is FFFFFFFFas well... ... | No, the member is an int* const (as seen from the const function), which is totally different.
The pointer is const, not the object pointed to.
|
5,806,254 | 5,837,479 | C++ avoid constructing an object | I have an class whose all default constructors are beyond my control. I need to avoid constructing them in some conditions and not in others. Is there any what I can do this ?
The pattern is something like this:
class A
{
public:
//ctor + dtor + methods
A();
~A();
// Data members beyond my control
... | You may want to use a Nullable type like boost::optional. This would look like:
class B {
public:
B()
{
/*
* Here, a has been default constructed and is empty
* You can do computations here and then...
*/
if(/* some elaborate condition*/) {
a = A();
... |
5,806,259 | 5,806,310 | Bounded stack of integers C++ | Hey, just doing some revision for upcoming exams and i'm looking at a past paper.
I'm asked to write the class implementation for this:
class Stack
{
public:
Stack(int n=1);
int pop();
void push(int);
int isEmpty();
int isFull();
˜Stack();
private:
int top... | I wouldn't have named it that, or likely implemented it in this fashion, but the int * cell is where your items go. I assume they want you to initialize it to an array of size when the stack is instantiated.
|
5,806,275 | 5,806,328 | how to find the elements name in the xml file using DOM xerces c++..? | I want to know how to read all the elements' names in the following xml file:
<fruits>
<apple> ... </apple>
<banana> ... </banana>
<grapes> ... </grapes>
<mango> ... </mango>
<papaya> ... </papaya>
<strawberry> ... </strawberry>
</fruits>
Here, the condition is that I am not sure which fruits a... | You can use the DOMNodeIterator to iterate all elements in your DOMDocument and then use the DOMNode->getName() to get the name and check if that's what you need.
|
5,806,305 | 5,806,333 | Is there a way to call constructor with class instance pointer? | We can call destructor explicitly through class pointer, why not constructor? Any idea?
#include <iostream>
class Con {
public:
Con( int x ) : x( x ) {
}
private:
int x;
};
int main() {
Con* c = new Con( 1 );
//c->Con( 2 ); //illegal
c->~Con(); // ok!
delete c;
}
Thanks,
| No. You cannot.
Con* c = new Con( 1 );
//c->Con( 2 ); //illegal
You've already called the constructor in the new expression.
By the time you've a valid pointer of type Con*, you've already created an object. And calling constructor on the "constructed" object doesn't even make sense. So why would C++ allow that?
|
5,806,458 | 5,806,644 | Marshall struct with char | When marshalling struct which contains a single char field from C++ to C# how the C# struct definition should look like?
[StructLayout(LayoutKind.Sequential, Size = 1), Serializable]
public struct SomeStruct
{
[MarshalAs(UnmanagedType.I1)]
public sbyte Field;
}
or
[StructLayout(LayoutKind.Sequential, Size = 1)... | You can't, in general, tell if char is signed or unsigned in C++. It depends on the implementation, and a single compiler (implementation) can often be configured through options to make it either way.
The best choice would be to make it explicit in the C++ code if possible, i.e. use signed char or unsigned char. Then ... |
5,806,489 | 8,551,774 | Signal fires although dialog not focused | I have a dialog with LineEdit elements. I want the dialog to close if ENTER is pressed so I added a slot for the returnPressed() signal:
ChPasswd::ChPasswd(QWidget *parent) :
QDialog(parent),
ui(new Ui::ChPasswd)
{
ui->setupUi(this);
connect(ui->NewPasswordInput, SIGNAL(returnPressed()), SLOT(checkPassw... | Alright, I just figured it out. Since this is a dialog pressing ENTER automatically calls another slot. This slot also calls checkPasswords() and therefor created a second message box which appears as soon as the first one was closed.
|
5,806,534 | 5,806,802 | MSMQ c++ receive message problem | I am trying to read messages from a MSMQ queue in c++.
The queue is successfully open, but I am having problems reading any message from it.
This code sample is taken from MSDN and modified in a few places.
Here is the code:
// Define the required constants and variables.
const int NUMBEROFPROPERTIES = 5;
DWORD cPropId... | The error code indicates that the properties you requested are invalid. My guess is that setting aMsgPropVar[cPropId].vt = VT_NULL; is wrong for Body Size and Body Type - the MDSN docs indicate both have type VT_UI4 - see here, for example.
|
5,806,570 | 5,806,737 | Dynamically adding an object? |
#include <iostream>
#include <vector>
#include <iomanip>
using namespace std;
static int c;
class DAI //DynamicArrayInput
{
public :
void getCountry()
{
cout << "Country : ";
cin >> Country;
}
void putCountry()
{
cout << Country << endl;
}
static int putCount()
{
r... |
c++; //c is a static variable declared at top
B = new DAI[sizeof(DAI) * c/sizeof(DAI)];
Here you are confusing new with malloc. To allocate c elements of type DAI, just do
B = new DAI[c];
However, your best bet is to stay with std::vector, which handles size and capacity itself.
for (int i = 0; i != 10; ++i)
... |
5,806,793 | 5,806,947 | Program crash in release build | in debug it works fine but when I run the C++ 2010 program in release build (not started from the debugger of visual studio) it crashes. If I comment the lines after the second char*-wchar* conversion it works. Why?
void myfunction(const char *dataBuffer)
{
size_t buffer_size;
mbstowcs_s(&buffer_size, NULL, 0,... | Probably because of an uninitialized variable (in debug mode most variables are Initialized to zero but are uninitialized in release)
Most bugs like this can be fixed by fixing all the warnings generated by the compiler (warnings are really logical errors rather than syntax errors). So set you warning level higher re-c... |
5,807,009 | 5,807,249 | C++ variable number of arguments | I need to define a virtual function that can take variable number of arguments, problem is c style ellipses does not work for non pod types, I have limited amount of memory (2KB) so i am trying to avoid allocating temp object just to pass to the function, all arguments will be of the same type (a custom shared pointer)... | Assuming your argument types are of class Arg, you can try this:
class ArgUser {
public:
// syntactic sugar:
void method() { // nullary
doMethod();
}
void method( const Arg & a1 ) { // unary
doMethod( &a1 );
}
void method( const Arg & a1, const Arg & a2 ) { // binary
doMe... |
5,807,090 | 5,807,109 | C preprocessors and order of operations | I'm learning C, but I do not understand this:
#define square(x) x*x
a = square(2+3) //a = 11
When this is run, why does a end up being 11?
| It expands to 2+3*2+3, which is equivalent to 2+(3*2)+3. Use parentheses to fix it:
#define square(x) ((x)*(x))
Now try it with square(x++) and you'll run into more problems (undefined behavior). Avoid doing this as a macro if you can.
|
5,807,130 | 5,807,170 | struct inside class.h | Code:
#include "Node.h"
#include "vector.h"
#include "algorithm.h"
struct PlusPoint {
bool used;
int id;
int plusScore;
PlusPoint(bool pUsed, int pId):used(pUsed), id(pId) {}
};
struct CompareToPlusPoint {
bool operator()(PlusPoint a1, PlusPoint a2) { return a1.plusScore < a2.plusScore ; }
}... | Apart from the fact, that the code is missing some includes (vector,algorithm), there is no such thing as Node and plusPoints, it compiles just fine.
|
5,807,471 | 5,807,636 | How to resize dynamically a two dimentional vector? | I need to resize a two dimensional vector (of unknown size) as follows:
//Creating the vector of vectors:
vector< vector< long > > v;
//Resizing the vectors:
/*Needing help here:
my current assumption is:
v.resize(1);
v[0].resize(1);
*/
//Adding elements:
v[0][0].push_back(0);
v[0][1].push_back(-1);
The co... | Your assumption about resizing the two dimensions is correct, but you are getting an error on push_back because the type of v[0][0] is long &, not vector<long> &.
I think you want:
v.resize(1);
//Don't resize the second dimension because you want it to grow dynamically
//v[0].resize(1);
v[0].push_back(0);
v[0].pus... |
5,807,474 | 5,814,867 | How to define dependencies for lib-files? | How to determine dependencies for lib-file in C++ programmatically or with a tool (like depends.exe aka Dependency Walrer for DLL)? In particular I am interested in the defining of C-runtime version. My problem is that my DLL, compiled in MSVC2010 depends on CRT 8.0. I assume that this dependency inherited from some in... | You can use dumpbin.exe which is installed with Visual Studio inside its /vc/bin/ directory.
You can have a look at :
http://msdn.microsoft.com/en-us/library/c1h23y6c(v=VS.100).aspx
|
5,807,520 | 5,807,670 | How to model cricket stumps in openGL | I am new to OpenGL and want to make cricket stumps for my mini project.
As far as I know the base is something like a cone, and then a cylinder comes above it,
but I am not able to model it.
Would you like to tell me how can I model it in OpenGL for 3D realization?
| You don't really model things in OpenGL. All OpenGL knows about is triangles. Colored triangles, different angled/sized triangles, textured triangles, etc, etc. OpenGL doesn't deal with modelling, that's your job.
You can either use modelling software (3dsmax, etc.) to create the model, export it, and then figure out ... |
5,807,699 | 5,807,816 | Why does this code compile? | What are the exact rules for deciding the access rights for the objects nested into the private sections of other objects?
For example, in the code snipped below, the proxy_t struct is nested into the private section of the abc_t, and yet its methods are available to the main function. Why does it compile at all?
#inc... | This line is the important one that I'm gonna talk about:
cout<<"proxied:"<<abc[1].a()<<" "<<abc[1].b()<<"\n";
When you call abc[1], this is a public method of abc_t. This is valid.
It returns a proxy_t. Although the declaration of this class (proxy_t) is not defined, you aren't actually using that return variable t... |
5,807,735 | 5,808,171 | C++ priority_queue with lambda comparator error | I have the following erroneous code which I am trying to compile in VC2010, but I'm getting the error C2974 this only occurs when I include the lambda expression, so I'm guessing it has something to do with that.
typedef pair<pair<int, int>, int> adjlist_edge;
priority_queue< adjlist_edge , vector<adjlist_edge>,
[]... | First define the lambda object, then pass it to the template's type using decltype and also pass it directly to the constructor.
auto comp = []( adjist a, adjlist b ) { return a.second > b.second; };
priority_queue< adjlist_edge , vector<adjlist_edge>, decltype( comp ) >
adjlist_pq( comp );
|
5,807,817 | 5,807,843 | How can I store a game map and display a portion of it on the screen? | Hey.
I'm going to write a simple ship shooting game as CG homework, so I'm planning to use some map system (though there's no need for that, it'll be an "extra") and I have no clue about how to represent a map and show it 'in parts', I mean, not all map will be visible in a single frame.
How do people usually work with... | Consider using a QuadTree. It breaks your map down into small components based by area. It lets you define how much space you want to see, which makes it ideal for zooming in and out, or panning around.
There's a C# implementation you could probably adapt to be C++ fairly easily.
|
5,807,886 | 5,808,051 | How to work with OpenGL and QT? | I'm Working on a small project and i need to work with OpenGL + QT
I'm Newbie in both of them. So i need a good tutorial that illustrates how to work with them each other not individually
is it better to work OpenGL on QT Creator or use QT Visual Studio Plug-in?
| You'll be using QGLWidget a lot! Here you go:
http://doc.qt.io/qt-5/examples-widgets-opengl.html
Of all those, maybe this is the best one to start: Hello GL Example. If you prefer using Qt Quick instead of Qt Widgets, check these posts:
Integrating custom OpenGL rendering with Qt Quick via QQuickFramebufferObject
Scen... |
5,808,151 | 5,808,235 | MFC/WIN32/C++: How to dispatch messages while doing a computationally intensive operation? | I would prefer to see if there is a reasonable way to handle this without using a second thread due to the specifics of this application (originally a DOS app with lots of global static variables, converted to Windows/MFC, but not designed from the ground up to be multi-threaded - just making it multiple document aware... | PeekMessage only looks ahead at the next message. You want GetMessage to remove it from the queue, and then DispatchMessage to actually invoke WndProc.
At this point you just reinvented DoEvents from VB, the staple of 1996 technology.
|
5,808,434 | 5,808,602 | How does the Viola-Jones face detection method work? | Please explain to me, in few words, how the Viola-Jones face detection method works.
| The Viola-Jones detector is a strong, binary classifier build of several weak
detectors
Each weak detector is an extremely simple binary classifier
During the learning stage, a cascade of weak detectors is trained so as to
gain the desired hit rate / miss rate (or precision / recall) using Adaboost
To detect object... |
5,808,516 | 5,808,859 | C++ can't return variable | Hey all! This bit of code always returns 0, even though errcheck will have a non-zero value. If I use return 1; it works as expected. Please help?
int errcheck = system(docommand.c_str());
if (errcheck != 0)
{
cerr << "Could not retrieve tarball!" << " Errcheck status (debug): " << errcheck << endl;
... | Unix exit statuses are restricted to values 0-255, the range of an unsigned 8-bit integer. As such, you cannot see 2048.
See Exit Status wiki page for more information.
|
5,808,556 | 5,808,621 | Regex to match function return types in vim | I'm using c++ with a header file that is quite large and would like to do a search for functions with specific return types, such as int. The problem lies in the fact that there is white space in front of the return types as shown below.
Set<Animal*> _animals;
int _getMonkeyCount(Zoo* zoo);
bool _addUnico... | You probably want something like:
/^\s\+\zsbool
The key here is \zs which defines the start of the match. There is also \ze to define the end of the match but you don't need that here.
|
5,808,658 | 5,809,359 | Templated class around boost::ptree headache | I'm struggling to find out why code with the following snippet will not compile. There may be something I don't understand about class templates (ie the typedef typename thing) but I don't think that's it in this particular case.
template<typename data_type>
class GlobalStore {
private:
typedef boost::property_tr... | Change
return st.get<T>(name);
to
return st.template get<T>(name);
See this FAQ for more info: What is the ->template, .template and ::template syntax about?
|
5,808,679 | 5,808,737 | Why is main() argument argv of type char*[] rather than const char*[]? | When I wrote the following code and executed it, the compiler said
deprecated conversion from string constant to char*
int main()
{
char *p;
p=new char[5];
p="how are you";
cout<< p;
return 0;
}
It means that I should have written const char *.
But when we pass arguments into main using cha... | Because ... argv[] isn't const. And it certainly isn't a (static) string literal since it's being created at runtime.
You're declaring a char * pointer then assigning a string literal to it, which is by definition constant; the actual data is in read-only memory.
int main(int argc, char **argv) {
// Yes, I know I... |
5,808,758 | 5,808,864 | Why is a static_cast from a Pointer to Base to a Pointer to Derived "invalid?" | So I have this code:
Node* SceneGraph::getFirstNodeWithGroupID(const int groupID)
{
return static_cast<Node*>(mTree->getNode(groupID));
}
mTree->getNode(groupID) returns a PCSNode*. Node is publicly derived from PCSNode.
All of the docs I've found on static_cast say something to this effect: "The static_cast opera... | The reason is most likely that the definition of Node is not visible to the compiler (e.g., it may have been only forward-declared: class Node;).
Self-contained example:
class Base {};
class Derived; // forward declaration
Base b;
Derived * foo() {
return static_cast<Derived*>( &b ); // error: invalid cast
}
cl... |
5,808,926 | 5,809,144 | Using XACT in C++/Direct X for a simple 2D game | I'm trying to take sound effects I have made and put them into my game. I have a sound like walking that I want to loop while the user is walking and once the user stops walking, I want the sound to stop. I went through the DirectX tutorials on using XACT but it does not answer my question. In my code I try to use the ... | Are you using the XACT_FLAG_STOP_IMMEDIATE flag?
|
5,808,944 | 5,809,038 | unable to push items in vector and list in C++? | This is a basic merge sort program:
The problem is when I try to push item in to "vector merged", nothing happens.
(Please refer the gdb data below the code)
vector<long> merge(vector<long> &L, vector<long> &R){
int i = 0;
int j = 0;
vector<long> merged;
while((i < L.size())&&(j < R.size())){
if ((L[i] <... | You have a bug in the algorithm, right now it seems like the first item will be merged correctly, but then all of L will be pushed and after that all of R.
It seems that moving a closing brace will solve your problem.
vector<long> merge(vector<long> &L, vector<long> &R){
int i = 0;
int j = 0;
vector<long> merged... |
5,808,948 | 5,811,386 | Merging leaves in an octree | I have a very large point cloud (> 100000 points) that I'd like to detect planar arrangements in. I decided to use an octree to break the points into very small planar clusters and then merge neighboring clusters that are coplanar. I have written code in C++ that quickly splits the point cloud into the small planar clu... | The standard fix is to lazily fix nodes. Have an access method that looks at the plane you're pointing to, and then sees whether it has been pointed elsewhere. If it has, recursively search until you find where it is, and fix up all of the objects back to the current one, and then hand back the right plane.
This is a... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.