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
7,797,503
7,797,541
Is there a Preprocessor Option that display when header files are preprocessed?
Looking through the MSDN, I would say no; however, I thought I would ask here before I give up. Is there a preprocessor option for Visual Studios that displays when a header file is included? Specifically, I'm looking for something similar to /verbose:lib described in the link below. http://msdn.microsoft.com/en-US/li...
The switch /showIncludes (List Include Files) is what you are looking for, as documented in MSDN. Here is a sample of the output produced by that switch: Given the file main.c, consisting of: #include "foo.h" and the file foo.h, consisting of: #include "bar.h" The output produced is: Note: including file: d:\temp\foo...
7,797,839
7,797,872
why does the array decay to a pointer in a template function
I don't understand why the array decays to a pointer in a template function. If you look at the following code: When the parameter is forced to be a reference (function f1) it does not decay. In the other function f it decays. Why is the type of T in function f not const char (buff&)[3] but rather const char* (if I un...
Because arrays can not be passed by value as a function parameter. When you pass them by value they decay into a pointer. In this function: template <class T> void f(T buff) { T can not be char (&buff)[3] as this is a reference. The compiler would have tried char (buff)[3] to pass by value but that is not allowed. So ...
7,797,927
7,798,441
PutFile not sending file from active directory?
pConnect->SetCurrentDirectory( "C:\\FilesToSendToServer" ); //Need this set on client, i believe currently setting on server. CFtpFileFind finder(pConnect); finder.FindFile( "*", INTERNET_FLAG_DONT_CACHE | INTERNET_FLAG_EXISTING_CONNECT ); finder.FindNextFile(); CString filename = finder.GetFileName(); //finds the only...
It looks like you were meaning to call the win32 API SetCurrentDirectory. This will change the local directory instead of the remote directory that pConnect->SetCurrentDirectory changes. Try ::SetCurrentDirectory if you're in a namespace. Of course your working directory will no longer be C:\uploadApp...
7,798,237
7,798,992
passing "this" to a thread c++
What is the best way of performing the following in C++. Whilst my current method works I'm not sure it's the best way to go: 1) I have a master class that has some function in it 2) I have a thread that takes some instructions on a socket and then runs one of the functions in the master class 3) There are a number of ...
Sounds good to me. In my servers, it is called 'SCB' - ServerControlBlock - and provides access to services like the IOCPbuffer/socket pools, logger, UI access for status/error messages and anything else that needs to be common to all the handler threads. Works fine and I don't see it as a hack. I create the SCB, (an...
7,798,242
7,798,824
Keyboard / Mouse input in C++
I'm wondering how to accept keyboard and mouse input in C++, using Visual Studio 2010, for Windows 7 32-bit. --EDIT: I forgot to mention that I need keyboard / mouse input without interrupting the flow of the program. Something like a listener. I don't want to have to pause the program and ask for input, and then have...
keyboard / mouse input without interrupting the flow #include <windows.h> #include <iostream> using namespace std; int main() { HANDLE hIn; HANDLE hOut; COORD KeyWhere; COORD MouseWhere; COORD EndWhere; bool Continue = TRUE; int KeyEvents = 0; int MouseEvents = 0; INPUT_RECORD InRec...
7,798,629
7,798,669
File Input and Errors on Compile
Hello Users of Stack Overflow! I'm having an issue with a program I'm attempting to write in C++. Every time I compile my code I get the following Errors: FCS2Phase.cpp: In function `int main(int, char**)': FCS2Phase.cpp:47:15: error: request for member `open' in `userfile', which is of non-class type `std::ifstream()'...
The following line should be ifstream userfile; instead of ifstream userfile();
7,798,644
7,799,539
I'm using boost::spirit to write a parser lexer
I'm using boost::spirit to write a parser, lexer here is what i want to do. i want to put functions and classes into data structures with the variables they use. so i want to know what would be the best way to do this. and what parts of boost::spirit would be best to use for this? the languages i want to use this on ar...
Spirit is a fine tool, but it is not the best tool for all parsing tasks. And for the task of parsing actual C++, it is pretty terrible. Spirit excels at small-to-mid-level parsing tasks. Language that are fairly regular, with standardized grammars and so forth. C and C-derived languages are generally too complicated f...
7,798,793
7,798,838
convert character array of numbers to integers
I am creating a console program that asks for users to input integers between 0 and 100 and then outputs each number and how many times is was entered. Each number the user enters is separated by a space and input ends when 0 is entered. So far i am using cin.getline to store the numbers in a character array. This limi...
Instead of using cin.getline simply do: int input; while( cin >> input, input != 0 ) { ...do computations or store it somewhere... } That will get you the input in integer form.
7,798,875
7,799,177
Tesseract function with no implementation
I am trying to create a project using Tesseract in something other than Visual Studio but there doesn't seem to be any documentation on how to go about doing this. The problem I am at now is that file scanutils.cpp calls a function open(char *, int, mode_t) and this isn't defined anywhere. Is this possibly a Unix func...
open() is a Posix function that usually wraps the open system call in conforming systems. This is a rather "low-level" function that is very platform specific. The portable C function that provides the equivalent functionality is fopen(), in the sense that the result of open() is the same as FILE * fp = fopen(...); int...
7,798,986
7,799,066
Function Pointer to member function of template class? (C++)
I've been butting my head against this problem in an assignment I've been working on, and can't seem to get it to work at all. I wrote a little test class to demonstrate what I'm trying to do, and hopefully someone can explain what I need to do. //Tester class #include <iostream> using namespace std; template <typenam...
You're not calling the member function pointer corrently; it requires the use of a special operator called the pointer-to-member operator. template <typename T> inline void Tester<T>::doFcn( FcnPtr fcn ) { (this->*fcn)( this->data ); // ^^^ }
7,799,102
7,799,285
how to use c++ from visual studio 2010 professional - I only see templates for c# and F#
I want to compile some open source C into a x64 dll for azure. I have Visual Studio Professional, but only C# and F# are showing up in project templates, no C++. How do I get C or C++ project templates to show up?
If you have installed support for C++ you'll see the templates under Other languages in the new project window (That if you didn't set your environment for C++ development during the first run) Otherwise you have to run VS2010 setup again and install VC++ support
7,799,348
7,799,476
Is it more efficient to declare variables late?
Is it more memory or possibly computationally efficient to declare variables late? Example: int x; code .. . . . x is able to be used in all this code . actually used here . end versus code .. . . . int x; actually used here . end Thanks.
Write whatever logically makes most sense (usually closer to use). The compiler can and will spot things like this and produce code that makes the most sense for your target architecture. Your time is far more valuable than trying to second guess the interactions of the compiler and the cache on the processor. For e...
7,799,394
7,806,838
Howto look up an SRV record pointing to an IPv6 address
My C++ application has to lookup a DNS SRV record pointing to an IPv6 address. From what I researched so far, the res_search() family of functions is the way to go. Does anyone have an example how to prepare such a query and how to extract the IPv6 result ?
res_search() (or req_query) is probably the way to go to obtain the initial SRV record. However the SRV record can only contain a hostname, not a literal IPv6 address. You should feed the hostname contents of that record into the getaddrinfo() function which can then look up both IPv4 and IPv6 addresses at the same tim...
7,799,493
7,799,576
Include C++ library in Netbeans 7.0
I'm trying the use this library (RollPlay) in my project but I don't know how to include it in my C++ project in Netbeans. Would I just add the .dll and .h files into the project folder, add the files to the project? I'm new to Netbeans and using non built-in libraries.
A library would normally reside in its own installation directory so you would need to point NB to where that is. If you right-click the project name in the "Projects" window, you'll have a Properties option. Select the Build/C++ compiler option to add the directory for the .h files. Select the Build/Linker to add...
7,799,705
7,801,286
boost::regex vs std::regex - can't find empty() method?
Replacing boost::regex with std::regex since we are using gcc 4.6 in the company I ran into an issue with empty () method of that class - it basically didn't make it from boost::regex into std::regex class. I am not sure whether this is a gcc's issue or this method didn't make it into C++11 standard at all, but that pi...
empty() got removed from std::regex a long time ago. N1507 (2003-09-16) was the original paper to suggest its removal (search for "What is an invalid/empty regular expression?"). This issue was directed at what then was std::tr1:regex. It was recorded in the LWG tr1 issues lists as issue 7.28 and contained the follo...
7,800,088
7,810,952
QGLWidget not receiving calls to resizeGL after initialization
I am having what appears to be the same problem as asked in this (unanswered) question: Qt resizeGL problem I am testing a new QGLWidget for a larger application. The resizeGL method is wired up to change the glViewport and repaint the OpenGL view. My QGLWidget is not part of a layout and is simply being created displa...
I resolved my problem with some help from my co-worker. As it turns out, I had implemented the event method and forgot to call the QGLWidget::event method inside it. The widget now correctly resizes.
7,800,144
7,800,225
issue reading in data
I am having trouble reading data from a file into a list in a class. It seems like an extra hexadecimal value is being picked up somewhere. Data: (what I want output to look like) Output: (extra 0x4463c4 is randomly included) Here is a bit of code i think is relevant. Can anyone advise me of errors I may have made? ...
You're passing structs objects to cout, which doesn't know how to display them. The hex values you get are your structs objects addresses.
7,800,460
7,801,357
How do you plot points in QT?
I am writing an application in C++ with QT where you have n points and compute the convex hull of this. However, once this is computed I have no idea how to plot the points and draw the border of the hull. Making menu buttons and such is simple enough, but I'm not sure I know the tools to do this. How do you do this?...
You can just create a custom class deriving from QWidget where you override the void paintEvent(QPaintEvent* event) method. In that you put the points into some sort of point list, either std::vector<QPoint> or QList<QPoint> and then paint it with a Polyline method. For instance: void Foo::paintEvent(QPaintEvent* event...
7,800,548
7,800,606
c++ template input validation
I am using the following for easily extracting input and validating the correct type. However, the end of file EOF is not being fired. template< typename T > std::istream& read(std::istream &istr, T &val) { std::string s; std::getline(istr, s); if (istr.good()) { s.erase(s.find_last_not_of(" \n...
iss >> val reads all the characters and "touches" the end of stream, so it sets off EOF every time. template< typename T > std::istream& read(std::istream &istr, T &val) { std::string s; std::getline(istr, s); if (istr.good()) { std::istringstream iss(s); //leave the '\n' if (! (iss >> val...
7,800,575
7,800,622
initialize array passed by pointer
The function cannot initialize an array because sizeof() returns bytes of an int pointer not the size the memory pointed by myArray. void assignArray(int *myArray) { for(int k = 0; k < sizeof(myArray); ++k) { myArray[k] = k; } } Are there other problems ? Thanks
I don't see other problems. However, you probably wanted this: template<int sz> void assignArray(int (&myArray)[sz]) { for(int k = 0; k < sz; ++k) { myArray[k] = k; } } Unless, of course, even the compiler doens't know how big it is at compile time. In which case you have to pass a size explicitl...
7,800,638
7,800,876
How to read n integers from standard input in C++?
I need to read something like: 5 60 35 42 2 38 6 5 8 300 1500 900 And then save the first line in an array. After calling other functions do the same with the next line, and so on. I try with gets() and then use sscanf() to scan the integers from the string, but I don't know how to read n numbers from a string.
I've seen input files like this for competitions before. If speed is more of an issue than error detection, you could use a custom routine. Here's one similar to that I use: void readintline(unsigned int* array, int* size) { char buffer[101]; size=0; char* in=buffer; unsigned int* out=array; fgets...
7,800,646
7,800,739
error C2678: binary '=' : no operator found which takes a left-hand operand of type 'const Recipe' (or there is no acceptable conversion)
I'm trying to sort a vector that contains an int and a string in each element. It is a vector of class type called vector recipes. Getting the above error, here's my code: In my Recipe.h file struct Recipe { public: string get_cname() const { return chef_name; } private: int recipe_id; strin...
Menu::show() is declared const, so inside of it Menu::recipes is considered to have been declared as std::vector<Recipe> const. Obviously, sorting a std::vector<> mutates it, so Menu::show() must not be const (or Menu::recipes must be mutable, but this seems semantically incorrect in this case).
7,800,828
7,800,841
equal to operator == can be used to do checking bit ?
What is the purpose of the function ? bool whatIsIt(double n) { return n == n; } It can be used to check every bit in n ? I doubt that . Any comments are appreciated.
It could be used to check if n is NaN (not a number), since NaN does not compare equal to itself. Probably a finnicky and not entirely reliable way to do it. (see Billy's various comments) C99 and C++11 have the isnan() function.
7,800,905
7,801,023
Affine Transform, Simple Rotation and Scaling or something else entirely?
The scenario goes like this: I have a picture of a paper that I would like to do some OCR. So take the image below as my input example: After successfully detecting the area that corresponds to the paper I'm left with a vector<Point> of 4 coordinates that define its location inside the image. Note that these coordinat...
I think http://felix.abecassis.me/2011/10/opencv-rotation-deskewing/ and http://felix.abecassis.me/2011/10/opencv-bounding-box-skew-angle/ will come in handy. The aforementioned posts don't cover perspective warping (only rotation). To get the best results, you'll have to use warpPerspective (maybe in conjunction with ...
7,801,053
7,801,090
Scripting language interpreter source code to learn from
I want to read, and learn from, the source code of a scripting language's interpreter/compiler. What scripting language interpreter/compiler has the simplest, cleanest, and easiest to read source code? I would prefer it to be written in C/C++ (what else are compilers written in anyway?) because I'm planning on writing ...
Take a look at lua, you can go through the firsts versions of the programming language and see how it has evolved. It's written in C and has a clean and nice code. You can write a compiler in almost every programming language, but C has been the one that most programmers chose.
7,801,109
7,801,139
Does the C++ standard library have a set ordered by insertion order?
Does the C++ standard library have an "ordered set" datastructure? By ordered set, I mean something that is exactly the same as the ordinary std::set but that remembers the order in which you added the items to it. If not, what is the best way to simulate one? I know you could do something like have a set of pairs with...
No single, homogeneous data structure will have this property, since it is either sequential (i.e. elements are arranged in insertion order) or associative (elements are arranged in some order depending on value). The best, clean approach would perhaps be something like Boost.MultiIndex, which allows you to add multipl...
7,801,216
7,801,290
is a program with threads in c/c++ supposed to run faster than a serial one?
I am learning the concept of threads in c/c++. I was trying the examples for the dot product of two vectors cited in Pthreads Overview. Serial version Pthreads version I ran both the serial and the thread version of the code and I found that the serial version was faster than the thread version. I thought it should b...
The code that link to has a few issues that you need to keep in mind: The serial version is doing an inner product of two length-100 vectors. The parallel version is doing an inner product of two length-400 vectors. You can see that in the array allocation (e.g., a = (double*) malloc (NUMTHRDS*VECLEN*sizeof(double)); ...
7,801,228
7,801,370
Can I specialize a class template with an alias template?
Here's a simple example: class bar {}; template <typename> class foo {}; template <> using foo<int> = bar; Is this allowed?
$ clang++ -std=c++0x test.cpp test.cpp:6:1: error: explicit specialization of alias templates is not permitted template <> ^~~~~~~~~~~ 1 error generated. Reference: 14.1 [temp.decls]/p3: 3 Because an alias-declaration cannot declare a template-id, it is not possible to partially or explicitly specialize an alias te...
7,801,236
7,815,529
How do I create a function object which modifies its arguments?
I'd like to replace SomeFunction and SetArg with something more generic from boost. It looks like something that can be done with bind in combination with lambda, but I don't know how. This code is very simple but the reason I'd like to replace it is because I need one for 2 and 3 etc arguments. template<class T> struc...
Here is what I came up with. The operator() of setter would probably require some tweaking as we are not really benefiting from the possible move semantics here, but I can't figure that out right now. Also note that this makes heavy use of C++11 features which might not be available to you. #include <string> #include <...
7,801,308
7,801,326
Simple C++ vector/pointer gaffe
This is definitely really simple. I have been out of C++ for a few years, so I need some help with figuring out why this won't compile. I have a class called 'PointList'. In the header file, I have the following: public: PointList(); private: std::vector< Point* > *pl; In the .cpp file, I have the following...
Are you using using declarations. If not you need to prefix vector with namespace std:: in your cpp file
7,801,397
7,801,422
What kind of VS 2010 C++ Project I must choose to compile a simple Borland C++ 5 Console app?
I have a simple Win32 console (no vcl) app written in Borland C++ 5, now I want compile the same application in VS 2010. but I'm new using this IDE and I don't know how run the code in VS. I tried choosing Win32 Console Application. but even i very simple app like this #include <iostream.h> #pragma hdrstop #pragma a...
<iostream.h> is deprecated, and VS10 does not support it, use <iostream> instead, and you'll also need std::cout, std::endl , etc.. i.e. #include <iostream> #pragma hdrstop // #pragma argsused // I don't believe this is valid in VS10 int main(int argc, char* argv[]) { std::cout << "Hello" << std::endl; st...
7,801,438
7,801,456
When does a std::priority_queue<> sort itself?
I was wondering when the C++ STL priority_queue sorts itself. I mean does it insert it into a correct place when you push the item in, or does it sort itself and give you the item of highest priority when you peek or pop it out? I'm asking this because my priority_queue<int> will contain an index to an array that may h...
The work is done during push() and pop(), which call the underlying heap modification functions (push_heap() and pop_heap()). top() takes constant time.
7,801,477
7,801,492
when do not use open source code?
Are there some cases where it may not be a good idea to use the code of an open source project even though your company might allow you to do so? Some cases that I think might be valid are: The code may be implemented in a different languages. It is not portable It may need some other close-source libraries What mi...
Yes, some open-source licenses may require you to expose your source code, e.g GPL. http://encodable.com/tech/blog/2006/02/25/Why_the_GPL_is_Incompatible_with_Commercial_Software
7,801,570
7,801,860
AABB in Frustum Defined by 8 corners
It seems like every example I can find has to do with using DirectX or OpenGL and it is confusing the snot out of me... I am not using either of these so i do not have any sort of view or clipping matrix. I have a view frustum shaped element(i have the 8 corner coordinates) and i need to see if an axis aligned box is i...
You need to look for AABB culling in World Space. If you have the 8 corner coordinates of the frustum shaped element, you can construct the 6 planes of the view frustum. From there you can determine the various cases where the box intersects the frustum (or not), not to forget the case where the box totally encloses ...
7,801,686
7,801,702
ispunct() not removing commas in the middle of a string
I have a string that consists of: UNIX is basically a simple operating system, but you have to be a genius to understand the simplicity. I have the following code that is supposed to strip this string of all punctuation. The test variable is my string: if(std::ispunct(test[test.length()-1])) { test.erase(...
Well, you're only doing this for test[test.length()-1] (the last character in the string). There's no comma there, just the period.
7,801,688
7,801,732
error invalid conversion C++
I think I know why I am getting this error, but I'm not sure how to correct it.. template <typename T> std::ostream& operator<<(std::ostream& os, const btree<T>& tree) { queue < btree<T> > q; class list <node<T>*>::iterator itr = bt.neighbours.begin(); for (; itr != bt.neighbours.end(); itr++) { os << (*...
Change the queue::push statement for pushing an object: q.push(*((*itr)->left()));
7,801,690
7,801,981
Why do I get compilation errors after I conditionally include stdafx.h?
I'm trying to write a program that compiles in Borland C++ and Visual C++. To do this, I add #ifdef _MSC_VER to include the stdafx.h file when the source is compiled under VS. The code compiles and executes OK in Borland C++, but in VS, it fails: error C1020: unexpected #endif #ifdef _MSC_VER //I'm in VS #include "st...
The way MSVC implements precompiled headers, is basically that the compiler ignores everything up to the line that brings in the precompiled header, and starts over from scratch there. So when you compile your program, it doesn't "remember" the #ifdef line, so the #endif line makes no sense to it. The thing is, there'...
7,801,711
7,807,299
Qt 4 for symbian - If the project build by Qt4 Creator in mac, can it deploy to symbian by Window?
I cannot include the QCA in my project. And people says "Build Plugin / lib on mac" in easy. So that i'm planning to build in on Mac (Qt4 Creator) and copy back to window for final deployment. Is it ok? Any suggestion? Thanks.
Why not also deply from Mac? And if you plan to only create SIS package and sign it then you can do it everywhere - providing that you have all the needed files.
7,801,925
7,874,653
Porting OCTAVE C++ to iOS
i'd been surfing the web for several hours finding always the same sites and no real answer to my query. Here's the thing, i'd like to port some of the Octave functions to a iPad/iPhone app. i'd already tried to mix C++ with Obj-C and it works like a charm BUT i haven't been able to find the right source of OCTAVE to ...
This may not answer your question, but might help: If the Octave functions you are using are relatively simple, you could try using a linear algebra package such as Armadillo. The docs contain a conversion sheet from Octave/MATLAB to C++.
7,801,967
7,802,323
memcpy -- copying uint64 to char *
I just don't know what memcpy works. You can simply copy paste the code and see how the output doesn't add up. I know I can write the code in some other ways but I just wonder why memcpy does not work. typedef unsigned char* bitmap; #define getbit(n,bmp) ((bmp[(n)>>3])&(0x80>>((n)&0x07))) #define setbit(n,bmp) {bmp[(n)...
I believe you are having an issue with endianness. When you cast your buffer to a uint64_t you are casting your buffer into a little endian uint64_t. So your bytes would then be ordered as follows: ie. buffer: | char 0 | char 1 | char 2 | ... | char n uint64_t: | byte 8 | byte 7 | byte 6 | ... | byte 0 You are then...
7,802,110
7,802,149
Separate static variable inside class member function among instances
MyClass::Foo() { static bool isFirst = true; if (isFirst) do something; isFirst = false; } MyClass::Bar() { static bool isFirst = true; if (isFirst) do something; isFirst = false; } I have used the above structure and it worked well so far when I worked with only one instance of the class. The prob...
The problem is all instances of MyClass seem to share the static variable. That is exactly what a static variable is. How can I make the variable not-shared by different instances(but shared among same instance)? You need to make isFirst a (non-static) member of MyClass. And rename it, following your edit: class My...
7,802,195
7,802,259
How do i use templated values as keys in a map?
Im trying to implement a 3 dimensional matrix using stl::map. I have a map whose "keys" are templated and "values" are other maps(for the other dimension). Here is the compiler error I get- graph.h|37| error: ISO C++ forbids declaration of ‘map’ with no type· So is it true that I cannot have a templated value as a ma...
So is it true that I cannot have a templated value as a map's keys? No, There is no such rule. If there was any such rule it would mean power of Generic Programming, the very purpose of existence of Templates would be useless. or is there another way to do it? You are just having an syntax error, because you d...
7,802,218
7,802,397
Namespaces vs. Static Classes
For a project I'm working on, I have a bunch of "library classes". These are essentially collections of related functions of values. Some of these libraries need to be "initialized" at run-time. So far, I've been utilizing the design below as a solution: // Filename: Foo.h namespace my_project { namespace library { cla...
This line is particularly bad: static library::Foo Foo; It emits a static copy of Foo in every translation. Don't use it :) The result of Foo::some_value would be equal to the number of translations the Foo.h was visible to, and it's not thread safe (which will frustrate your users). This line will result in multiple ...
7,802,301
7,880,668
ColladaDOM loader debug assertion errors, on strings?
D3DXMATRIX ColladaFileLoader::processMatrix(daeElement* node) { D3DXMATRIX matWorld; daeTArray<daeElementRef> nodeChildren = node->getChildren(); for (int i = 0; i < nodeChildren.getCount(); i++) { string type = nodeChildren[i]->getAttribute("sid"); if (type == "rotationX") { string data = node...
Ok found the problem after nearly a week of beating my head against the wall, for others who may have run into this issue in the future I'll post the solution. The version of colladaDOM I used was compiled with /mDd library (multi-threaded debug dll) while my project was using /mtd (multi threaded debug static) setting...
7,802,420
7,802,447
Possible reason for error C2146: syntax error : missing ';' before identifier
I am doing a sample application where I have declared a struct: // common.h typedef struct MyStruct { int a; } //sample.h #include "common.h" int main() { MyStruct st;// getting error here } C2146: syntax error : missing ';' before identifier What are the possible reasons for this?
Two things: First, you're missing a semi-colon after the struct definition: // common.h typedef struct MyStruct { int a; }; ^ Not that this is still wrong. You will need to fix the other error. Second, you should define the struct like this: // common.h typedef struct { int a; } MyStruct; Alternat...
7,802,540
7,802,583
While/Switch Statement weird output
#include <stdio.h> #include <iostream> using namespace std; float cost, total; bool loop(char item){ switch (toupper(item)) { case 'A': cost = 4.25; return true; case 'B': cost = 5.57; return true; case ...
As others have mentioned, When you press Enter, two characters get inputted, the character you enter + the newline, You need to account for both of these. Possible solutions are: Approach 1: The C way scanf(" %c", &item); ^^^ Add a space here, or the better approach, Approach 2: The C++ way simply use the...
7,802,549
7,802,578
Write to file with C++ dup2
Alright I am trying to read from one file and write to another. I have other things to add such as grabbing info from the first file but for testing I am trying to get it to write to the second file. My understanding was that everything after the dp2() call would output to the second param. Right? using namespace ...
First, I'm not sure what led you to believe that you need to use dup2(). Don't use it here, it's not needed and will do the wrong thing. Second, to write output to a low-level file descriptor, use write(): write(file2, "yeah\n", 5); Don't forget to close(file2) when you're done with it.
7,802,683
7,802,709
An elegant way to get string from enum value?
Possible Duplicate: Is there a simple script to convert C++ enum to string? In the C# program below, while using enumeration Priority, i need the string "None" and not the id 0. The C# code for doing this is given below. Is there an elegant way of doing this in C++. Can a map be avoided in the C++ implementation. en...
In C++, an enum is nothing more than a bit of syntactic sugar around an integral literal. The compiler quickly strips the enumerator name away, so the runtime never has access to it. If you want to have a string name for an enum, you have to do it the hard way.
7,802,695
7,803,023
dependencies between source and error runtime component
I have an annoying dependency problem between components, and i would like to hear several ways to resolve it. Basically i have 3 components that depend almost acyclically from each other, except for a small dependency between the first and the last component. Concretely, this is a JIT compiler but hopefully it is a wi...
The simplest solution is to define all the types and common behavior that is used by your modules in an independent unit (possibly a single header), that all the real processing units use. For minimum overhead/headaches and compatibility issues (these shared types could be useful elsewhere at some point for communicati...
7,802,831
7,803,020
Is it possible to embed a command prompt in a win32 app?
In linux and when installing packages etc. There are some installers that have a progress bar and a dos window which shows the files being extracted etc. How can i add this window to my C++ Win32 programs so that i can have it showing the tasks im doing? I cannot find any documentation on MSDN. Question: How can i add ...
You cannot embed a real console window inside another window (although a windowed process can have a separate console window). While it looks like a console window / command prompt, it is just a matter of appearances. What you want to do is create a sub-window/control with similar characteristics as a console window ...
7,802,967
7,802,988
0 in the while statement
i have one question and please help me.i have read on web page somthing about do while statement,different is that ,in while there is written 0,not boolean condition do{ // do some instruction }while(condition ); is clearly understandable,but this one do { //again some instruction }while(0); i ca...
It does something only once. It is widely used in macros to group statements and make the usage more natural (i.e. require ending semicolon). Any compiler worth its salt should ignore the do .. while altogether and just run the enclosed statements.
7,803,013
7,803,063
Invalid conversion from ‘const int*’ to ‘int*’ while taking std::set element address
I am getting following error error: invalid conversion from ‘const int*’ to ‘int*’ Following is my program #include <set> int main ( int argc, char **argv) { std::set<int> intSet; intSet.insert(1); intSet.insert(2); intSet.insert(3); intSet.insert(4); intSet.insert(5); int *pAddress = &(*(...
It is because each element of std::set is stored as T const, and the implementation has a reason to do so. Since std::set contains exactly a single copy of a value. It has to make it immutable, otherwise, one can change it's value to something which already exists in the set. Even if the elements were mutable, you wou...
7,803,280
7,803,388
Can I use a crypted hash as a filename or do I have to convert it first?
I am trying to hash a string then use that hash as the name of a file. My problem: is that all the C++ hashers/crypters I have come across hash a std::string or char* & return the hashed string as an unsigned char*? How do I convert that unsigned char* to a char* or std::string so I can then write it to a file or file...
The result of the hash likely contain bytes that map to chars that are not allowed in a filename (e.g. null-char, '+', '?', etc....). So "hashStr" in your code isn't likely to be a string, but just an array of bytes that aren't null terminated. Try this little function to convert from "binary hash to string suitable f...
7,803,345
7,803,478
How to randomly select a class to instantiate without using switch?
I'm refactoring a single 3000+-line class with a tangled web of conditionals and switches into a set of worker classes. Previously part of the constructor would select which "type" of thing to use via code like the following: enum Type { FOO, BAR, BAZ }; Type choices[] = { FOO, FOO, BAR, BAZ }; // weighted towards FOO...
The answer is : a base class and an array of function pointers can help you do that. struct Base { virtual ~Base() {} }; //make ~Base() virtual struct Foo : Base {}; struct Bar : Base {}; struct Baz : Base {}; template<typename T> Base *Create() { return new T(); } typedef Base* (*CreateFn)(); CreateFn create[] = ...
7,803,572
7,803,593
Problems with pointers in a list
For some reason when I try and read a property of a pointer to an object(GamePlayer) within an std::list (playerlist) it works at first, but when I try to access it later in another function I get a bunch of random numbers instead of the numbers for my client's socket. That was a mouthful, sorry. I hope someone could...
The most likely explanation is that you're calling addPlayer with a pointer than becomes invalid by the time you call logicPort. One possibility is that you call addPlayer with the address of an object on the stack, and the object disappears when the stack is unwound. edit The problem is right here: bool PlayerDB::addP...
7,803,625
7,803,673
Write BSTR to file with encoding how to?
I have a function to write file a BSTR, but I can not write it to a file with encoding include? Here is my function, please correct for me! unsigned long Vnpt_WriteFile(const LPCTSTR pFilePath, const BYTE* pbData, const DWORD cbData) { DWORD numbytes = 0; unsigned long rv = 0; FILE* fileHandle; HANDL...
BSTR are wide char (wchar_t) strings. You should have no problem writing them into a file using general purpose functions as WriteFile. Only problem you'll have is with viewing the file with some text editor. To solve that, you have to place a Byte Order Mark (BOM) at the beginning of the file, before you write the act...
7,803,634
7,803,650
Sorting a vector<Struct> alphabetically
I have a std::vector<Word> data that is off of the struct below: struct Word { std::string word; int line_number; }; I have read in words from a file and pushed it in to my vector storing the words in the string above along with the line number that the word appears on. Now I need to sort the words alphabetica...
In this scenario you should write a function that compares two Word structs and pass that function to std::sort. bool compare_by_word(const Word& lhs, const Word& rhs) { return lhs.word < rhs.word; } std::sort(data.begin(), data.end(), compare_by_word); In this question you can find solution if you want to write ...
7,803,789
7,804,175
safe enable_shared_from_this usage
Please consider the following simplified example: #include "boost/shared_ptr.hpp" #include "boost/smart_ptr/enable_shared_from_this.hpp" using namespace boost; class State : public boost::enable_shared_from_this<State> { public: shared_ptr<State> GetSelf() { return shared_from_this(); }; // re...
The simplest way to prevent unmanaged instances is to make the constructor of each derived class private. Your factory function will need to be either a friend or a member of the class it's creating; if you want to keep your factory template, then it will need to be declared before the derived classes in order to make ...
7,804,016
7,804,042
C++ Class isn't returning the correct value of my private variable
Im trying to get this program to take the users input and put that into a public function and assign it to the privateVariable, then I want it to return the value of privateVariable to main() and output it to the screen, but all it displays is the value of an undefined int ( -858993460 ). What logical problem am I havi...
You are setting in object1 and getting from object2. object1 and object2 are different objects. As variable in object2 is not set, you get a garbage value. And I see no use of public userVariable in MyClass.
7,804,281
7,804,325
how to create print preview of the document printed
I am developing a custom pane which will show up when the user presses 'Print'. This custom pane need to have a print preview. Please tell me how to create dynamic print preview of a document/images,etc. Thanks in advance
From the c# tag i guess that it's not a problem if you use .Net framework. In this case this is what you want.
7,804,361
7,804,442
Win32 API GetMessage()
I want to change the default behaviour of a combobox (c++, win32 api). I make the combobox drop down when something is entered in its edit control I want to avoid the default behaviour that the combobox searches for the first match in the list, selects it, and enters the selected string into the edit control. Can I sup...
You likely want to implement Window subclassing. This allows you to insert your own WndProc function into the combobox control that gets called before the control's own WndProc is called. You can filter out (and drop) window messages you don't want the control to get. I'm not booted into my windows partition right no...
7,804,482
7,804,654
Implement Vector of Map in c++
I want to use vector of Map in c++. I have list of mapped values, which I want to store as map in vector. My requirement goes something like this: 1. For N columns, I have a map of values . 2. I want to maintain map of for each i in N. I am trying to maintain this in Vector >. Please let me know how to make it work....
In your example, you are pushing back using a pointer (via new), and not by const reference or value. Your 'vector of maps' declaration is fine, but the insertion is causing a compiler error. To push a map into the vector, use the form: std::map<std::string,int> m; // populate m if needed x.push_back(m); or simply x.p...
7,804,692
7,805,609
LevelDB vs. std::map
In our application we use std::map to store (key, value) data and use serialization to store that data on disk. With this approach we are finding that the disk I/O is performance bottleneck and finding values using key is not very fast. I have come across LevelDB and thinking of using it. But I have some questions. ...
LevelDB just does something else than std::map. Are you really saying you want (high performance) persistence for std::map? look at std::map with a custom allocator. Allocate the entries from a memory mapped region and use fsync to to ensure the information hits the disk at strategic moments in time. mmap boost iostr...
7,804,955
7,805,049
Heterogeneous containers in C++
I saw this nice graphic which classifies which STL container would suit based on different requirements of data such as: -- Fixed Size Vs Variable size -- Data of same tyme Vs different type -- Sorted Vs unsorted data -- Sequential Vs random access http://plasmahh.projectiwear.org/cce_clean.svg I notice in that image, ...
Well generally C++ Containers are designed to hold objects of a single type using templates. If you want different types that are all derived from one type you can store a container of pointers (I guess you could also have a container of void* to anything...) e.g. std::vector<MyBaseType*>. If you want completely unrela...
7,805,193
7,805,371
What is making my constructor protected?
#ifndef SLIST_H #define SLIST_H #include "llist.h" using namespace std; class slist:public llist{ public: slist(); int search(el_t Key); void replace(el_t Elem, int I); }; #endif That is my new class I just made that gives me the search and replace function, on top of all the inherited functions contained in...
I honestly can't see the problem but not every compiler is standard-compliant, so I would try the following: 1) Rename your class - if it works, that means it's a because of a naming conflict. 2) Remove the using directives. 3) Remove the inheritance. If it works after this... you really need to change compilers. 4) Tr...
7,805,318
7,805,500
why upcast when using arithmetic and access operators
what would be a reason for upcasting in C++ in the code which will be used for numerical computations over huge amounts of data (a library that I'm using)? Consider the following hierarchy: template<class T> class unallocatedArray { public: unallocatedArray(int size, T t) : size_(size), t_(0) ...
I can only guess, but some of the arithmetical operations might have been overwritten in geomField in order to implement the geometric mapping. If you have data in an geomField but want to perform unmapped operations, that might be a reason for upcasting. If, on the other hand, none of the operations that are executed ...
7,805,748
7,805,807
When should I not split my code into header and source files?
I know this maybe quite subjective, but are there any general rules for situations when it is not necessary for code to be split into two files? For example is the class is extremely small, or if the file simply holds some global definitions or static functions? Also, in these cases, should the single file be a .cpp fi...
On the technical side, whenever you need to obey the one definition rule you have to separate declarations from definitions, since you will need to include the declarations many times in multiple translation units, but you must only provide one single definition. In aesthetic terms, the answer could be something like "...
7,805,834
7,806,083
Generic wrapper to return last parameter of function in C++
We have written a large library functions whose prototypes mostly look like: void my_fun( const in_class & in_param_1, const in_class & in_param_2, const in_class & in_param_3, out_class & out_param); Is there a generic way to wrap these functions so that the following is equivalent (assuming out_param is onl...
Consider all cases: template<class T1, class Out> Out generic_wrapper(void (*f)(const T1 &, Out &), const T1 & t1) { Out out; f(t1,out); return out; } template<class T1, class T2, class Out> Out generic_wrapper(void (*f)(const T1 &, const T2 &, Out &), const T1 & t1, const T1 & t2) { Out out; ...
7,805,867
7,806,157
Can I use using inside a fnc def?
I've a construct of this form: template<class X> struct Base { X get_data() { return X(); } }; template<class X> struct Derived : Base<X> { X do() { auto v = get_data();//this get is from Base } }; I tried to use this get as it is shown but I was getting error : there are no arguments to 'get_d...
using directives for base class member names only make sense on the class level, where they serve to make names of base class members visible that might otherwise be hidden. They do not make sense at function scope, and thus aren't allowed there. What you can do is this: struct Derived : public Base<X> { using Base<X...
7,806,097
7,806,188
Changing between iterating forward and reverse
I have a animation class which stores the frames in a std::list, the header file declares a iterator, I increment the iterator using time. My animations are working fine until I try to reverse the animation (from the current position), I can't decrement the iterator (bidirectional huh?). I've thought about storing a re...
What do you mean "I can't decrement the iterator"? On my Visual C++ 2010, this works: std::list<int> l; l.push_back(1); l.push_back(2); l.push_back(3); auto i = l.end(); while (i != l.begin()) { --i; std::cout << *i << std::endl; }
7,806,147
7,806,436
QString and german umlauts
I am working with C++ and QT and have a problem with german umlauts. I have a QString like "wir sind müde" and want to change it to "wir sind m&uuml;de" in order to show it correctly in a QTextBrowser. I tried to do it like this: s = s.replace( QChar('ü'), QString("&uuml;")); But it does not work. Also s = s.replac...
QStrings are UTF-16. QString stores a string of 16-bit QChars, where each QChar corresponds one Unicode 4.0 character. (Unicode characters with code values above 65535 are stored using surrogate pairs, i.e., two consecutive QChars.) So try //if ü is utf-16, see your fileencoding to know this s.replace("ü", "&uuml;") ...
7,806,166
7,806,209
Extern inline functions must have the same address in all translation units. How the heck is that achieved?
According to the standard, extern inline functions must the same address in all translation units. How is this achieved in the compiler? I mean when I'm compiling some translation unit, I have no idea what the other TU will be like. So how can I have the same address everywhere?
That's up to the implementation, but usually it's resolved by the linker. Each compiled translation unit will produce an object file containing a copy of the function, flagged in some way so that the linker knows that it should expect (and accept) duplicates. The linker will include one of them, discard the others, and...
7,806,236
7,806,482
ambiguous template overload for template parameter is a container
Please consider the following example: #include <string> #include <vector> using std::string; using std::vector; template <typename T> const T GetValue() { return T(); // some value } template <typename T> const vector<T> GetValue() { return vector<T>(); // some vector of values } int main(int argc, char* a...
One simple way is to use an out-param, so that the template parameter can be deduced from the argument: #include <vector> using std::vector; template <typename T> void GetValue(T &t) { t = T(); // some value } template <typename T> void GetValue(vector<T> &v) { v = vector<T>(); // some vector of values } int...
7,806,589
7,806,686
C++ is it possible to delay initialization of constant static member?
I am using Qt but this is a generic C++ question. My case is simple, I have a class Constants which has a constant static member which I want it to be initialized after certain function calls are made. Constants.h #ifndef CONSTANTS_H #define CONSTANTS_H class Constants { public: static const char* const FILE_NAME...
One option is to return it from a function, keeping it in a static variable. This will be initialised when the function is first called. char const * const file_name() { // Store the string, NOT the pointer to a temporary string's contents static std::string const file_name = QApplication::applicationFi...
7,806,597
7,806,989
Is mark and space parity possible using boost.asio?
I cannot seen to get the serial port set up correctly using the termios structure so i am looking at third party libraries. I have been advised to try boost.asio but when looking through the examples it appears that it does not support mark and space parity, is this true? If it is possible could someone show example co...
There is a very good article on this problem here. In particular MARK and SPACE parity, although implemented in most hardware, are not defined in the POSIX standard. The manpage of of the Unix/Linux termios library, for instance, doesn't loose a single word about these two parity modes. (Note that PARMRK has no...
7,806,689
8,571,428
Instrumenting C/C++ code using LLVM
I want to write a LLVM pass to instrument every memory access. Here is what I am trying to do. Given any C/C++ program (like the one given below), I am trying to insert calls to some function, before and after every instruction that reads/writes to/from memory. For example consider the below C++ program (Account.cpp) ...
Try something like this: ( you need to fill in the blanks and make the iterator loop work despite the fact that items are being inserted ) class ThePass : public llvm::BasicBlockPass { public: ThePass() : BasicBlockPass() {} virtual bool runOnBasicBlock(llvm::BasicBlock &bb); }; bool ThePass::runOnBasicBlock(Basi...
7,806,771
7,806,805
How to joining 2 variables in other variable
See the example to understand int rnd = rand() %10; string Folder = "c://foldername"; string final_name = Folder + rnd; // here the target /* I want the result like that (random folder name) foldername5 foldername10 foldername3 foldername20 foldername17 */
In c++ you use stringstream to convert integers to strings. int rnd = rand() %10; string Folder = "c://foldername"; stringstream ss; ss << Folder << rnd; string final_name = ss.str(); // here the target
7,807,003
7,807,141
binary_search with Pointers
i want to implement binary_search with pointers #include <cstdlib> #include <iostream> using namespace std; int binary_p(int x[],int size,int target){ int *p=&x[0]; int *q=&x[size]; while(p<q){ int mid=(p+q)>>2; if (target==x[*mid]) return 1; else if(target<x...
Here is the working code. #include <cstdlib> #include <iostream> using namespace std; int binary_p(int x[],int size,int target){ int *p = &x[0]; int *q = &x[size - 1 ]; while( *p < *q ){ int mid = (*p + *q) >> 2; if (target == x[mid]) return 1; else if (target < x[mid...
7,807,052
8,141,567
Using Boost libraries with mingw
I'm tryin to use boost threads on mingw (TDM-mingw, 32bit based on gcc4.6) from qtcreator using qmake. I managed to compile boost 1.4.7 using bjam --toolset=gcc --layout=tagged --without-mpi --without-python -j 4 stage --build-type=complete However I simply can not get it to link. I tried to link against several of t...
Just now I recompiled boost once again and now it works, so I assume it was just a case of bjam using the wrong mingw version for some reason
7,807,382
7,808,832
How to get exact type of object in Ruby extended C++?
Hi. I'm working on a Ruby C++ extension, I have the following function, in which "self" object is either of structure type or of Exception type. VALUE myFunction(VALUE self, VALUE args) { // Some functon call and process on args argument } Now in the above function I need to know the exact type of object "self" (i.e...
You can get the class with rb_obj_class which would be the appropriate VALUE.
7,807,437
7,807,490
Postfix increment operator
I have a custom class MyInt, encapsulating a int m_nValue data. The postfix operator MyInt operator++(int) { MyInt temp(*this); ++(*this); return temp; } if the operator returns an object, then why i am not able to call postfix++ operator more than once like: MyInt value(10); value++; // valid value+...
Wrong answer: Because value++ is a temporary variable that holds the old value of value. You can't ++ it. You also can't write 15++! It's similar. The former is a temporary variable, the later is a constant, none of which you can increment. Correction: Since this answer got accepted, I am not going to change the origin...
7,807,635
7,807,751
How do I convert an Erlang data structure into a C++ adjacency list (graph)?
Disclaimer: The author of this post is a C++ beginner. In my Erlang code, I have a data structure which represents a directed graph: -record(vertex_entry, {vertex_name, outgoing_edges}). -record(outgoing_edge, {edge_weight, neighbour_name}). Edge1 = #outgoing_edge{edge_weight = 12.5, neighbour_name = 2}, Edge2 = #outg...
Unless performance is critical here, consider serialising to text instead, in a format which is easy to parse. It'll save you lots of debugging effort if you can read the output, save it to file when testing the read side, etc. Even if you do decide to switch to a binary encoding, writing out the text encoding first m...
7,807,656
7,807,706
Porting C++ OpenGL Game to iPad
We have a game, developed in C++ and OpenGL for Windows and Mac. Now we want to port the game to iPad. Is there a better way than writing the entire program in Objective-C to make our game work on iPad? Now I am an iPhone/iPad noob, so pardon if the question is dumb.
You probably need to write only a small part in Obj-C that deals directly with iOS(creating a gl surface, input etc). Rest should work fine. You just need to make sure you will be using only the subset of OpenGL that is in OpenGL ES.
7,807,755
7,807,918
Reading popen results in C++
I am writing a C++ application and I need to read the result of a system command. I am using popen() more or less as shown here: const int MAX_BUFFER = 2048; string cmd="ls -l"; char buffer[MAX_BUFFER]; FILE *stream = popen(cmd.c_str(), "r"); if (stream){ while (!feof(stream)) { ...
Your example: FILE *myfile; std::fstream fileStream(myfile); std::string mystring; while(std::getline(myfile,mystring)) Does't work because although you're very close the standard library doesn't provide an fstream that can be constructed from a FILE*. Boost iostreams does however provide an iostream that can be const...
7,807,933
7,808,401
Template classes vs Private inheritance
Why would some compilers insist on qualifying members public members of template base class while the not requiring the same for non-template class? Please look at the following code listings: Template class: #include <iostream> using namespace std; template <class T> class TestImpl { public: // It wont make a differ...
The problem you are facing is that for the compiler vval_ is not a dependent name, so it will try to look it up before the actual instantiation of the template with the type. At that point, the base type is not yet known to the compiler [*], and thus it does not consider the templated bases. Visual Studio does not perf...
7,808,085
7,808,911
How to get the status of a service programmatically (Running/Stopped)
I need to get the status of Windows "print spooler" service in my C++ application.
Use QueryServiceStatus or QueryServiceStatusEx. There are plenty of examples on the web on how these are used.
7,808,237
7,830,136
UAC prompt elevation - how does it work?
Windows displays UAC prompts on the "secure desktop" when certain security-related operations need to be performed. There's obviously some API somewhere that creates the secure desktop and creates a window on it, but I have no idea where I would find out about the mechanisms involved. I guess I could reverse engineer t...
It seems likely that, from the point of view of the system, the secure desktop is just a perfectly normal desktop with a suitable ACL. Note that CreateDesktop allows you to specify a security descriptor for the new desktop. So far as I know, the secure desktop has no special behaviour, so I see no reason to suppose th...
7,808,290
7,808,329
Casting pointer-to-function with ellipsis
Consider the following program: #include <iostream> typedef void (*fptr)(...); void foo(fptr func) { (*func)(12); } void bar(int x) { std::cout << "bar : " << x << std::endl; } int main() { foo(fptr(bar)); } This compiles, runs and prints bar : 12 on at least one compiler :) I found this in some legacy...
What the code is doing is undefined behavior. If its working is just by chance, there are no guarantees that it should work. The only thing that can be safely done with a casted function pointer is cast it back to its original type.
7,808,394
7,808,660
Using an Objective-C++ class with C++ instance variables in Objective-C code
I'm writing an Objective-C++ class interface that has to be usable from both Objective-C and Objective-C++. The problem is that, because it must be usable from Objective-C, I cannot simply use a C++ type. I want to do it using pointers and I came up with this: @interface SXDiff : NSObject { @private #ifdef __cplusplus ...
With Apple LLVM version 2.0+ try moving all of your C++ code from the header into a class extension. //SXDiff.h @interface SXDiff : NSObject { } ... @end //SXDiff.mm #include "dtl/dtl.hpp" @interface SXDiff() { dtl::Diff<std::string, std::vector<std::string> > *_diff; } @end @implementation SXDiff ... @end ...
7,808,405
7,808,449
comparing a char to a const char *
string line = "blerdy blah"; for (int i = 0; i < string.size(); i++) { line[i] != "n"; } With this I get the error "cannot convert from char to const char *" If I replace the last line with line[i] != *"n"; It works. I get why in one sense, I'm dereferencing a pointer. What I don't get is why it's a pointer in t...
You have to compare char with char in this case: line[i] != 'n'; When you say *"n" you actually dereference the first element of the char array with n and \0 elements inside it, which gives you n, that's why it works, but you don't want to write it like that.
7,808,504
7,808,614
Using the IBM 3514 Borland Graphics Interface driver in High resolution mode in Turbo C++ on Windows 7 64 bit OS using DosBox
I'm running a graphical program in Turbo C++ using DosBox on Windows 7 64 bit. Now, I want to use the IBM3514 graphics driver in the High resolution mode (IBM3514HI). So, I wrote the following bare bones program to test it: #include <graphics.h> #include <iostream.h> void main() { int gd = IBM3514, gm = IBM3514HI,...
Under Windows your graphical adaptor is virtualized. You can't access it directly and use its specific features (unless you use DirectX/OpenGL/other strange methods). DOSBox emulates some "historical" graphical adaptors for the programs it runs (to be precise: Tandy/Hercules/CGA/EGA/VGA/VESA). You must use the VESA 2.0...
7,808,657
7,812,402
Compilation error with boost serialization
I created a small sample for testing the boost serialization library, but I have a compilation problem. First of all, here's the code: #include <iostream> #include <fstream> #include <iomanip> #include <boost/filesystem/operations.hpp> #include <boost/serialization/nvp.hpp> #include <boost/filesystem/fstream.hpp> #incl...
It looks like dbPath is not defined. Additionally, the declaration of ooxml/iixml appears incorrect. Try modifying your code to do the following: ... const char * dbPath = "file.xml" std::ofstream ofs(dbPath); boost::archive::xml_oarchive ooxml(ofs); ooxml << BOOST_SERIALIZATION_NVP(a); std::ifstream ifs(dbPath...
7,808,883
7,808,942
extending an object of a basic class to an object of a complex class
how can I do that? I thought of an method in the complex class which copies every variable of the basic object to the complex object, but that seems a little bit to inconvenient. class Basic { //basic stuff } class Complex : public Basic { //more stuff } Basic * basicObject = new Basic(); //now "extending" basicO...
Define the values you want to share between the classes in protected section like so: class Base { public: int myPublicShared1; int myPublicShared2; Base& operator = (Base& other) { // Copy contents in base across return *this; } protected: int myShared1; int myShared2; private: int notShared1; int notShared2...
7,808,916
7,809,004
std::queue<T, list<T> >::size() is slow in O(n)?
I experienced unexpected performance behavior of my code which uses a queue. I realized that performance degraded when more elements were in the queue. It turned out that usage of the size() method was the reason. Here is some code that shows the problem: #include <queue> #include <list> #include <iostream> #include "...
queue is a container adaptor, so you have to understand that the complexity descriptions may refer only to the work the adaptor does itself (which is indeed constant, namely just passing the call through to the underlying container). For example, see this reference: size() calls the underlying container's size() functi...
7,808,939
7,809,038
How do I achieve this with vim cindent?
If I write the following code in vim at the moment const SomeType & some_function (<ENTER> then vim will continue the next line at an indent of two tabs. I want it to indent the next line with only one tab. I know cindent exists, but I can't work out what syntax will make this happen.
:help cinoptions-values (N When in unclosed parentheses, indent N characters from the line with the unclosed parentheses. Add a 'shiftwidth' for every unclosed parentheses. When N is 0 or the unclosed parentheses is the first non-white character in its line, line up with the next non-white ...
7,808,988
7,809,256
Invalid conversion from (some-class)** to void**
I am new to this community and new to C++, which is where i am trying to get my program to run. I am trying out an exercise in Thinking in C++ by Bruce Eckel, and there, I am to use his implementation of a Stack and change its constructor so that it takes as its arguments an array of pointers to objects and the size of...
You can use a void* to point to anything, but a void** is not a void*; it points to a void*. And a product* is not a void* (it could even have a different size or representation). If you want to pass a pointer to an array of pointers, you need to pass it with the type of the pointers in the array, and if you want to ...
7,809,000
7,809,045
why sorting algorithm takes zero seconds
here is algorithm #include<iostream> #include<Windows.h> #include<time.h> using namespace std; int main(){ int a[10]={12,3,5,2,7,80,10,1,16,30}; long ts,te; srand(::GetTickCount()); ts=clock(); for (int i=0;i<10;i++){ for (int j=9;j>i;j--){ if (a[j]<a[j-1]){ ...
Unless you used punch-cards to write your program, you shouldn't be surprised that sorting 10 numbers takes less than one tick. If you want a more accurate profile of your code, use milliseconds, that should give you a better idea. The inner-most instruction in the loops run 100 times - that's nothing compared to even ...
7,809,047
7,809,130
Workaround for Interface
In C++, how can I declare an interface s.t. I can use it as shown below: /** Enemy "Interface" */ Class Enemy { Enemy(); virtual ~Enemy(); virtual void doStuff() = 0; }; /** Enemy of type 1 */ Class Enemy_type1 : public Enemy { Enemy_type1(); virtual ~Enemy_type1(); virtual void doStuff() { ...
First, you'll have to (or at least want to) make the functions that make up your interface public: class Enemy { public: Enemy(); virtual ~Enemy(); virtual void doStuff() = 0; }; Then you'll inherit from it (C++ doesn't have "interfaces" and "classes" as separate concepts). class Emeny_type1 : public Enemy...
7,809,194
7,809,643
overloading operator .
Ok, I know that operator. is not overloadable but I need something like that. I have a class MyClass that indirectly embeds (has a) a std::string and need to behave exactly like a std::string but unfortunately cannot extend std::string. Any idea how to achieve that ? Edit: I want that the lines below to compile fine M...
As per your later edit, that: MyClass strHello1("Hello word"); std::string strValue = strHello1; const charValue = strHello1.c_str(); should compile fine, the only solution is to write a wrapper over std::string: class MyClass { private: std::string _str; public: MyClass(const char*); //... all other constru...
7,809,200
8,098,696
Implementing Task Farm messaging pattern with zeromq
I am using zeromq to solve a problem which involves several hundred (potentially thousands) clients request tasks to be carried out. Each client would request for a specific task to be carried out, and the result(s), when completed, whould be returned back to the client that issued that request. These are the actors th...
There are a variety of approaches to this, and IPython.parallel includes two such implementations with ZeroMQ - one simple and pure-zmq, and another that is more elaborate, with the Controller implemented in Python. We split the Controller into two actors: Hub - an out-of-the-way process that sees all traffic, and kee...