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,978,419
4,978,590
C++ GDI+ loading an image from a file then deleting the file *before* unloading the image
Simply what it says on the tin I'm loading a bitmap from a file using Bitmap::FromFile but afterwards I want to delete it from the disk. The problem is, Bitmap::FromFile absolutely locks the file from any changes/deletion until the loaded image is unloaded This is because I'm storing the bitmaps in a binary file, so I ...
Take a look at Bitmap::FromStream. You should be able to use SHCreateStreamOnFileEx to open an IStream on the file. After loading your bitmap you can safely delete the stream and then the temporary file. If the binary file is only compressed with a supported algorithm, then pass the corresponding flag to SHCreateStream...
4,978,452
4,979,394
Problem on Transferring file through TCP with the use of file pointers
i need to transfer a file of 8.3MB over TCP, when i use file pointers to read and write to files then i send about 8.6MB data and also receives 8.6 MB of data by calculating the output of send and recv calls although my file size is 8.3 MB, further the when i check the size of file separately by seeing its properties t...
while (read(fd, buf, MAX_LINE)) { //usleep(1000);; len = strlen(buf) + 1; total += send(s, buf, len, 0); //printf("%fKB and %fMB\n",total/1024, total/(1024*1024)); } There is an issue here, you have no guarantee that read will read a zero byte so strlen(buf) is potentially dangerous. Also note, that as...
4,978,477
4,978,644
Pointers to methods & templates problem, C++
There are 2 template classes A and B having 2 private members a1, a2 and b1, b2. template <typename T> class A { private: T a1, a2; public: T getA1 () const {return a1;} T getA2 () const {return a2;} }; template <typename T> class B { private: T b1, b2; public: T getB1 () const {return b1;} ...
You're doing illegal things. See this, template <typename T> static T ( *getFirst ) (); Here you're trying to define template function pointer which is illegal in C++. The C++ Standard says in $14/1, A template defines a family of classes or functions. Please note that it does not say "a template defines a family ...
4,978,812
4,978,855
Fastest way to read data from a lot of ASCII files
for a college exercise that I've already submitted I needed to read a .txt file wich contained a lot of names of images(1 in each line). Then I needed to open each image as an ascii file, and read their data(images where in ppm format), and do a series of things with them. The things is, I noticed my program was takin...
You're allocating memory and deleting it in each loop. I don't think that is good if you so concern about performance. So one improvement you can do is: reuse the memory once it is allocated to your program. void *memory = malloc(sizeof(Image)); //reusable memory. //placement new to construct the object in the alrea...
4,979,090
4,979,274
Dedicated thread (one thread per connection) with buffering capability (c/c++)
My process reads from a single queue tasks that need to be sent to several destinations. We need to maintain order between the tasks (ie task that arrived in the queue at 00:00 needs to be sent before the task that arrived at 00:01) therefore we cannot use thread pool. Order needs to be maintained per destination. One...
The "need to maintain order" all-but-directly states that you're going to be executing the tasks serially no matter how many threads you have. That being the case, you're probably best off with just one thread servicing the requests. You could gain something if the requirement is a bit looser than that -- for example, ...
4,979,100
4,981,013
need help in UI threads in C++
I'm using UI threads and I built one thread with message map and it works fine, the problem is when I'm tring to create another thread from the first one. When I'm getting to this line: this->PostThreadMessage(WM_MYTHREADMESSAGE,0,0); I'm getting the next message: "No symbols are loaded for any call stack frame. Th...
The question is difficult to understand. I'm assuming that you're stepping through your program in the debugger, and you get to that PostThreadMessage line. If you choose Step Into, the debugger will try to step into the PostThreadMessage call (or the framework wrapper, depending on the type of this). Since PostThrea...
4,979,137
4,979,592
Can a multithreaded function use a static array to share data between threads?
Say you have a function that counts the occurences of a value in a large array. You want to multithread this function by having each thread count the occurences in its own part of the array, then adding the results together. We can assume that each thread has a unique rank (from 0 to N-1), and that each thread will cal...
The answer to your question is yes, threads have access to global data and static data in the same compilation unit, but there is more to this topic about "sharing data between threads" that is important to understand. For each thread, there is a corresponding function (the "thread function") that a thread will execute...
4,979,153
4,979,393
Algorithm for Flow Layout Panels?
In Gui's there are Flow Layout Panels which size the contents of the panel to a nice snug fit with nice spacing. Given arbitrary sized rectangles, and a container rectangle, what algorithm could be used to make all the widgets fit snug? Thanks
There are lots of different layouting algorithms out there. Most of them are pretty simple, which is a good thing, because the complex ones often behave "strange". Flow layouts like the one in your image usually align all widgets in one row horizontally. Then, starting from the first widget, the widths of the widgets i...
4,979,535
4,981,892
Querying for an A record in C
I'm working on some code that will check DNS records using libresolv. I first do the query with res_query and that succeeds, but if I'm checking an 'A' record, dn_expand will not give me the IP address back (and I don't think I should really expect it to). However, I have not been able to find a function that will deco...
The way to do this is to take the rdata from the rr (using res_rr_rdata(rr) ), and run it through inet_ntop. For an A record, this is what I ended with: if (ns_parserr(&msg, ns_s_an, rrnum, &rr)) { printf("ns_parserr: %s\n", strerror(errno)); } if(ns_rr_type(rr) == ns_t_cname){ printf("Found cname\n")...
4,979,631
4,979,763
Why is −π < atan2(y, x) ≤ π while for lines we really need only from 0 to π?
Possible Duplicate: what is the difference between atan and atan2 in c++ ? Why is −π < atan2(y, x) ≤ π while for lines we really need only from 0 to π and what has api like atan2 but would return from 0 to pi?
One common application of atan2 is converting from cartesian coordinates to polar coordinates. And that it supports all angles is its reason of existance. Else you could just use atan(y/x).
4,979,681
4,979,705
How to properly free a std::string from memory
What's the best way to delete an std::string from memory allocated on the heap when I'm done using it? Thanks!
std::string is just a normal class1, so the usual rules apply. If you allocate std::string objects on the stack, as globals, as class members, ... you don't need to do anything special, when they go out of scope their destructor is called, and it takes care of freeing the memory used for the string automatically. int M...
4,979,886
4,981,768
How to map 13 bit value to 4 bit code?
I have a std::map for some packet processing program. I didn't noticed before profiling but unfortunately this map lookup alone consume about 10% CPU time (called too many time). Usually there only exist at most 10 keys in the input data. So I'm trying to implement a kind of key cache in front of the map. Key value is ...
You may want to go with middle solution and open addressing technique: one array of size 256. Index to an array is some simple hash function like XOR of two bytes. Element of the array is struct {key, value}. Collisions are handled by storing collided element at the next available index. If you need to delete element f...
4,980,280
6,012,631
"enum class" emulation or solid alternative for MSVC 10.0
I'm looking for a hacky kind of solution to the following problem: GCC 4.4+ accepts the following c++0x code: enum class my_enum { value1, value2 }; Which allows the use like this: my_enum e = my_enum::value1; with all the bells and whistles this brings. I would like to make this code compatible with MSVC 201...
I just discovered a problem with James' good hack (which I have heretofore been using), and a fix to the problem. I discovered the problem when I tried to define a stream operator for my_enum. #include <iostream> struct my_enum { enum type { value1, value2 }; my_enum(type v) : value_(v...
4,980,383
4,980,408
Return a vector knowing it will always contain a single record in order to be consistent with the rest of the interface?
I'm writing a little address book application and have a design dilemna regarding the interface for the data source / backend. I have the following abstract base class for data source classes: class DataSource { private: public: virtual std::auto_ptr<Contact> getContact(int id) = 0; virtual Con...
I always follow the design principle of return the least complex thing that defines your object. Vectors are meant to hold lists of things not single item and while it might make the semantics symmetric it will undoubtedly be nonintuitive to another developer.
4,980,406
4,980,430
C++ virtual function undefined at link time - why?
I'm having a bit of trouble using virtual functions in C++, and I might be misusing them in a constructor. The problem is that when linking a component lib (written by me) into my final executable, a virtual function is marked as undefined, even though I have written an implementation for it, and linked it. I have the ...
You are calling the virtual function from the base class constructor. There are special rules for the dispatch of virtual functions during construction and destruction: Effectively, when the constructor of the base class UdpConnection is executing, the dynamic type of the object is UdpConnection, not UdpClient, so t...
4,980,443
4,980,488
How to set MFC time/date control to 24 hour time
I am trying to get a CDateTimeCtrl control in a dlg box to show 24 hour time format rather than am/pm nonsense. I would have thought there was a flag for this, but MS decided NOT to provide one. Is it possible?
Even though CDateTimeCtrl doesn't provide a class method to change the format, the class itself wraps the Win32 date and time picker which does allow you to set a custom format. You can do this by sending a message directly to the control: DateTime_SetFormat(m_dateTime.m_hWnd, TEXT("HH:mm:ss")); Edit: As @Kirill V. Ly...
4,980,696
4,981,178
Circularly Linked Lists C++
I've some prob to add a new elment in my Circularly Linked Lists... When I try to add the first... if( empty() && pos ==1 ) { newnode = new Node(ele); newnode->next = newnode; last = newnode; } .. I've a glibc detected :double free or corruption (fasttop) ... do you know why ? It's because i must point t...
The main reason to use a circularly linked list is simplification. And for that, you should always (with circular list) use a header node. For an empty circular list, the header node is linked back to itself, and is a permanent part of the list, it's not carrying any data – except in certain cases, a sentinel value. Wi...
4,980,810
4,980,820
How to pass cin or ifstream object as argument function
I though this would work since ifstream inherits from istream string getFileContents(istream& file_contents) { string result; string line; while (getline(file_contents, line)) result += line + "\n"; return result; } then I want to call this function like so: ifstream file_input; getFileConten...
It should work; are you sure you didn't leave around a wrong prototype that has a parameter of type ifstream & instead of istream &?
4,980,815
4,980,847
C++ - Determining if directory (not a file) exists in Linux
How would I determine if a directory (not a file) existed using C++ in Linux? I tried using the stat() function but it returned positive when a file was found. I only want to find if the inputted string is a directory, not something else.
According to man(2) stat you can use the S_ISDIR macro on the st_mode field: bool isdir = S_ISDIR(st.st_mode); Side note, I would recommend using Boost and/or Qt4 to make cross-platform support easier if your software can be viable on other OSs.
4,980,819
6,666,338
What are the GCC default include directories?
When I compile a very simple source file with gcc I don't have to specify the path to standard include files such as stdio or stdlib. How does GCC know how to find these files? Does it have the /usr/include path hardwired inside, or it will get the paths from other OS components?
In order to figure out the default paths used by gcc/g++, as well as their priorities, you need to examine the output of the following commands: For C: gcc -xc -E -v - For C++: gcc -xc++ -E -v - The credit goes to Qt Creator team.
4,981,241
4,981,313
no default constructor exists for class
#include "Includes.h" enum BlowfishAlgorithm { ECB, CBC, CFB64, OFB64, }; class Blowfish { public: struct bf_key_st { unsigned long P[18]; unsigned long S[1024]; }; Blowfish(BlowfishAlgorithm algorithm); void Dispose(); void SetKey(unsig...
If you define a class without any constructor, the compiler will synthesize a constructor for you (and that will be a default constructor -- i.e., one that doesn't require any arguments). If, however, you do define a constructor, (even if it does take one or more arguments) the compiler will not synthesize a constructo...
4,981,370
4,981,536
The Game vs The Game Engine?
I was wondering if somebody could tell me how the game and the game engine fit into game development. Specifically what I mean is, the game engine does not actually have a game. So where I'm unclear about is basically, do game developpers build an engine, then create a new class that inherits from engine which becomes ...
The distinction between the game and the actual game engine is architectural. The game logic is specific for one game whereas the game engine is something that can be reused. Much like an operating system provides utilities for applications the game engine does the same for the game code. Game engines will typically ha...
4,981,415
4,981,547
How to make a functor from a member function?
I want run to call c.drive(): #include <functional> using namespace std; struct Car { void drive() { } }; template <typename Function> void run(Function f) { f(); } int main() { Car c; run(bind1st(mem_fun(&Car::drive), &c)); return 0; } This does not compile and the error messages does n...
bind1st makes a unary function out of a binary function and a value. You are trying to make a function that takes no parameters out of a unary function and there isn't anything to support this in standard C++03. You will have to do something like this. template<class X, void (X::*p)()> class MyFunctor { X& _x; publ...
4,981,522
4,981,587
Reading a fixed number of chars with << on an istream
I was trying out a few file reading strategies in C++ and I came across this. ifstream ifsw1("c:\\trys\\str3.txt"); char ifsw1w[3]; do { ifsw1 >> ifsw1w; if (ifsw1.eof()) break; cout << ifsw1w << flush << endl; } while (1); ifsw1.close(); The content of the file were firstfirst firstsecond second...
The extraction operator has no concept of the size of the ifsw1w variable, and (by default) is going to extract characters until it hits whitespace, null, or eof. These are likely being stored in the memory locations after your ifsw1w variable, which would cause bad bugs if you had additional variables defined. To get...
4,981,565
4,981,579
how does boost-asio know what port the server is running on?
So I was looking through the asio tutorials and I compiled the synchronious daytime client and the synchronious daytime server. I was playing around with the code on the server end by changing the port (in the site's code they hard coded 13 as the port) to be passed in through the command line. I noticed that the clien...
interestingly enough nothing on the client said what port the server was on server port in client is hardcoded here: tcp::resolver::query query(argv[1], "daytime"); the key is "daytime". it's a standard protocol and has its standard port number 13
4,981,588
4,982,754
automake+libtool+c++ = very bloated interface
First i have "include_HEADERS = 'my public headers'" and "libfoobar_la_SOURCES = 'private sources' 'private headers'". All is fine. It compile/install/link. But when i do "nm -C my_instaed_lib.so" i get: 00005be0 T yyget_debug(void*) 00005b00 T yyget_extra(void*) 00005bf0 T yyset_debug(int, void*) 00005bb0 T yyset_ext...
Look for the libtool option -export-symbols. Give it a list of symbols that you want to export. By default, libtool exports all symbols.
4,981,826
4,981,870
Link error while using MinGW compiler (can't find __main)
I'm trying to compile a very simple program with MinGW on Windows, but I still got link errors. The program to be compiled is just C++ hello world. Z:\dev>type test.cpp #include <iostream> int main() { std::cout << "Hello World!\n"; return 0; } Of course, just using MinGW's g++ is okay. Z:\dev>g++ test.cpp -o tes...
Instead of using ld, try using g++ to link. Try this: Z:\dev> g++ -c test.cpp -o test.o Z:\dev> g++ -o test.exe test.o
4,981,941
9,019,039
What is wrong with this context creation?
I would like to create a render context to use opengl. The wglMakeCurrent(hdc, hrc) is returning true. But for some reason OpenGL functions are ignored. Here is the code for context creation: int pixelFormat; hdc = GetDC(hwnd); PIXELFORMATDESCRIPTOR pfd; memset(&pfd, 0, sizeof(PIXELFORMATDESCRIPTOR)); pfd.nSize = si...
you can use the glGetError() function to get an error code. You can also get a textual description with the functions gluErrorString() and gluErrorUnicodStringEXT() from the utility library. Something like this: char *message; message = gluErrorString(glGetError()); printf("OpenGL error: %s\n", message);
4,982,026
4,982,032
C++ random int function
Hello dear members of stackoverflow I've recently started learning C++, today I wrote a little game but my random function doesn't work properly. When I call my random function more than once it doesn't re-generate a number instead, it prints the same number over and over again. How can I solve this problem without us...
srand(time(NULL)); should usually be done once at the start of main() and never again. The way you have it will give you the same number every time you call rolld6 in the same second, which could be a lot of times and, in your sample, is near guaranteed since you call it twice in quick succession. Try this: #include "s...
4,982,083
4,982,100
Qt Application will not compile
This has been stumping me for a while. I am trying to create a function that takes a hash table, and returns said hash table. However I am getting this error in the header file, error: ‘string’ was not declared in this scope. error: template argument 1 is invalid Here is the header file itself: #ifndef NAME_SPAWN_H...
The real name of string is std::string. Try using that instead. (You can leave off the std:: qualifier only if there's a using namespace std; directive in scope. But it's a good habit not to put using namespace std; in header files.)
4,982,123
4,982,197
Problem with linked libraries and GTK+
When trying to compile with Code::Blocks the example that comes up with GTK+: #include stdlib.h #include gtk/gtk.h static void helloWorld (GtkWidget *wid, GtkWidget *win) { GtkWidget *dialog = NULL; dialog = gtk_message_dialog_new (GTK_WINDOW (win), GTK_DIALOG_MODAL, GTK_MESSAGE_INFO, GTK_BUTTONS_CLOSE, "Hello W...
Have you added the GTK Directory containing the libglib-2.0.a, libgobject-2.0.a files to the Linker Search Directories. This can be done from the following Path: Settings | Compiler and debugger... | Search directories | Linker | Add. The full command line for the compiler/linker can be viewed in the Build Log window...
4,982,132
4,982,156
WSAEventselect Error: 10038
I've been trying to figure this out for a while now and I need help because I'm out of ideas. My WSAEventselect function returns error number 10038. Code: // Error checking.... if(netEvent.iErrorCode[FD_ACCEPT_BIT] != 0) { int temp1 = WSAGetLastError(); emit ClientErrorSi...
According to the Winsock error reference, this is a WSAENOTSOCK error, meaning you're trying to do something with an invalid socket handle. Without more information about where the error is occurring in your code I don't think I can offer much more advice than that, but I'd suggest checking to ensure that you're creat...
4,982,177
4,982,183
C++ member initialization list question
class TreeNode { // An object of type TreeNode represents one node // in a binary tree of strings. public: // Constructor. Make a node containing str. TreeNode(string str) : item(str), left(NULL), right(NULL) {} string item; // The data in this node. TreeNode *left; // Pointer...
No, you can't -- that part initializes the fields of the TreeNode class when you construct it. If you remove the part you mention, the fields will be given either default-constructed or undefined values.
4,982,237
4,982,484
Conditions where ImpersonateLoggedOnUser fails
I have a Windows service that uses ImpersonateLoggedOnUser in order to drop the system permissions and run another application using the current users rights. If the call to ImpersonateLoggedOnUser fails, an application executed by the service is going to have to have system rights by design, which is not good. I fixed...
ImpersonateLoggedOnUser will fail if you don't have the impersonate privilege or if the handle in question is invalid. I'm not sure if there are other failure modes for the API.
4,982,466
4,982,501
C++: Difference between using the new keyword vs not when instantiating class members?
For a programming assignment, we are given a template class with two members declared not as pointers, but actual objects: Foo member; In the constructor, I tried member = *(new Foo()); initially, but learned that, at least sometimes, it was copying the new Foo object, and therefore causing memory leaks. I finally dis...
Your analysis is incorrect. Both of these are memory leaks. What you are doing is allocating a new copy of the object, assigning the value to the member, and then discarding the pointer to the allocated memory without freeing that memory. It is a memory leak in both cases. Now, consider the following code: class Member...
4,982,652
4,982,690
C++ changing output on console
What is the easiest way to display changing numbers in the console? I have a normal command line program in C++ which uses cout, but I'd like to display a percentage number representing the progress which counts up to 100 without printing a new line. How is that done? (If it matters: I'm on Windows 7)
When I’ve needed that I have just output a carriage return character, in C++ \r. Remember to flush the output each time, e.g. cout << "\r" << x << "% completed. " << flush; The spaces at the end to clear previous output on the line in case of Microsoft-like fluctuating progress.
4,983,092
4,983,095
C++ equivalent of sprintf?
I know that std::cout is the C++ equivalent of printf. What is the C++ equivalent of sprintf?
std::ostringstream Example: #include <iostream> #include <sstream> // for ostringstream #include <string> int main() { std::string name = "nemo"; int age = 1000; std::ostringstream out; out << "name: " << name << ", age: " << age; std::cout << out.str() << '\n'; return 0; } Output: name: nemo, age: 1000...
4,983,097
4,983,112
Identifying characters in strings
What is the shortest way to check if a string contains the character "-" or it contains only numbers? Edit: And how would I do it in C without std::string? Which one is better?
std::string has a member function, find, which can be used to search for a character or substring. It returns std::string::npos if the search character or substring is not found. One straightforward way to test whether a string contains only digits is to use the find_first_not_of member function with the search list "...
4,983,145
4,983,424
converting string to filetime
What is the fastest way to convert a string of the form ""1997-01-08 03:04:01:463" to filetime? Is there a function which does that?
I am guessing that you are talking about a Windows FILETIME, which contains the number of 100 nanosec ticks since 1/1/1600. Use sscanf() or a std::istringstream to parse the string into its components. and populate a SYSTEMTIME struct Use SystemTimeToFileTime() to convert to a FILETIME e.g. FILETIME DecodeTime(cons...
4,983,336
4,983,355
Problem with definition in C++ under VS2010
Been working on some code and thought it would be a bit clever to try and implement some fast workaround define functions. Yet everything turned upset down when I decided to factor MostSigBit function in a single define and suddenly building my project started failing. Even rewrote this code using if-else statements, n...
A question mark is missing: #define MostSigBit(x) (x&0x80 == 0x80) (x = x<<1 ^ 0x1B) : (x <<= 1) should be: #define MostSigBit(x) (x&0x80 == 0x80) ? (x = x<<1 ^ 0x1B) : (x <<= 1)
4,983,716
4,983,723
Is there anything like a restrict keyword for C++ to indicate that _iterators_ are not aliased
g++ does implement __restrict__ for pointers, but I could not find anything about iterators. My overall intent is to encourage the compiler to vectorize stl loops. Edit: Even if the compiler is unable to vectorize, the __restrict__ keyword should be able to tell the compiler that no unnecessary reloads are necessary in...
I don't know the answer to your direct question. However, the compiler would only ever be able to vectorize a loop for std::vector, as it's the only container (I think) that has contiguous storage, and no dependencies between successive storage locations (unlike e.g. std::list). I don't know how to make it do so, tho...
4,983,835
4,983,878
Export DLLs classes and functions and import them into Win32 Application
I have a dll with a class that define some methods and variables inside it. I marked it as __declspec(dllexport) and i imported the .h header inside a win32 application project in the same solution. I can use the functions but when I try to compile the project I have a lot of errors about external symbols not resolve...
Please read about the standard way of using macros for this very common task here: http://wiki.tcl.tk/8721 The basic idea is that you define a macro, say MY_API like so: #ifdef BUILD_MYAPI # define MY_API __declspec(dllexport) #else # define MY_API __declspec(dllimport) #endif When you declar...
4,983,927
4,983,936
Is there kind of "attribute" keyword in C++?
maybe I missed something, but I'm wondering about the following: At the Mozilla Developer Pages about Coding Guidelines, I read the following: Whenever you are retrieving or setting a single value without any context, you should use attributes. Don't use two methods when you could use one attribute. Using attr...
Mozilla uses a language called IDL (interface definition language) to define interfaces for objects that are used in multilanguage contexts, such as both C++ and JavaScript. It compiles down into code in these two languages and therefore allows developers working on the project to have a single definition for their in...
4,983,964
4,984,633
C2326 function cannot access 'bar' when defining a lambda inside a local class
I have hit some strange compiler error involving local classes and lambdas. I have narrowed it down to the following example: int main() { class test { void foo(int bar) { auto lambda = [=] (int) { return bar; }; } }; return 0; } And VS10 says: error C2326: 'void main::test::fo...
I can confirm that this happens in VS10 only when the class is defined in a function and the lambda accepts a parameter. No such problems appear in g++. I believe this is indeed a bug, if you open a defect please link to it here so we can follow up on it (otherwise let me know and I'll open a defect).
4,983,972
5,062,571
What are the pros and cons of using d-pointers?
d-pointers are heavily used in Qt, they are an implementation of pimpl idiom. I know advantages and disadvantages of pimpl idiom. But I have missed the advantages of d-pointers implementation. Here and here are the samples of d-pointers. Isn't it easier to just use this? class MyClassPrivate; class MyClass { // inte...
The set of macros for d-pointer pattern provides some sort convenience and consistencies. For example, Q_DECLARE_PRIVATE ensures that the pimpl private class for Foo is named as FooPrivate, that FooPrivate befriends Foo, and creates an nice inline function (both const and nonconst versions) called d_func(). The latter ...
4,984,043
4,984,066
C++:: Share class with all others class
I am new to OOP and C++. I have a class called Database. The constructor of this class will establish connection to database. Then, I have others classes, like Users, Scores etc. I want all those classes shared the connection from Database class. How do I do that? Example of Program flow: Main function called database...
I would suggest passing in the connection to the other classes' constructors. For example: Connection conn("servername"); User u(conn, "user", "pass"); This is an alternative to a static connection which others are suggesting. Both work fine but this pattern does not make the assumption that there is only one database...
4,984,080
4,984,097
C++ members selection operators
Possible Duplicate: What is the difference between the dot (.) operator and -> in C++? C++ has the following member selection operators: . and ->. What is the main difference between them? Thanks.
. is used with non-pointers, while -> is used with pointers, to access members! Sample s; Sample *pS = new Sample(); s.f() ; //call function using non-pointer object pS->f(); //call the same function, using pointer to object . cannot be overloaded, while -> can be overloaded.
4,984,244
4,984,324
Getting pid of a process running by execute function in QProcess
How can I get a pid of a process which was run by QProcess.execute(....,....).
I don't think you can. Also, as QProcess::execute blocks until the termination of the process, the PID wouldn't be of much use anyway. If you want more control over the external process, create a QProcess object.
4,984,291
4,984,339
C++ and MySql++:: Segmentation error?
Okay, I just directly put my code here: main.cpp mysqlpp::Connection conn(false); int main() { if (conn.connect(DATABASE, HOST, DBUSER, DBPASS)) { Users a(conn, "test","pass"); //a.authenticate(); and my Users.cpp: Users::Users(mysqlpp::Connection conn, string username, string password) { this->conn = con...
you should store a pointer to a mysqlpp::Connection in your Users class then accept a pointer instead of a whole connection object in your constructor. Don't forget to update other references in your class implementation as well. main.cpp: replace mysqlpp::Connection conn(false); with mysqlpp::Connection *conn = new m...
4,984,375
4,984,417
c++ const public field vs. a getter method
I want to add unique ID (within a single session) to each object of a certain class. One solution is to use a factory function which increments some static counter. A simpler solution is to add this counter to the class itself, e.g.: class fooWithUniqueId { public: fooWithUniqueId() : id(next_id++) {...}; ...
I can use the id as a key in a map (as copy construction correctly initializes the id of the copy object) What do you mean by "correctly"? The default copy constructor will copy the ID, whether it is stored in a private or a public member variable, and you will end up with two objects sharing the same ID. This might ...
4,984,381
4,984,581
shared_ptr and weak_ptr differences
I am reading Scott Meyers "Effective C++" book. It was mentioned that there are tr1::shared_ptr and tr1::weak_ptr act like built-in pointers, but they keep track of how many tr1::shared_ptrs point to an object. This is known as reference counting. This works well in preventing resource leaks in acyclic data structure...
A shared_ptr wraps a reference counting mechanism around a raw pointer. So for each instance of the shared_ptr the reference count is increased by one. If two share_ptr objects refer the each other they will never get deleted because they will never end up with a reference count of zero. weak_ptr points to a shared_ptr...
4,984,412
4,984,477
C++, Removing an element from a pair, inside a function
I am using C++, I have a vector of paired variables, for which the first element is a vector and the second element is an integer. My problem is that I am trying to remove certain elements from this vector, and can't seem to get it to work! The code is shown below, and everything is working as I'd expect up to the lin...
You shouldn't iterate a vector AND erase elements inside the loop. When you erase elements, the vector size changes and the indexes also change. A recommended way would be to store the elements you have to remove in another structure (like a vector) and then loop to remove them. void myCode::PairRemoval(vector<myTypeDe...
4,984,502
4,984,589
How to force template <class> to be derived from BaseClassA?
Is there any possibility to force a template to be from a certain base class so that I can call the base class function? template <class T> void SomeManager::Add(T) { T->CallTsBaseClassFunction(); //... do other stuff }
Sure, you can combine type traits with SFINAE: #include <type_traits> template <class T> typename std::enable_if<std::is_base_of<your_base_class, T>::value, void>::type SomeManager::Add(T) { T->CallTsBaseClassFunction(); //... do other stuff } Although I don't really see the benefit here.
4,984,609
4,984,664
Compiling for Mac/Linux on Windows
Obviously you can't really run Mac or Linux apps on Windows, but can you compile binaries for those platforms using MSVC++ for example (plugging in additional compilers and tools obviously)? For a serious build system, you don't want one build server per platform so having an automated build server which compiles for a...
Crosstool-NG seems like your best option for Linux apps; they show that as one of the standard configurations. I do not know about Mac OS X; this question suggests that it will probably be difficult.
4,984,612
4,986,253
Program can't find libgcc_s_dw2-1.dll
Possible Duplicate: The program can't start because libgcc_s_dw2-1.dll is missing I'm using Code::Blocks and MinGW 4.4 (I think) compiler to create a C++ project. I get this system error if I run it from its directory, but not from within Code::Blocks. The program can't start because libgcc_s_dw2-1.dll is missing f...
The link commandline argument -static-libgcc should work. Another variant you could try is plain -static. If you don't want to worry about this, and still want to redistribute your binary, just copy the relevant dll from MinGW's bin directory and place it alongside your executable. This is common practice and works as ...
4,984,816
4,984,837
Return vector from function without it being destroyed
I have come across an interesting problem. I have a function in C++ that returns a vector filled with classes. Once the vector is returned, it calls deconstructors for each class that is element in the vector. The problem is an obvious one: the data is destroyed where a class points to the pointers, which get released ...
You can create anything on heap with new. You shouldn't give out from the function the references to your stack objects, as they will be destroyed as soon as the function finishes. If you prefer your function to return the vector by value, be sure that the objects inside the vector implement copy constructor (and perha...
4,984,931
4,985,034
stl:map and mirrored data access
I am getting data from a device that returns flow rate (double) and time (double). I want to store them and be able to access the data using both the flow rate to get the time and time to get the flow rate ... I'm using two stl:map containers to do this ... is there a way to use only one container? Here is the method...
Using a map of doubles to search for elements is an issue because you cannot expect doubles to compare accurately, and there is a slight possibility it will allow duplicates in. If you actually know there will be no duplicates in your data and no NaN values and you only want to sort values and make range-compares then ...
4,984,948
4,991,992
Pthread-ed filetransfer application crash
I am developing a file transfer application and am using pthreads on the receiver side for receiving multiple files. The function which is passed to pthreads calls the following function and at the end of this function I get a SIGABRT error and stack-smashing error appears on the terminal. Please help me find the bugs....
check the return code of system function, especially recv() which could return 0 or -1 you forgot to increment the buffer pointer you're givin to recv(), so each time it is called, the content of the buffer is overwritten you forgot to ensure there's a NUL character at the end of buffer before calling sscanf()
4,985,122
4,985,144
dynamic array member variables
Hey i'm new to c++ and still working out its perticularities. I'm having the darnedest time trying to figure out whats going wrong with this code. I've stepped through it and everything is calculating correctly. The issue is that value_array in the base class doesn't seem to be retaining the values once the derived ...
That's because you're violating the Rule of Three. Since your class manages a resource, it needs a copy constructor and an assignment operator. I strongly suggest replacing any T* data member with a std::vector<T> data member. Then you don't need to write those special member functions manually.
4,985,218
4,985,242
Is it possible to only use C syntax in a .mm file?
Is it possible to only use C syntax in a .mm file?
There's nothing wrong with writing .mm file that works in terms of plain old functions, strings and arrays, rather than the additions made by objective-c and c++. However, there are a few cases where valid C isn't valid C++ (or Objective-C++) which you'll want to consider (http://www.parashift.com/c++-faq-lite/big-pict...
4,985,348
4,985,492
VS C++ 2010 Express problems (IDE/header files HELL ?)
I almost finished writing the first draft of my game's logic engine which is entity / component based. It's not perfectly based on that philosophy, but I also think that how the implementation is done differs from person to person. I'm writing in C++ using OOP, STL and virtual functions. Yes, I know that virtual functi...
The only reason I can think of is a circular reference, and even though it may not be immediately evident, a simple way to check (and possibly fix) this is to add a forward declaration for the other class: class NonRenderableEntity; class Action:public NonRenderableObject { ... NonRenderableEntity *userEntity;...
4,985,351
4,985,656
c++ boost::any to define my own print ,
Am struggling a lot to find how to do to use boost::any to create a print function that can print any type using template first. template <typename T> struct printer { void print(ostream& os, const boost::any& a); }; I need to define first print(). i wish to have the real operator << for any, The idea is simple: ...
There is quite easy way to do this, described in "Beyond the C++ Standard Library: An Introduction to Boost": struct streamer { virtual void print(ostream &o, const boost::any &a) const =0; virtual streamer * clone() const = 0; virtual ~streamer() {} }; template <class T> struct streamer_impl: streamer{ void p...
4,985,414
5,713,387
How to enable gdb pretty printing for C++ STL objects in Eclipse CDT?
I'm trying to add pretty printing for STL objects in eclipse cdt. I tried to follow the steps described here: http://sourceware.org/gdb/wiki/STLSupport I checked out the python folder, but I can't seem to get this done... I created a gdbinit and selected for my debug configuration, but whenever I try to start debugging...
This is the solution that works for me. Download ( http://www.gnu.org/software/gdb/download/) and install latest gdb (i.e. with --prefix $HOME). It supports python scripting. Get python pretty printers by executing svn co svn://gcc.gnu.org/svn/gcc/trunk/libstdc++-v3/python in a directory of your choice (i.e. $(HOME)/...
4,985,432
5,195,408
Implementing a GObject interface in C++
I try to implement a GType interface in C++ using Glibmm (part of Gtkmm). The object will be passed to an API in C. Unfortunately, the documentation for gtkmm does not cover many details of how it wraps the GObject system. What I have so far: class MonaCompletionProvider : public gtksourceview::SourceCompletionProvider...
Finally, I found a solution. Class definition (order of subclasses matters): class MonaCompletionProvider : public Glib::Object, public gtksourceview::SourceCompletionProvider { ... Constructor (again, order matters): MonaCompletionProvider::MonaCompletionProvider() : Glib::ObjectBase(typeid(MonaCompletionProvider...
4,985,451
4,985,516
Get SCSI hard drive serial on Linux from a C++ program
I want to retrieve SCSI hard drive serial on Linux (Ubuntu) from a C++ program without root priveleges. I tried ioctl(fd, HDIO_GET_IDENTITY, &id) but it seems to work only for ATA devices. Does anyone have a solution for SCSI HDDs? The solution I am looking for should not require the user to have root priveleges. Any s...
How about sending a SCSI Inquiry command, as described here: http://tldp.org/HOWTO/archived/SCSI-Programming-HOWTO/SCSI-Programming-HOWTO-9.html A complete program: http://tldp.org/HOWTO/archived/SCSI-Programming-HOWTO/SCSI-Programming-HOWTO-24.html Edit: The bottom of this page shows the specific structures required f...
4,985,555
4,985,777
Segmentation Fault In My Xlib Wrapper Class (C++)
I am attempting to create a wrapper class to the Xlib library, but I get a segmentation fault! I am new to C++ and this is probably out of my depth and maybe have my goals set to high, other than that problem, can someone tell my why I'm getting this segmentation fault? source file header file main.cpp I believe this i...
Your error indicates that either the display or window parameters to XMapWindow() were incorrect. You need to include more error checking in your code, in particular for the results of the calls to XOpenDisplay and XCreateWindow. The only obvious error I can see is that you're passing the CWBackPixel flag to XCreateWin...
4,985,790
4,985,824
Which one of the following function types CANNOT be overloaded?
Taken verbatim: Which one of the following function types CANNOT be overloaded? The constructor function of a structure The constructor function of a class The destructor function of a class Any constant method of a class Any static method of a class
Since overloading, as far as I understand it, is basically having multiple functions/methods, each with the same name but a different signature, the only logical answer would be 3., the destructor, since the signature is fixed to ~ClassName().
4,985,800
4,985,978
Why is the derived class's destructor invoked on a const reference to the base class?
In GMan's answer here, the destructor of the restore_base class isn't virtual, so I keep wondering how exactly that works. Normally you'd expect the destructor of restorer_base to be executed only, after the object goes out of scope, but it seems that the derived restorer_holder destructor is really called. Anyone care...
The standard case where you need a virtual destructor is void foo() { scoped_ptr<Base> obj = factory_returns_a_Derived(); // ... use 'obj' here ... } And the standard case where you don't is void foo() { Derived obj; // ... use 'obj' here ... } GMan's code is doing something a little trickier, that turn...
4,985,909
4,986,318
How to set and read pins on the parallel port from C++?
I am helping a friend to finish a final year project in which he has this circuit that we want to switch on and off using a C++ program. I initially thought it would be easy, but I have failed to implement this program. The main problem is that Windows XP and above don't allow direct access to hardware so some we...
Have a look at codeproject: here, here and here. You'll find treasures. The 1st link works for Windows 7 - both 32 bit and 64 bit.
4,985,918
4,986,129
makefile and its uses
What is a makefile and how do I use it?
The main purpose of a Makefile is to store every you need to build your project in one place. It contains the instructions for compiling your code, linking your compiled code, packaging the executables, extracting third party tools, and many other useful things. Pretty much any command you entire at the command line ...
4,985,993
4,986,001
inheritance of abstract class
I hav a base class which is abstract. I am inheritting a new class from the abstract base which i could not instantiate an object. The reason the compiler tells is that cannot allocate an object of abstract type Is there any way to overcome this.
cannot allocate an object of abstract type This indicates you've not implemented all the pure virtual functions in the derived class. So first, implement all the pure virtual functions, then create instance of this class. You cannot create instances of class which has even a single pure virtual function! Remember, pu...
4,986,047
4,986,202
How to access structure in other program's memory?
I know how to import and use read/writeprocessmomory in C#. I'm working on game trainer. I need to have "direct" access to other process memory casted to struct. I can use readprocessmemory or writeprocessmemory but that would take much time to inplement for many structures. There is this structure in C++: class CRende...
If you need a structure to be binary compatible with a non-managed program, you can use the [StructLayout] attribute and its friends. E.g. in your case it would be something like: [DllImport("kernel32.dll", CharSet=CharSet.Auto)] public static extern IntPtr GetModuleHandle(string lpModuleName); [StructLayout(LayoutKin...
4,986,052
4,986,192
Boost property_tree - working with simple arrays or containers
I'm loading an ini file with boost property_tree. My ini file mostly contains "simple" types (i.e., strings, ints, doubles, etc.) but I do have some values that represent an array. [Example] thestring = string theint = 10 theintarray = 1,2,3,4,5 thestringarray = cat, dog, bird I'm having trouble figuring out how to g...
Yes you are doomed to parse on your own. But it's relatively easy possible: template<typename T> std::vector<T> to_array(const std::string& s) { std::vector<T> result; std::stringstream ss(s); std::string item; while(std::getline(ss, item, ',')) result.push_back(boost::lexical_cast<T>(item)); return result; }...
4,986,058
4,986,066
Function like template parametrs
Can anyone explain me, how to write template parameters like in boost::function (for example boost::function<int (float,bool)> ). What is a right syntax? I try this: template <typename T (typename Arg1,typename Arg2)> struct func{}; but it doesn't working.
template <typename T> struct func {}; int (float, bool) itself is already a type. If you only want to match types being a function with 2 parameters, create a specialization like this: template <typename T> struct func; template <typename R, typename T1, typename T2> struct func<R(T1,T2)> { typedef R return_type;...
4,986,198
4,986,386
Introspecting struct definition in C++?
So I'm working on a file format for storing structured data defined over some kind of range. The simplest example would be something like float values over time, but I'm designing it to allow multiple dimensions and arbitrary data at each point. I'd like to store the structure of the data in the file header as well be...
Not exactly what you're looking for, but probably a very good source for inspiration, would be Google's Protobufs. They take a slightly different approach than the ones that you discussed in your question. With protobuf, first you describe your data structures in .proto files, and then the protobuf compiler (protoc) co...
4,986,341
4,986,378
Where should I prefer pass-by-reference or pass-by-value?
In what circumstances should I prefer pass-by-reference? Pass-by-value?
There are four main cases where you should use pass-by-reference over pass-by-value: If you are calling a function that needs to modify its arguments, use pass-by-reference or pass-by-pointer. Otherwise, you’ll get a copy of the argument. If you're calling a function that needs to take a large object as a parameter, p...
4,986,561
4,986,588
C++ Win32 GUI switch statement error
I'm making a Win32 GUI project using Code::Blocks and the MinGW compiler. At this line of my code: switch(LOWORD(WPARAM)) which is the switch statement for which menu button was clicked, I get the following error upon compiling: error: expected primary-expression before ')' token I found some other cases of this err...
The problem is that LOWORD(WPARAM) Is calling the LOWORD macro on the WPARAM type rather than a variable of type WPARAM. This would be similar to calling printf(char *); For example. To fix this, change the code so that it calls LOWORD on a WPARAM variable. Most window procedures name this wParam, so you might wan...
4,986,673
4,986,802
C++11 rvalues and move semantics confusion (return statement)
I'm trying to understand rvalue references and move semantics of C++11. What is the difference between these examples, and which of them is going to do no vector copy? First example std::vector<int> return_vector(void) { std::vector<int> tmp {1,2,3,4,5}; return tmp; } std::vector<int> &&rval_ref = return_vecto...
First example std::vector<int> return_vector(void) { std::vector<int> tmp {1,2,3,4,5}; return tmp; } std::vector<int> &&rval_ref = return_vector(); The first example returns a temporary which is caught by rval_ref. That temporary will have its life extended beyond the rval_ref definition and you can use it as...
4,986,844
69,833,093
What does "cdecl" stand for?
Yes, I know that "cdecl" is the name of a prominent calling convention, so please don't explain calling conventions to me. What I'm asking is what the abbreviation (?) "cdecl" actually stands for. I think it's a poor naming choice, because at first sight it reminds one of "C declarator" (a rather unique syntactic aspe...
The term CDECL originates from Microsoft's BASIC and their Mixed Language Programming ecosystem. The ecosystem permitted any of the Microsoft's four major languages (BASIC, FORTRAN, Pascal and C) to make calls to any other. Each language had a slightly different calling convention, and each had a way to declare an exte...
4,986,847
4,988,787
I'm looking for any optimizations I can make in a graphics editing program
Heyo, this is my first time asking a question here so do forgive me if I mess somethin up >~< I'm working on a program similar to openCanvas, the earlier ones that allowed multiple people to draw on the same canvas in real time over the internet. OC's really buggy and has a lot of limitations, which is why I wanted to ...
Data Structure You should definitely use a quadtree (or another hierarchical data structure) to store your canvas and its nodes should contain much smaller blocks than 512x512 pixels. Maybe not as small as 1x1 pixels, because then the hierarchical overhead would kill you - you'll find a good balance through testing. Dr...
4,986,876
4,986,928
Garbage Appended to Output When Reading Values from a File
I'm new to C++ file io, so the other day I decided to write a small program that simply reads a UTF-8 encoded string and a paired float from a binary file. The pattern is string-float with no extra data or spacing between pairs. EDIT I've revised the code based on several answers. However, the output remains the same (...
There are at least two issues. First, the line: file->read(reinterpret_cast<char*>(stringSize), sizeof(char) * 2); Probably should take the address of stringSize: file->read(reinterpret_cast<char*>(&stringSize), sizeof(stringSize)); Second, the line: char* buffer = new char[stringSize]; Doesn't allocate enough memor...
4,986,990
4,987,011
Ways to call a function on return
Whenever I have 2 specific functions, one that I want called upon entry of a function, and one that I want called upon return in a function, I usually use a helper class and put the functions that I want called in the constructor and destructor - then just instantiate an object of that class at the beginning of a funct...
This is a fairly common technique. More specifically, the destructor will be called when leaving the scope where the object was initialized, which might be before the function returns. One use of this is with locks, where a helper object is used to do the unlock when it is destroyed. This is the only way to ensure a fu...
4,987,016
4,987,041
Segmentation fault when appending two chars - C++
I am trying to append two chars but for some reason I am getting a segmentation fault. My code is like; #include <string.h> char *one = (char*)("one"); char *two = (char*)("two"); strcat(one, two); and I seem to be getting a segmentation fault at strcat(one, two), why is that?
http://www.cplusplus.com/reference/clibrary/cstring/strcat/ the first parameter to strcat, must be big enough to hold the resulting string try: //assuming a,b are char* char* sum = new char[strlen(a) +strlen(b)+1]; strcpy(sum,a); strcat(sum,b);
4,987,432
4,987,544
Help with implementing a function to change size of dynamic array
I'm trying to write a function that will change the size of a dynamic array to a new size. In my header file, I have: Image **images; //pointer to a dynamic array of image pointers int maximum; //size I want to do this by allocating a new array and copying the values over without changing their indices. If there are n...
images=newArray; for (int i =0;i<newmax;i++) *images[i]=*newArray[i]; This is odd. images and newArray are now the same, hence no need to copy the contents of newArray back to itself. So remove this loop? Also, need to add: maximum = newmax; If the '1' is the index, this should cause firstScene->addpic...
4,987,477
4,987,490
C++ unexpected array output
//Page 215, #2, by Jeremy Mill //program taken in 7 values, displays them, and then sorts them from highest to lowest, and displays them in order. #include <iostream> #include <iomanip> using namespace std; int main() { //Define the variable we will need const int arraySize = 6; double dailySales[arraySize]; ...
Be carreful when looping through your array. The loop has to start from 0 to size-1. So instead of using less-than-or-equal: for (int a = 0; a <= arraySize; a++) You should use less-than: for (int a = 0; a < arraySize; a++)
4,987,658
4,990,051
Include third party libraries in source tree
My CMake C++ project depends on several commercial libraries (only libs and headers are available). I want an easy way to include these packages in my source tree. I have tried the following options: Use svn:externals and provide these libraries in a thirdparty folder of the source tree. Pros: easy. Cons: slow downloa...
The desired workflow can be achieved by adding the third party libraries as CMake external projects. The ExternalProject_Add command lets you automatically download, build and install third-party libraries.
4,987,661
4,987,707
Member functions same as passing reference to global function?
Can I be sure that: class foo { public: int x; void bar(int k) { x = k; } }; foo o; o.bar(5); Will be the same as: class foo { public: int x; }; void foobar(foo& f, int k) { f.x = k; } foo o; foobar(o, 5); I know both will set "x" to "k", but can I be sure that they both perform at same speed / ge...
I know both will set "x" to "k", but can I be sure that they both perform at same speed / generate same asm? Practically, you can be sure it doesn't matter. If you think it matters, then profile and compare the differences, or look at asm output from your compiler. Can the compiler optimize methods greater? Genera...
4,987,785
4,987,809
Why result output is integer even result is defined as float?
#include<iostream> using namespace std; int main(int argc, char** argv){ float result; result=(340/101); cout<<"Result="<<result; } in this code result is=3, i'm curious about why is that? what is the prevention of this cause and it can be seen a minor problem but it really deprecate my resu...
340 is an integer and 101 is an integer, so 340/101 performs integer division. The result of the division is converted to a float when it is assigned to result. You need to cast one to a floating point type to have floating point division performed: result = static_cast<float>(340)/101; or just use a floating literal...
4,987,845
4,987,884
Inserting values into a map
typedef map <int, string> MAP_INT_STRING; MAP_INT_STRING mapIntToString; mapIntToString.insert (MAP_INT_STRING::value_type (3, “Three”)); I have only found examples where the values are inserted into the map through the source code. I would like to know how to allow a user do so as the program is running. I i...
now, speaking seriously. first you need to take values from users and then to insert them into your map. something like this: std::map<int, std::string> m; while (true) { std::cout << "please give me an int\n"; int i; std::cin >> i; std::cout << "now gimme some string\n"; std::string s; std::cin...
4,987,879
4,990,055
Options for inter-service one-way communication
I'm searching for different options for implementing communication between a service and other services/applications. What I would like to do: I have a service that is constantly running, polling a device connected to a serial port. At certain points, this service should send a message to interested clients containing ...
There are a number of ways to do a broadcast system, but you'll have to either give up reliability (ie, some messages must be lost) or use a proper subscription system. If you're willing to give up reliability, you can create a shared memory segment and named manual-reset event object. When a new message arrives, write...
4,987,894
4,987,956
Find the running time in Big O notation
1) for (i = 1; i < n; i++) { > n 2) SmallPos = i; > n-1 3) Smallest = Array[SmallPos]; > n-1 4) for (j = i+1; j <= n; j++) > n*(n+1 -i-1)?? 5) if (Array[j] < Smallest) { > n*(n+1 -i-1 +1...
Is this an algorithm given to you, or one you wrote? I think your loop indexes are wrong. for (i = 1; i < n; i++) { should be either for (i = 0; i < n; i++) { or for (i = 1; i <= n; i++) { depending on whether your array indexes start at 0 or 1 (it's 0 in C and Java). Assuming we correct it to: for (i = 0;...
4,987,955
4,987,980
Why does this work and how? Non-static Qt object
I'm a little confused and would like to clear this up. //QDir()::rmdir is from Qt Creator auto complete. //It does not work. //Says no such static function.I looked it up, turns out to be true. //Fair enough...though I'm not sure why auto-complete suggested it. bool success = QDir()::rmdir("Y:/dir1/dir2/dir3"); //Do...
One of the QDir constructors is: QDir ( const QString & path = QString() ) Your QDir().xxx code is calling this constructor, which then uses default to using a QString() as one argument. This is safe and normal to do.
4,988,236
4,988,315
How to I compress a tarball with gzip?
Hey, I was wondering if anyone knew how I could compress a tarball file with gzip. I checked out this already and compressed a tarball successfully, although I want to then compress that tarball with gzip instead of libbz2. I have also tried implementing the gztack function from the gzappend.c example from the zlib sou...
Use the zlib routines gzopen to open a compressed stream, gcwrite to write data to it and compress it, and gzclose to close it. Here's a complete program that compresses one file to another: #include <errno.h> #include <stdio.h> #include <string.h> #include <zlib.h> int main(int argc, char **argv) { if(argc < 3) ...
4,988,331
4,988,364
Why reading Floating point number from file gives rounded output?
i have a file and two inputs are shown below: 34.800287000 0.077352000 i'm reading from a file(by getline then define stringstream) and saving it in my class variables which are both defined double. However when i check my variables i see that: 34.8003 0.077352 EDIT: i'm using cout to check my variables. why is th...
The standard IO streams classes have a limit to their precision that can be customized at runtime. By default I believe it's six places, which matches the output you're getting above. If you want to increase the precision, you can use the setprecision stream manipulator: double myValue = /* ... */ cout << setprecisio...
4,988,448
5,296,177
Algothm Analysis bigO and normal notation
int I(int i, int j, int n) { return n * i + j; >1 } int DotProduct( int A[], int B[], int i, int j, int n ) { int t=0; >1 for(int k=0; k<n; k++ ) > n+1 t += A[ I(i,k,n) ] * B[ I(k,j...
You start from the beginning: you first need to calculate the time it takes tu run an average case MMultiply: The first thing you can see in MMultiply is a loop from 0 to n - 1, that gives you: T(MMultiply) = n*(T(what_is_inside_the_first_loop)) Now you need T(what_is_inside_the_first_loop). As you only have another lo...
4,988,939
4,989,141
How do boost::variant and boost::any work?
How do variant and any from the boost library work internally? In a project I am working on, I currently use a tagged union. I want to use something else, because unions in C++ don't let you use objects with constructors, destructors or overloaded assignment operators. I queried the size of any and variant, and did som...
If you read the boost::any documentation they provide the source for the idea: http://www.two-sdg.demon.co.uk/curbralan/papers/ValuedConversions.pdf It's basic information hiding, an essential C++ skill to have. Learn it! Since the highest voted answer here is totally incorrect, and I have my doubts that people will a...
4,989,048
4,989,111
Best Cross Platform way to obtain OS version in C++
Hey, I'm a bit new to C++ and am writing a simple program. My program will be using some folders in Windows 7 path: C:\Users\%username%\Appdata\Local... Windows XP path: C:\Documents and Settings\%username%\Local Settings\Application Data... Unix: /home/%username%/.hiddenfolder/... now the problem is win...
You don't need OS version at all. On *nixes (well, on Linux and OSX for sure, but should be on others too) you can use HOME environment variable. On Windows, you must (yes, must, because paths can be remapped/localised and hard-coding them is nice way to having more work than necessary) use SHGetFolderPath function (it...
4,989,067
4,989,155
speed of handling input: growing an array, or counting input, allocating, and then reading
Basically I am wondering what would be a faster way of handling input from standard input: Method one: Declaring an array of some arbitrary size, reading into the array, and if the input is more than the size, allocate a new array twice the size, copying the contents into the new array, and deallocating the previous ar...
Both methods are O(n). However, you're reading from stdin, so there's no way to rewind it back to the beginning unless something is already storing the data somewhere, so I don't see how you could use method 2. You would need to use method 1. If you can use realloc, it might not even have to do any copying. If you're w...
4,989,228
4,989,245
Trying to jump directly to a node in a linked list
Hello I dont know if there is a command in C++ which I can use to jump directly to 5th node in a linked list? I know with : p->next i can try to go to the next node but what if I want to go to the 56th right awat is there a way ? like p->next(56) or something ? Thanks
If the linked list does not have a command like p->get(56) built in then you have to write your own function that uses a for loop. It takes the list and the number of the element you want and then calls next that number of times.
4,989,301
4,989,556
How to print superscript 2 in c/c++?
I'm trying to do print a square mark in following code: code 1: char* exp = new char[300]; *(exp) = 178// which is 2's extended ascii code *(exp+1) = '\0'// end of string printf("%s",exp);` it will print "?" and seems like the little 2 will join the next letter automatically: code 2: char* exp = new cha...
The ASCII charset only covers English letters, numbers and a bunch of other characters, but nothing fancy like squared symbols, diamonds or clubs and the like. Those characters are outside the ASCII specs and depends on which coding will be assumed by whoever reads your output. Also all non-English characters (e.g. Chi...