question_id
int64
25
74.7M
answer_id
int64
332
74.7M
title
stringlengths
20
150
question
stringlengths
23
4.1k
answer
stringlengths
20
4.1k
5,206,448
5,206,522
Counting occurrences of letter in a file
I'm trying to count the number of times each letter appears in a file. When I run the code below it counts "Z" twice. Can anyone explain why? The test data is: abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ #include <iostream> //Required if your program does any I/O #include <iomanip> ...
As others have pointed out, you have two Qs in the input. The reason you have two Zs is that the last inputFile >> character; (probably when there's just a newline character left in the stream, hence not EOF) fails to convert anything, leaving a 'Z' in the global 'character' from the previous iteration. Try inspect...
5,206,687
5,206,950
AVL Tree strange behavior
The following code got me really puzzled. class class AVLTree { private: struct AVLNode { AVLNode *leftchild; AVLNode *rightchild; int data; int height; }; AVLNode *root; public: AVLTree() { root = NULL; } bool isEmpty() const { return root == NULL; } void print(); void inorder(AVLNode *n, i...
If n was null on entry to the function, then that line will attempt to dereference it, giving the error. Your code to allocate a new node should assign it to n itself, rather than a separate variable with the same name that shadows the function argument. Change the first line of the if (n == NULL) block from AVLNode *...
5,206,741
5,206,797
Why does the symbol of the SHA512 function in libeay32 not have a leading underscore?
I am attempting to use OpenSSL's SHA512 function in a C++ project of mine. In order to do this, I include openssl/sha.h in my source files that call SHA512 and link with the libeay32.lib library. SHA512 is declared in openssl/sha.h as: extern "C" { //... unsigned char *SHA512(const unsigned char *d, size_t n,unsigned c...
There is only one calling convention for 64-bit code. None of the nonsense of __cdecl, __stdcall, __fastcall etcetera. Whoever comes up with another x64 calling convention to save a fraction of a nanosecond is going to be summarily executed. Accordingly, DLL exports no longer have to be decorated with leading unders...
5,206,749
5,206,760
is there corresponding class in C++ as TreeMap in Java?
is there corresponding class in C++ as TreeMap in Java? thanks
Yes, std::map, found in the <map> Standard Library header.
5,206,787
5,206,930
C++0x Tuples Store Elements Backwards
After a bit of investigation, I found that C++0x stores the elements in a tuple backwards in memory. For example, take this code: std::tuple<char, char, char> x('\0', 'b', 'a'); char* y = (char*)&x; std::cout << sizeof(x) << std::endl; std::cout << y << std::endl; When compiled with the GCC 4.5.2, I get the following ...
The tuple layout that you are exploring is an unspecified implementation detail of tuple. Other implementations will have other layouts. If you write to this one, depending on gcc's layout, your code may not be portable to other std::libs. The libc++ tuple implementation (for example) has the opposite (in-order) layo...
5,206,855
5,206,873
Equivalent of TinyXML for JSON in C++?
Is there any small C++ JSON decoder? It should work under both GCC and Visual Studio. It doesn't need to support encoding.
We've had success with jsoncpp
5,206,994
5,207,058
Encapsulation in a Composition Class C++
I have a map class, which contains a vector containing MapEntitys. MapEntity is a class of which Factory, Farm and 3 other classes are inherited from. These 5 classes both should be "ticked" every few seconds, at which point they will all do a function individual to each class, but only the map class should be able to ...
Syntactically you could use any of that. However, if MapEntities are to be "ticked" from outside, the tick method should be part of their public methods. Actually, it should be a virtual public method of the MapEntity class. And yes, public methods are proper encapsulation. They tell the user of your class what it can ...
5,207,147
5,292,493
OpenCV crop image with ellipse
I have an image (cv::Mat) with size of 92x112 I want to surround the object in this image with a ellipse then get only this pixels to create another image containing only the object. I mean, cropping the original image with a ellipse. It's possible? I am trying drawing a ellipse, but the ellipse don't draw complete, wi...
I solve using this: imagen = imread(nombre_imagen,0); //read image (grayscale) //Use old C interface IplImage *res,*roi; IplImage src(imagen); res = cvCreateImage(Size(imagen.rows,imagen.cols),8,1); roi = cvCreateImage(Size(imagen.rows,imagen.cols),8,1); cvZero(roi); cvEllipse(roi,cvPoint(src.width/2,src.height/2),cvS...
5,207,181
5,207,209
Why is C++ compatible with C?
After reading an amount of C++ articles and tutorials, I often see the phrase "C++ is not C!" or some variant. If this is true, why is C++ trying to be compatible with C? Surely this just encourages C programmers to write bad C++ code? I'm only a newb in the field, so feel free to bombard me with reasons why I'm wrong ...
The purpose of compatibility with C is so that C++ programs can have convenient access to the billions (trillions?) of lines of existing C code in the world. It was never intended as a suggestion to code C++ as if it was C. Peripheral objectives were: Leverage the C skills that many programmers have (given that it is ...
5,207,200
5,666,132
Port simple C++ to PHP code
I need something similar to this in PHP: struct MSG_HEAD { unsigned char c; unsigned char size; unsigned char headcode; }; struct GET_INFO { struct MSG_HEAD h; unsigned char Type; unsigned short Port; char Name[50]; unsigned short Code; }; void Example(G...
I created a general purpose php Struct class, to emulate c-structs, it might be useful to you. Code and examples here: http://bran.name/dump/php-struct Example usage: // define a 'coordinates' struct with 3 properties $coords = Struct::factory('degree', 'minute', 'pole'); // create 2 latitude/longitude numbers $lat = ...
5,207,284
5,207,344
Isn't inline premature optimization?
Possible Duplicate: Inline functions in C++ Modern compilers are better than programmers at deciding what should be inlined and what should not. Just like, register, shouldn't inlining functions be a job for the compiler only, and be considered premature optimization ?
inline has a double meaning that some are unaware of - it allows a function to be defined in more than one translation unit (i.e. if you define an unbound function in a header and include it from within various translation units, you are forced to declare it inline or the linker would complain about doubly defined symb...
5,207,332
5,207,437
C++ Types Impossible to Name
While reading Wikipedia's page on decltype, I was curious about the statement, Its [decltype's] primary intended use is in generic programming, where it is often difficult, or even impossible, to name types that depend on template parameters. While I can understand the difficulty part of that statement, what ...
The wikipedia page you link has a perfect example: int& foo(int& i); float foo(float& f); template <class T> auto transparent_forwarder(T& t) −> decltype(foo(t)) { return foo(t); } Note that foo(int&) returns int& (a reference type) while foo(float&) returns float (a nonreference type). Without decltype, it's impos...
5,207,467
5,207,528
What is lifetime of lambda-derived implicit functors in C++?
The question is simple: what is lifetime of that functor object that is automatically generated for me by the C++ compiler when I write a lambda-expression? I did a quick search, but couldn't find a satisfactory answer. In particular, if I pass the lambda somewhere, and it gets remembered there, and then I go out of sc...
Depends on how you capture your variables. If you capture them by reference ([&]) and they go out of scope, the references will be invalid, just like normal references. Capture them by value ([=]) if you want to make sure they outlife their scope.
5,207,532
5,207,554
Appending a number to a number?
How cold I do the following: say I have the number 10 and would like to append the number 317 to it. The resulting integer would be 10317. How can this be done. Also, once I have this number, how could I then for example remove the 17 off the end. Without using strings, and without obvious solving and adding. Thanks
This will append both numbers int append_a_and_b_as_int(int a, int b) { for(int tmp = b; tmp > 0; tmp % 10) { a *= 10; } return a + b; } This will get rid of the last n numbers int remove_n_numbers_from_a(int n, int a) { for(int i = 0; i < n; i++) { a /= 10; } return a; ...
5,207,639
5,207,666
How do you pass an enum by reference?
I have an enum with four keys I'm taking as input for an interface program and I'd like to pass the enum by value to the interface function, which has become quite long. The enum is like this: enum MYKEYS { W, S, O, L }; There's also a boolean array that I have to pass by reference, which is also a little tricky. b...
You can't pass the enum itself as a parameter of your function! The enum defines a new type, and you can create a variable of this type, that may take one of the value defined by the enum: MYKEYS k = W; Only then you could pass k by reference to some function: function foo(MYKEYS& k_); Regarding your second question,...
5,207,657
5,207,704
Can I execute a "variable statements" within a function and without defines?
I am facing a problem that I cannot see how it is solvable without #defines or incurring a performance impact although I am sure that someone can point me to a solution. I have an algorithm that sort of produces a (large) series of values. For simplicity's sake, in the following I pretend it's a for loop in a for loop,...
Functors : struct Caller { void operator()(int x, int y) { if ( x+y == 800 && y > 790) std::cout << x << ", " << y << std::endl; } }; template <typename T> void your_algorithm(T foo) { for (int x=0 ; x<1000 ; x++) for (int y=0 ; y<1000 ; y++) foo(x, y); } int...
5,207,688
5,207,738
C++ -- Why should we use operator -> to access member functions of a SmartPtr?
The question is given in the last two lines of code. template<class T> // template class for smart class SmartPtr { // pointers-to-T objects public: SmartPtr(T* realPtr = 0); T* operator->() const; T& operator*() const; T* Detach( void ) { T* pData = pointee; p...
SmartPtr<TestClass> sPtr(new TestClass); TestClass* ptrA = sPtr->Detach(); Is actually invalid, because TestClass has no member function Detach. operator-> of the SmartPtr class is declared as T* operator->() const, as such (should) return the pointee of the smart pointer. TestClass* ptrB = sPtr.Detach(); Is the vali...
5,207,765
5,207,919
C4275 warning in Visual Studio
I get this warning when compiling my code in VS2008 warning C4275: non dll-interface class 'std::runtime_error' used as base for dll-interface class 'MyException' 2> c:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\include\stdexcept(148) : see declaration of 'std::runtime_error' My class is defined as c...
MSDN: http://msdn.microsoft.com/en-us/library/3tdb471s.aspx "An exported class [as in DLL] was derived from a class that was not exported [as in DLL]." Apparently you are declaring MyException to be exportable from a DLL (by using: __declspec(dllexport)), while std::runtime_error is not exportable. Consider if MyExcep...
5,207,779
5,207,794
C++ Problem declaring multiple object instances on the same line
For a homework assignment, I'm having a hard time understanding the behavior when the main class is instantiating two objects of the same class on the same line as follows. Note that the object of the assignment is for the class to behave like an int: main () { MyClass x,y = 5; cout << "x = " << x << endl; // outpu...
The problem is that C++ is parsing MyClass x,y = 5; As if you had written MyClass x; MyClass y = 5; And so x is getting default-initialized rather than initialized with 5. To fix this, change the line to read MyClass x = 5, y = 5;
5,207,784
5,207,858
can anybody explain C C++ Java regarding dynamic or static language
can anybody explain C C++ Java regarding dynamic typed or static typed language. I read somewhere that C C++ and Java are all static language. But I recall there are other opinions about these. Very confused. Thanks!
What other opinions? There is no question that C, C++, and Java are all statically typed languages, with C++ and Java having some dynamically typed features. There's another issue: strongly vs. weakly typed, which pertains primarily to implicit conversions and overloading. There are numerous in-depth discussions of the...
5,207,842
5,207,909
C++ Put wav file into dll
I want to include one wav file into dll and play it later. How to do it? I know how to play file that is in the same direcory. But I want to include around 50 wav files into my dll.
You embed such files as resources. You need a resource file, and e.g. MY_WAV WAVE "file.wav" Then to play it directly, use PlaySound. PlaySound("MY_WAV", hInstance, SND_RESOURCE); hInstance should be the handle passed to your DllMain
5,208,108
5,208,126
How to create and use list, of type "customClass"
I have created a class "Node" to contain a bunch of data. I am trying to make a list of the same type of this class. I am having errors in trying to use push_back() or any of the other functions. error is the following:" /home/.../FIFO.cpp|61|error: no matching function for call to ‘std::list >::push_back(Node*&)’|"...
The compiler error tells you "Couldn't find a push_back function that takes a Node * as parameter". This is because your list contains Node and not Node *, these are not the same types. Use: list<Node *>
5,208,152
5,210,008
c++ cin.getline() fail
my problem is that my program doesnt read the values that I enter by keyboard, only reads the 1st, the 2nd and last. I´ve tried with cin.ignore(); and other solutions but doesn work. This is the input: Insurance 1 Model: mazda serial number: 60 Price: 9999 Contract number: 76Z Contract money: 12 //after all charac...
You can use std::getline() in order to read the data into a string, and then copy the contents into your fields, limiting, if needed, the number of characters to copy. #include <util> #include <cstring> // ... std::string input; std::getline( cin, input ); // +1 char for end of string std::strncpy( a[p].contrato[a[p...
5,208,184
5,208,200
Should member functions be "const" if they affect logical state, but not bitwise state?
I'm writing a class that wraps a legacy C API that controls a hardware device. In a simplified example, I might have something like: class device { public: void set_request(int data) { legacy_set_req(p_device, data); } int get_response() const { return legacy_get_rsp(p_device); } private: device_handle_t...
I believe that const should reflect logical const-ness, regardless of the internal representation. Just because your object contains only a pointer to something that changes, doesn't mean all your member functions should be const. C++ even has the mutable concept for internal representation that needs to change even if...
5,208,185
5,208,229
Polyhedron from the plane equations
I have a few planes (3-10 of them) in 3d defined by their equations (three coefficients and the offset). These planes are the edges of a convex polyhedron. I need to draw that polyhedron. How can I do that? What software/libraries/algorithms can I use? I work in Linux and I'm usually using C or C++.
Every plane pair intersects in a line on both planes. Each plane then contains a set of lines that intersect in points, all of those are the edge points of your polyhedron you'll have to connect in a convex way. With some math/geometry skills, you should be able to solve this, but using a library (f.e. CGAL) of course ...
5,208,356
5,208,409
Memory alignment on iPhone and Android
As I've discovered from my tests iPhone's malloc has 16 byte alignment. But I'm not sure whether it is guaranteed or just coincidence. So the question is: what is the guaranteed memory alignment when using malloc() on iOS and Android(NDK)?
malloc in C returns a pointer to a block of memory "which is suitably aligned for any kind of variable"; whether this alignment is or will remain at 16 bytes is not guaranteed even for different versions of the same OS. Objective-C is effectively based on C, so that should hold true there too. If your Android NDK is wr...
5,208,415
5,208,433
LoadLibrary taking a LPCTSTR
I want to develop a plugin system using LoadLibrary. My problem is: I want my function to take a const char* and LoadLibrary takes a LPCTSTR. I had the bright idea to do (LPCSTR)path which kept giving me a module not found error. Current code is below. If I uncomment the widepath = L.. line it works fine. I've rea...
Use LoadLibraryA(), it takes a const char*. Winapi functions that take strings exist in two versions, an A version that takes an Ansi string and a W version that takes a wide string. There's a macro for the function name, like LoadLibrary, that expands to either the A or the W flavor, depending if UNICODE is #defined....
5,208,556
5,208,580
How to make closed source for the library written with template in C++
After reading this article Storing C++ template function definitions in a .CPP file, I know that the definition of a class that uses template has to be written in the header file in some way. So a client user can use it by importing the header files. Doesn't this mean the complete implementation details are revealed to...
The details of the template implementation will be visible. You can provide explicit template instantiations if you know which parameters will be necessary, however. But to be a generic solution, you have to provide the implementation so it can be used with other parameters. No, you don't have to release it as open ...
5,208,811
5,208,931
How to get port identifiers for an edge using Boost Graph Library?
Using the Boost Graph Library, is it possible to get the port identifiers for an edge? Example: After calling read_graphviz, I can iterate through the edges of this graph and print their node_ids -- I get "A -> B, A -> B". How can I print something like "A:p0 -> B:p1, A:p0 -> B:p2"? digraph G { A [label="A|<p0>p0...
From the read_graphviz_new.hpp source: struct edge_info { node_and_port source; node_and_port target; properties props; }; Where node_and_port looks like this: struct node_and_port { node_name name; std::string angle; // Or empty if no angle std::vector<std::string> location; // Up to two identifiers // ...
5,208,813
5,208,819
Why is cin.getline() skipping the first word in each line?
I am trying to display the text of a command line inputted text file line by line. But for some reason, it skips the first word in each line after the first line. code: using std::cout; using std::cin; using std::endl; int main (int args, char* argv[]) { char x[100]; char y[100]; char z[100]; cin...
cin.getline(x,100) >> argv[2]; You read a line (or the first 99 characters of the line) into x. Then you skip any whitespace and read the next word into argv[2]. The first words are ending up there. Why are you using >> argv[2]? What are you possibly trying to do with this? argv[2] may not exist and even if it doe...
5,208,833
5,208,840
Can two classes friend each other?
I haven't yet worked out a specific case. But I am about to embark on writing some code that I feel will end up needing this; and so I wanted to know if: Two classes can friend each other; so that they can freely access the private and protected members of the other (I believe the answer is yes, and ofcourse I can s...
You can have mutual friendship: class A { friend class B; }; class B { friend class A; }; Whether or not this makes sense depends entirely on the problem you are trying to solve. It definitely could make sense in certain circumstances. The only example from my current project that utilizes mutual friendshi...
5,208,896
5,208,922
using reference and pointer for operator overloading on large objects
In the book of “The C++ Programming Language”, the author gives the following example and several claims. class Matrix { double m[4][4]; public: Matrix( ); friend Matrix operator+(const Matrix&, const Matrix&) }; Matrix operator+(const Matrix& arg1, const Matrix& arg2) { Matrix sum; for ...
If operator+ was instead declared as taking its operands by value, e.g., Matrix operator+(Matrix arg1, Matrix arg2) then copies of arg1 and arg2 would have to be made to be passed into the function. A simple matrix addition, e.g., Matrix x, y; x + y; would require copies of both x and y to be made; effectively, you ...
5,208,945
5,208,971
linkedlist with class in the struct can't get bool operation working
I can't seem to get Boolean operation working like I thought it works. /////.h file class linkD { private: struct ListNode{ driver driver; ////class ListNode *next; }; ListNode *head; ///.cpp file void linkD::deleteNode(driver d){ ListNode *nodePtr; ListNode *previousNode; ListNode *newNode; newNode...
That's because driver is a class object. You have to define the equality operator for a class. Are you expecting class object to be pointer like (as in Java i.e. They can be NULL) If you want to test driver objects for equality define it like this: class driver { public: bool operator==(driver const& rhs) c...
5,209,019
5,209,144
What is it the estimate of Moore's law, a program to do this
In 1988, the number of transistors in the Intel 386 SX microprocessor was 275,000. What were the transistor counts of the Pentium II Intel microprocessor in 1997? If Intel doubles the number of transistors every two years, the new processor would have Pn = 275,000 * 2^n (where n = 9/2 = 4.5) = 275,000 * 22.63 ...
In C: #include <stdio.h> #include <math.h> #define BASELINE_CPU_YEAR 1988 #define BASELINE_CPU_TRANSISTORS 275000 /* Estimate transistor count for Intel CPUs for a given year * based on Moore's law */ double moores_law(int year) { float year_offset = (year - BASELINE_CPU_YEAR) / 2.0; return BASELINE_...
5,209,031
5,209,844
How can SIP handle a C++ method that returns int*
I'm trying to make a C++ library available as a Python module. It seems SIP is the best tool for the job. (If wrong, please correct me.) One class looks like the programmer was trying to get around c's lack of dynamic typing: class Item{ private: enum ITEMTYPE{TYPE_INT,TYPE_FLOAT,TYPE_INT_ARRAY,TYPE_FLOAT_ARRAY}...
I don't know sip, but I've used swig to wrap C++ into a python module and it was pretty straightforward. swig can handle most standard C++ data types (including standard library containers) automatically.
5,209,481
5,209,502
C++ code to automatically close console
I am currently learning C++ for a programming course. I noticed that my professor's program automatically closes at the end of their program. It usually prompts the user for an input, and then upon entering an input, the program closes. How would I code that? I only know using return 0 gets me "Press Any Key to Continu...
If your program doesn't wait for any input, it runs and finally exits from the program. On exiting, the console automatically closes. I assume, to run the program you're clicking on the .exe, as opposed to runnng the program from cmd.exe, or you run the program from visual studio itself without debugging.
5,209,495
5,209,512
How can I determine if a dialog is null in Qt?
I'm trying to show a simple dialog like this: if (!aboutDialog) aboutDialog = new AboutDialog(this); aboutDialog->exec(); For some reason it doesn't work (aboutDialog has some pointer although is not initialized), the checking if (aboutDialog == 0) doesn't work either. I don't want to create the instance e...
You need to initialize aboutDialog to 0 explicitly somewhere. Probably in the constructor of the class this member belongs to. (!aboutDialog) is a correct test. Consider the following: #include <iostream> class Thing { void *data; public: Thing(){} void print() { std::cout << data << std::endl; } }...
5,209,625
5,235,383
Boost.Test error messages are no more shown in error list of VS2010
I am using Boost.Test Unit Test Framework for native C++ projects. All is working fine, but I've got one issue after upgrading to Visual Studio 2010: The messages about failed tests are no more shown in the error list after the tests ran as a post build step. This is a pity since the combination of Boost.Test with nati...
Visual Studio 2005 Build output for compiler errors looks like this: |.\ut_TEMPLATE.cpp(8) : error C2065: 'x' : undeclared identifier Whereas Visual Studio 2010 compiler errors look like this in the output window: |1>ut_TEMPLATE.cpp(8): error C2065: 'x' : undeclared identifier (Edit: See the comment by gbjbaanb about...
5,209,823
5,210,007
How to call qDebug without the appended spaces and newline?
I'm using the the C++/Qt print function qDebug, but sometimes I would like to control how ", space and newline is appended and not use the default qDebug. Let's take a simple example: QString var1("some string"); int var2 = 1; qDebug() << var1 << "=" << var2; This will print "some string" = 1 But Let's say that I...
Try this format: qDebug("%s=%d", "string", 1); In this case qDebug uses printf formatting P.S. Adapted for your example: qDebug("%s=%d", var1.toStdString().c_str(), var2);
5,210,183
5,210,189
C++ nested class error "cannot convert ... in assignment"
I'm new to C++ and I keep getting this error message in the following class: class LinkedList { class Node *head; class Node { Student *student; Node *next; Node *prev; public: Node(Student *n_student, Node *n_next, Node *n_prev); ~Node(); Student *getStude...
Change this: class Node *head; Into this: Node *head; When you declare a field of a certain class inside a class, you don't need the class keyword. Just the type name and its corresponding identifier. Like this: Node *n; LinkedList *l; No class keyword. class keyword is only used when you actually declare/define a c...
5,210,191
5,210,304
Identifying address calculation insns in asm
I am looking at x86 asm and I wanna try to read it and identify a bug in my cpp code and OPTIMIZE. But the asm has a lot of overhead from address calculating instructions. And I can't seem to find a way to identify the ones that are calculating an address from the ones that are doing other tasks. for example an add cou...
No, not really. Most registers are general purpose, and used for all kinds of calculations. Some compilers are even smart enough to use address calculating instructions like LEA to compute other things. You will probably have to find where a variable is loaded into a register, and follow it from there.
5,211,090
5,211,107
Not using parentheses in constructor call with new (c++)
Possible Duplicate: Do the parentheses after the type name make a difference with new? So I had in my main: Class* pC = new Class; It was working as Class* pC = new Class(); I realized just today that I had omitted the parentheses (so I was hit by the "opposite" of the most vexing parse in a way). My question: Ar...
If the class has a default constructor defined, then both are equivalent; the object will be created by calling that constructor. If the class only has an implicit default constructor, then there is a difference. The first will leave any members of POD type uninitialised; the second will value-initialise them (i.e. set...
5,211,473
5,213,061
Problem with recv() on a tcp connection
I am simulating TCP communication on windows in C. I have sender and a receiver communicating. The sender sends packets of specific size to the receiver. The receiver gets them and sends an ACK for each packet it received back to the sender. If the sender didn't get a specific packet (they are numbered in a header ins...
You are using TCP to communicate between your receiver and transmitter and TCP is a stream-oriented protocol. That is you put a stream of bytes in one end and you get the stream out on the other end, in order and with no loss. There is no guarantee that each send() will match a recv() on the other end as the data may...
5,211,538
5,246,302
Boost Spirit and Boost Phoenix questions
one. Is it possible to define that a spirit rule's local variable be default constructed using a parameter passed into the rule ? I have AST builder objects that have a cyclic dependency, I would like to initialize the child with a reference to the parent, the parent is passed by reference to the child parser's rule. ...
1) There is no way of doing this, although it's a nice idea and worth investigating. 2) Answered here 3) The mini-review of Phoenix V3 has ended March 2nd, the results have been published here.
5,211,600
5,211,615
Using a macro inside a loop condition
I am programing in C++ and I defined a variable as a macro, and I want to return a value from a function using the macro. For some reason the compiler says that I have a syntax error. I am using Linux. #include <iostream> #define FACTOR 10; int dosomthing(){ return (FACTOR/2); } Any suggestions on what might be g...
Macros are replaced. So in the end you'll get return (10;/2); Just remove the ; from your macro and you'll be fine.
5,211,621
5,211,673
assignment vs std::swap and merging and keeping duplicates in seperate object
Say I have two std::set<std::string>s. The first one, old_options, needs to be merged with additional options, contained in new_options. I can't just use std::merge (well, I do, but not only that) because I also check for doubles and warn the user about this accordingly. To this effect, I have void merge_options( set<s...
What's wrong with void merge_options( set<string> &old_options, const set<string> &new_options ) { for (set<string>::iterator i = new_options.begin(); i != new_options.end(); ++i) if (old_options.find(*i) != old_options.end()) warn_duplicate(*i); else old_options.ins...
5,211,646
5,211,821
GCC/g++ cout << vs. printf()
Why does printf("hello world") ends up using more CPU instructions in the assembled code (not considering the standard library used) than cout << "hello world"? For C++ we have: movl $.LC0, %esi movl $_ZSt4cout, %edi call _ZStlsISt11char_traitsIcEERSt13basic_ostreamIcT_ES5_PKc For C: movl $.LC0, %eax mov...
For 64bit gcc -O3 (4.5.0) on Linux x86_64, this reads for: cout << "Hello World" movl $11, %edx ; String length in EDX movl $.LC0, %esi ; String pointer in ESI movl $_ZSt4cout, %edi ; load virtual table entry of "cout" for "ostream" call _ZSt16__ostream_insertIcSt11char_traits...basic_ostream...
5,211,656
5,211,689
Why can't I use templated typedefs in C++?
Consider the following program: #include <iostream> #include <algorithm> using namespace std; template<class T> struct A { typedef pair<T, T> PairType; }; template<class T> struct B { void f(A<T>::PairType p) { cout << "f(" << p.first << ", " << p.second << ")" << endl; } void g(pair<T, T> p)...
The compiler doesn't know that A<T>::PairType is a type when parsing struct B template. The only way of knowing whether A<T>::PairType is a type or not is instantiating both templates, which does not happen until your main function. Tell the compiler explicitly that it is so: void f(typename A<T>::PairType p)
5,211,674
5,218,877
Getting value from json-spirit
I'm using the Json-Spirit library, however i'm unsure how to read value from an object, without iterating over each of the name-value pairs. If i have an object such that: { "boids": { "width": 10, "count": 5, "maxSpeedMin": 2, "maxSpeedMax": 80, "maxForceMin": 0.5, ...
json_spirit added support for std::map so that you can look up a value. One of the projects in the json_spirit download is json_map_demo. This will help you to understand it better.
5,211,752
5,213,763
Implementing a platform independent Glob
I'm trying to implement glob(3), or glob-alike function in C++. I already have a function that reads directory contents into an std::vector<std::string> container (let's call this function ListDirectory()), so I'd obviously only need the stringmatching part - My questions: What kind of concept should one follow when i...
If you are searching platform independent wildcard library, for example, there is shwild library. If you are examining pattern matching for self-educational purpose, as for basic regular expression by backtracking, I think chapter one of Beautiful Code illustrates well. When once you are at home in regular expression, ...
5,211,806
5,211,830
What's the difference between std::merge and std::set_union?
The question is clear, my google- and cplusplus.com/reference-fu is failing me.
std::set_union will contain those elements that are present in both sets only once. std::merge will contain them twice. For example, with A = {1, 2, 5}; B = {2, 3, 4}: union will give C = {1, 2, 3, 4, 5} merge will give D = {1, 2, 2, 3, 4, 5} Both work on sorted ranges, and return a sorted result. Short example: #inc...
5,211,894
5,246,291
Boost Phoenix (or Boost Lambda) - taking a pointer lazily
Is there a way of taking a pointer of a lazy phoenix value / ref ? If so how ?
Phoenix placeholders overload operator&(), therefore a simple &_1 should do the trick (see Phoenix docs here).
5,211,914
5,212,057
Types of iterator : Output vs. Input vs. Forward vs. Random Access Iterator
How many types of iterators are there in C++ STL? As of now, I know of these: Output Iterator Input Iterator Forward Iterator Random Access Iterator Are there more? What are the differences between them? What are the limitations and characteristics of each? Which type is used when?
If you can, find and read "The C++ Standard Library: A Tutorial and Reference". This book contains a whole chapter about STL iterators. Here is a little something from the book: Iterator Category Ability Providers ----------------- ------------------------------- ----------------------------...
5,211,961
5,211,972
How does C++ handle &&? (Short-circuit evaluation)
When encountering a (bool1 && bool2), does c++ ever attempts to check bool2 if bool1 was found false or does it ignore it the way PHP does? Sorry if it is too basic of a question, but I really could not find a mentioning of that neither in Schildt nor on the Internet.
Yes, the && operator in C++ uses short-circuit evaluation so that if bool1 evaluates to false it doesn't bother evaluating bool2. "Short-circuit evaluation" is the fancy term that you want to Google and look for in indexes. The same happens with the || operator, if bool1 evaluates to true then the whole expression will...
5,211,988
5,212,594
Boost Custom Validator for Enum
I am trying to validate command line input to an Enum that I've defined, but get compiler errors. I have used Handle complex options with Boost's program_options as an example to work from. namespace po = boost::program_options; namespace Length { enum UnitType { METER, INCH }; } void validate(boost::any& v...
In your case, you simply need to overload operator>> to extract a Length::Unit from an istream, as shown here: #include <iostream> #include <boost/foreach.hpp> #include <boost/program_options.hpp> namespace Length { enum Unit {METER, INCH}; std::istream& operator>>(std::istream& in, Length::Unit& unit) { std::st...
5,212,018
5,212,058
How to make C++ cout not use scientific notation
double x = 1500; for(int k = 0; k<10 ; k++){ double t = 0; for(int i=0; i<12; i++){ t += x * 0.0675; x += x * 0.0675; } cout<<"Bas ana: "<<x<<"\tSon faiz: "<<t<<"\tSon ana: "<<x+t<<endl; } this the output Bas ana: 3284.78 Son faiz: 1784.78 Son ana: 5069.55 Bas ana: 7...
Use std::fixed stream manipulator: cout<<fixed<<"Bas ana: "<<x<<"\tSon faiz: "<<t<<"\tSon ana: "<<x+t<<endl;
5,212,112
5,212,164
Using Namespace visibility in header
I am working on a c++ library which is split up into multiple namespaces. Since I am trying to avoid the "using" directive in header files I am forced to do the alternative "namespace::class" for variables, returns and parameters. As you can imagine this could get messy. So, I tried putting the using statement inside a...
// your header namespace Project { namespace Utility { class A; } namespace System { using Utility::A; class B { A *a; // instead of Utility::A *a }; } } // end your header class A {}; int main() { using namespace Project::System; A a; } test.cpp:25:5: error: reference to 'A...
5,212,122
5,212,406
What is the relation between Scala and C++ traits
Traits is a concept used in Scala as well as in C++ (although in C++ it is more of an idiom than a concept integrated into the language). It is not obvious to me how the concepts are related though. What is the relation between Scala and C++ traits?
They're not related at all. In C++, a traits class is a helper object that tells you something about a type that you can't get from the type name itself. C++ traits are actually more similar to Scala's def foo[A:Manifest] notation (a feature for which I don't know the proper name.) Scala's traits are actually a lot mor...
5,212,131
5,221,340
Fatal Error: OgreCgPlugin.h: No Such File or Directory (Ogre3d)
After attempting to install Ogre3d from source for Linux, it all built properly but I realized that I had built static libraries. I re-built using CMake again, this time un-ticking the static option. When I create a new Ogre Project in code::blocks and try to compile, I get: __________________________________________...
It almost sounds like when you recompiled (after unchecking static), it didn't install the files afterward, as at some time during the build process it generates a file called OgreBuildSettings.h that holds this information (in this case, it's defining OGRE_STATIC_LIB, despite the fact that you unchecked it.) If you ra...
5,212,346
5,212,382
C++ Operators pre- and post- incrementing
I am not understanding the pre/post incrementing of this code example: int1 = 14; int2 = ++int1; // Assert: int1 == 15 && int2 == 15 In this pre-incrementing example why does int1 == 15? Why is int1 incremented and not just int2? Then we have: int1 = 14; int2 = int1++; // Assert: int1 == 15 && int2 == 14 In this post...
Both ++int1 and int1++ increment int1 because that's what the increment operators do: they increment their operand. The reason that int2 is 15 in the first example and 14 in the second example because the pre-increment and post-increment operators differ in their return value: The post-increment operator increments the...
5,212,360
5,212,383
Problem dereferencing char pointer in C++
I have a small school assignment. My output is not correct. Can you see if I'm doing anything wrong? //1. Create a char pointer named cp char *cp; //2. Dynamically allocate a char and store its address in cp char dynamicChar = 'A'; cp = &dynamicChar; //3. Write the character 'x' into the char *cp = 'x'; //4. Print ...
Try cout << *cp << endl; You want to print the character, not the pointer to it. When you hand it the pointer, cout thinks you're telling it to print out a character array starting there.
5,212,495
5,213,298
c++ compiler for windows mobile
Well I was curious about this and searched for a while but couldn't find anything really, but maybe someone there got an answer... I would like to compile code ON my windows mobile 6, and also probably be able to run it aftewards (note that I'm saying ON not FOR). Does something like that even exist? I mean, 600 MHz CP...
Please have a look at PowerGCC - port GCC to PocketPC platform. It's pretty complicated "quest" to install it. http://www.mpcclub.com/wiki/index.php/CPrograms#Install_a_C_environment_on_PocketPC_.28compiler_etc..29 cke - IDE for mobile platform http://www.animaniak.com/cke/cke_main.asp
5,212,609
5,212,623
Avoiding boilerplate code in a one-to-one association relationship
Although I'm programming in C++, this is more of a general question about design. I noticed that when I have objects in a one-to-one association relationship, there tend to be a lot of common methods between them, leading to boilerplate code that essentially directly calls methods of the inner class. As an example, I h...
Well. To this particular situation. Why not simply implement Tab::getTabbable()? Like this: const ITabbable* Tab::getTabbable() const { return m_tabbableObject; } Then users can do: const ITabbable* obj = tab->getTabbable(); string title = obj->getTitle(); You don't have to replicate all functionality. Update: This ...
5,212,791
5,212,854
STL - Copy mixing containers
I am trying to understand STL algorithms. Copy is defined as : template<class InputIterator, class OutputIterator> OutputIterator copy ( InputIterator first, InputIterator last, OutputIterator result ) Can some one please explain why does the following works when vectors & deques are mixed but fails when vectors a...
Associative containers (in plain C++03) are special containers that keep their elements sorted at all times, commonly implemented as a Red Black Tree. To maintain the order invariant, the set and map iterators provide constant references into the key object, and as such you cannot modify it. In particular for std::set<...
5,212,794
5,212,820
Pass reference to output location vs using return
Which is better for performance when calling a function that provides a simple datatype -- having it fill in a memory location (passed by pointer) or having it return the simple data? I've oversimplified the example returning a static value of 5 here, but assume the lookup/functionality that determines the return value...
In general, if your function acts like a function (that is, returning a single logical value), then it's probably best to use int func(). Even if the return value is a complex C++ object, there's a common optimisation called Return Value Optimisation that avoids unnecessary object copying and makes the two forms roughl...
5,212,985
5,213,026
Parameter-passing of C++ objects with dynamically allocated memory
I'm new to the C++ world, but I have some experience with C and read some tutorials about C++. Now, creating objects in C++ seems quite easy and works well for me as long as the class has only attributes that are values (not pointers). Now, when I try to create objects which allocate memory in the constructor for some ...
Use containers and smart pointers. E.g. std::vector for dynamic length array, or boost::shared_ptr for dynamically allocated single object. Don't deal directly with object lifetime management. Cheers & hth.,
5,213,057
5,213,155
Getting started with SQL express from a c++ console application
Right now I am writing a little c++ console program using VS2010 Express. The next thing I want to do is to access a SQL database from within this program. I've downloaded SQL server 2008 express. I've managed to set up a little db using the db gui. My question now is, how do I access this db from within my program. Wh...
Microsoft doesn't provide much for SQL connectivity from C++ console applications. There are a number of libraries such as SOCI and DTL that can help though.
5,213,107
5,219,984
DirectInput8Create fails : E_INVALIDARG
I'm using DirectInput with Direct3D 11, and compiling for x64 and I get an E_INVALIDARG from this line: HRESULT hr = DirectInput8Create(hInstance, DIRECTINPUT_VERSION, IID_IDirectInput8, reinterpret_cast<void **>(&this->_d8Input), 0); When I set a break point to look at what is going on I get no sign of any invalid ar...
Ok, it turns out I was compiling with /SUBSYSTEM:CONSOLE and the hInstance passed in from WinMain when using a console subsystem doesn't please DirectInput8Create at all.
5,213,119
5,213,163
What does "return obj(value); return?
What does return obj(value);return? Returns it the newly constructed object or a copy of it? The reason why I am asking: Is return obj(value); more efficient than temp = obj(value); return temp; ? Follow-up: If so, is it really a difference, or do compilers optimize this away?
Return statement always returns a copy of the argument object with one exception: when the function returns a reference, the reference might be attached to the argument of return directly, in which case no copy is made, of course. For this reason, from the pedantic point of view in your case there's no way to say what ...
5,213,150
5,213,172
Limited Number of Active Methods?
I am currently working on a recursive program to process datasets of varying sizes. The problem I'm finding is that with my largest dataset (around 350,000 records) my program seems to be terminating without providing any error information. From testing I think it could be due to the recursion leaving too many incompl...
C++ as a language does not. A real implementation of C++ will always have a limit though, and you're using deep enough recursion that running out of stack space certainly sounds quite possible. At least right off, it sounds like recursion is probably a poor choice for the job, though you've given little enough descript...
5,213,188
5,213,228
C++ Macro: how to create an overrite?
So I found a need in using something like Boost.Extension to keep my apps more open to new modules. But as soon as I got to first tutorial I found out that its syntax is quite not like I'm used to: // Depending on the compiler and settings, // it may be necessary to add a specific export // declaration. The BOOST_EXTEN...
You can replace BOOST_EXTENSION_EXPORT_DECL by function with: #define function BOOST_EXTENSION_EXPORT_DECL Then you can use it by: void function boost_extension_hello_world(int repetitions) { for (int i = 0; i < repetitions; ++i) { std::cout << "Hello World" << std::endl; } } But this could cause problems if...
5,213,268
5,213,341
C++ Windows Plugins - Passing Classes
I am working on a plugin system in C++ whereby a C++ executable loads a dll and runs plugin_start(someclass&) via GetProcAddress. I fully understand how to pass function pointers to the dll, and visa versa, and how the dll may use anything defined in a header file, but I would like the dll to be able to use someclass...
I did something like this a long time ago. I simply used a straight C interface to keep things simple. There may be a better way but I think passing a pointer to the object is your best and most straight-forward approach.
5,213,332
5,213,881
Fastest Multi-Reader / Single Writer Protection for Shared Resources - C++
I would like confirmation that my approach is extremely fast and appropriate for cross platform protection of a shared resource for a mostly multiple reader, single writer approach using C++. It favors writers such that when they enter all current threads are allowed to finish, but all new threads of any type must wait...
The decision to leave shared_mutex was made independently of any quality issues. The decision was part of the "Kona compromise" made in the Fall of 2007. This compromise was aimed at reducing the feature set of C++0x so as to ship a standard by 2009. It didn't work, but nevertheless, that is the rationale. shared_mu...
5,213,388
5,214,001
Who owns memory returned by MySQL Connector C++?
I'm having memory leak / deleting errors when using MySQL Connector C++ 1.05. The Connector returns a pointer to a result set from executing query. I am assigning the pointer to a boost::shared_ptr. The call looks like: std::string query_text; query_text = /* ... */; boost::shared_ptr<sql::Statement> query(p_db_conn...
1) According to this example, you're doing everything correct. If you're using the shared_ptr<X> to store the result, it would be automatically disposed after your shared_ptr object goes out of the scope (in your case) / has no more actual references (speaking globally). 2) It depends, but the most common practice is t...
5,213,406
5,213,516
C# getting info from hexadecimal data
I have this hexadecimal data: byte[] data = new Byte[] { 0xC1, 0x3A, 0x00, 0x01, 0x5D, 0xDA, 0x47, 0x53, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,...
Here is one way to do it: struct SERVICE { public byte c; public byte size; public byte headcode; public byte Type; public ushort Port; public string ServiceName; public ushort ServiceCode; }; string GetNullTerminatedString(byte[] data, Encoding encoding) { int index = Array.IndexOf(dat...
5,213,445
5,213,499
Implement a map of strings
I have to implement a class that behaves like a map of strings using binary search tree. This is the class I implemented: template<class T> class StringMapper { private: // Pair struct Pair { std::string el1; T el2; }; // Nod struct Node { Pair* data; Node* left; ...
Your interface is an internal iterator. You need to keep some kind of pointer to where you are in the iteration, and set it in getFirstPair(). Once you add this, getNextPair() just goes to the next one. It's somewhat difficult to do this, but that's your assignment, so I leave it to you. The actual std::map uses an e...
5,213,629
5,213,679
How to enumerate all available network interfaces?
How to enumerate all network interfaces currently available on the computer (including virtual, non-connected, loopback etc)? I need to know their IP4/6, Mask, Gateway, DNS, WINS etc Language: C++, WinAPI System: Windows 2000 and higher (including Win7)
Have a look at http://www.codeproject.com/KB/IP/netcfg.aspx. It's a giant example of what you want to do.
5,213,691
5,213,754
Implementing a C++ array class
For School I have been given a class interface to define my own array class (not inherited). I'm having trouble with overloading the assignment operator (=) and comparison operator (==) as well as the index operator. This was given to me in the class interface: Array& operator = (Array const& array1); // overload as...
First and foremost it's important you understand that the operators you mentioned work on this. Each give you different variables depending on the operator you choose to overload: Assignment operator: Array& operator = (Array const& array1); This operator means "assign array1 to this", it is also known as "copy operat...
5,213,799
5,217,624
(CUDA)nvcc can't parse the toolkit path properly in my project, while in a sample project it can
I have been trying to add a .cu file into my own(dll) win32 project and compile it, using VS2008 on Windows7. I was able to compile a .cu in the cppIntegration sample project, but in my project I was having issues. At first, I got the error "Don't know what to do with "Toolkit...". It seems nvcc was having issues with ...
I solved my issue. The thing is, my environment variable CUDA_PATH had \MyCUDA in it. This worked for cppIntegration because it was on C:, but not for my project because it was on E:. So I had to add C:\MyCUDA. It still doesn't explain why nvcc didn't like the spaces in the path though. Hope someone will find this usef...
5,213,852
5,214,210
Regex with BoostRegex C++
Hi i wish to get the values of the following expression : POLYGON(100 20, 30 40, 20 10, 21 21) Searching POLYGON(100 20, 30 40, 20 10, 21 21) When i execute the following code i obtains this result : POLYGON(100 20, 30 40, 20 10, 21 21) result = 100 20 r2 = 100 r2 = 20 r2 = , 21 21 r2 = 21 size = 7 I don't know ...
I have got the result from IRC channel. The regular expression is : static const boost::regex ex("[\\d\\s]+"); static const boost::regex ex("[\\-\\d\\s]+");
5,213,919
5,213,958
How to access member variables, from non member function within class C++
I have created a class called "ShortestTime". I have some functions within it that are not member functions, but I would like them to be able to access my member variables. ie. I have a function that sorts a List that is a public member variable, but it doesn't have access to this member variable. I have read somethin...
There are ways you could use friend to solve your problem but we would need to see sample code. But my personal approach would be to add a function to ShortestTime that sorts your private member. ShortestTime::SortInterals() { //sort private stuff } Is there a reason that won't work?
5,213,952
5,213,982
Erase window background win32API
My classmates started using Delphi with pascal but I as c++ porgrammer have to use win32 API. They were changing background color so I need to know this aswell but there are some differencies. In delphi each form looks like it has it's own instance, and setting background color for one window is just a matter of changi...
You process WM_ERASEBKGND simply by erasing the background (using FillRect() is fine). By returning a non-zero value, you are simply telling Windows that this message has been taken care of and no further action is needed. There is nothing more formal than that.
5,214,009
5,214,275
SWIG with C++ templates: undefined symbol
C++ Templates and SWIG aren't playing nicely together for me. When I try to import my module I get the error ImportError: ./_simple.so: undefined symbol: _Z9double_itIiET_S0_ I am using SWIG 1.3. Here is a simple example showing the problem: //file: simple.h template <typename T> T double_it (T a); //file: simple.cc ...
Typically templates are defined in a header file instead of in a cc file. With the setup you have, the compiler cannot find / compile the implementation of the template. You will need to change the organization of the code so that the template implementation is available: //file: simple.hh template <typename T> T doub...
5,214,403
5,214,446
How to make a Single Executable VS 2010
I'm making a game using C++ and DirectX and it'd be nice to share my groups progress with other people by providing a single executable file instead of having to run a setup wizard. I've checked my Release and Debug folders but those executable don't work. The release .exe is something like 21KB which doesn't seem ri...
You need to specify that all your libraries have to be statically linked in. There are several threads about doing this in Visual Studio, like: How do you pack a visual studio c++ project for release? How do I make a fully statically linked .exe with Visual Studio Express 2005?. However, to add on to those answers l...
5,214,589
5,216,013
C++: Patching a binary file using fstream
I have a huge file that is already created. I need to write some data at the start of the file while retaining the other contents of the file as such. The following code corrupts the existing file. Can anyone help me with the right method. ofstream oFile(FileName,ios::out|ios::binary); oFile.seekp(0); oFile.writ...
You are missing ios::in Use: ofstream oFile(FileName,ios::out|ios::in|ios::binary);
5,214,611
5,214,681
Unexpected order of evaluation (compiler bug?)
Possible Duplicate: Undefined Behavior and Sequence Points I'm not sure if this is a gcc bug or not, so I'll ask: unsigned int n = 0; std::cout << n++ << n << ++n; gcc gives the extremely strange result: "122" which AFAICT is impossible. Because << is left associative, it should be the same as: operator<<(operator<...
There is a sequence point between evaluating arguments and calling a function. There is no sequence point between evaluating different arguments. Let's look at the outermost function call: operator<<(operator<<(operator<<(std::cout, n++), n), ++n) The arguments are operator<<(operator<<(std::cout, n++), n) and ++n...
5,214,770
5,214,824
How to read a string line by line in C++
I have a string with an xml code in it. I want to read from it line by line so i can extract the strings betweens "title" tags. I know how to extract the titles, but how do i traverse the string ? Sounds easy but i have no idee right now. Thanks in advanced.
Maybe you can give some more details about what extracting the strings between the "title" tags means? If you already can extract the title tags, then that means you know their positions, so then extracting the string is just a matter of taking the substring between the opening and closing title tags right? Are you l...
5,214,790
5,214,797
C++ XOR key is too long?
I have a XOR key (dfficvvifvdfher89429338jwesjcnasidneufhrfdfha23p3rwe23323ncdnhj) but it seems to be way too long, even for long long format. How can I use this key and get rid of "error C2177: constant too big"?
Put each value into a distinct char in a char array, i.e.: const char xor_key[] = "dffic..."; You then XOR however-many characters against the key at a time, then use the key again at the next character after that.
5,214,791
5,214,832
Defining Bit-Flags Using #define in C++
I'm learning about bit-flags. I already know how they work and how they are defined in a struct. However, I'm unsure if they can be defined in a #define preprocessor directive like this: #define FLAG_FAILED:1 Is this preprocessor define directive the as a struct bit-flag definition? PS: I've already come across this ...
Any #define that you want to use to inject bitflags into a struct must take the form: #define IDENTIFIER SUBSTITUTED_CODE In your postulated use... #define FLAG_FAILED:1 The identifier contains the colon, which makes it invalid. You could do something like this: #define FLAG_FAILED int flag_failed :1 struct X { ...
5,215,009
5,215,172
Creating a sequential file
I'm trying to create a sequential file but it doesn't seem to be working. Can anyone explain how to get this to work in MS Visual Studio 2010? #include <iostream> #include <string> #include <fstream> #include <cstdlib> using namespace std; int main() { ofstream outClientFile( "clients.dat", ios::out); if (!ou...
You cannot use an int to store 10-digit telephone numbers, as the 'largest' telephone number you could store would be (in signed int) 2147483647 or (in an unsigned int) 4294967295. Neither of these are large enough to store a phone number from my home state with area codes 503, 541, or 971. Strings are probably best fo...
5,215,011
5,215,030
How can I use a comparison function with more than 2 arguments with a c++ priority queue?
I have an object class that stores a database record. There is also a comparison class that can take in two of these records and an additional object that describes how the ordering should be done. I need to use these two classes with a priority queue to merge the records. From what I can tell, I can only give a com...
Make a function object containing the extra information, either using boost::bind, std::bind, or by hand, then pass that object into the priority queue. Here's a by-hand version: class my_compare { SortOrder so; public: my_compare(const SortOrder& so): so(so) {} bool operator()(const Record& a, const Record& b...
5,215,249
5,215,393
Template Error: no appropriate default constructor available
The thing is, I am not (knowing trying to use any default constructor of beatle::beatle the error: 1> ecosystem.cpp 1>c:\program files (x86)\microsoft visual studio 10.0\vc\include\map(172): error C2512: 'beatle::beatle' : no appropriate default constructor available 1> c:\program files (x86)\microsoft visual...
std::map<>::operator[] requires a default constructor. This is because it first creates an entry in the map then does the operator= that you are calling. If you absolutely want to use an std::map but do not want to provide a default constructor (perhaps it is illogical for your case?) you can use: std::map<>::insert() ...
5,215,554
5,216,754
Visual Studio "Application failed to start because the application configuration is incorrect" error
I obtained some code from a friend, developed on the same system (Windows 7) and same Visual Studio Ultimate 2010, with all the libraries relatively mapped. The code builds, but when trying to run it I get the error: Application failed to start because the application configuration is incorrect" Running Dependency Wa...
Your project uses one or more libraries that were built with Visual Studio 2008, the previous version of Visual Studio. They require the C runtime library for that version to be available; that's why it is complaining about msvcr90.dll. You've got Visual Studio 2010; you only have msvcr100.dll installed on your machine...
5,215,574
5,215,592
question on operator overloading
I am trying to understand a program, which includes the following definition for a function f void f(String S, const String& r) { } Here String in the argument stands for a class. I am confused on the difference between the definitions of these two arguments: "String S" and "const String& r". S should represent an ob...
const String& r is a constant reference to String r. Within the function, you access r just like a String. The difference is that it is actually a reference to the object passed to the function, while S will be a copy of the object passed to the function. You can almost think of it as if you are accessing r through ...
5,215,764
5,215,809
C++: Drawbacks to writing whole classes in Header files for small projects?
Just a style question... I'm a lowly indie game dev working by myself, and I developed what I have been told is a 'bad' habit of writing whole classes in my headers. Some of the benefits I know .h/.cpp file combos have are they allow code to be split into compilation chunks that won't need recompiled so long as they...
is there any compelling reason to follow the "file.cpp" for every "file.h" setup for a small project where compile time and interface/implementation separation are not priorities? Nope; there's nothing wrong with defining classes and functions in header files, especially not in small projects where compile times aren...
5,215,802
5,216,569
C++ just a syntax error: syntax error : identifier
I feel so dumb right now: moveSequence look(COORD xyBeatle, fieldd &field); what could be so wrong about that, to give a syntax error? error C2061: syntax error : identifier 'fieldd' What I am trying to do is pass an a reference of a class fieldd to look() via: moveSequence sequence = look(xy, m_field); It doesn't s...
We really need more code to identify your problem but I wonder if you need to forward declare fieldd since you have refactored the code into different files, perhaps the headers are not included correctly or the dependencies no longer make sense? changing your declaration to: moveSequence look(COORD xyBeatle, class fie...
5,216,006
5,216,947
POST HTTP request to login with username and password with Java script and c++
I have been developing an application with C++ and some parts require connection to http servers, I managed to send GET and HEAD requests and retrieve the webpage. Currently, I'm trying to send a POST request form to a website that requires login in informations, It is similar to the GET request, however, I don't know...
Try rewriting your request as: POST /users/login HTTP/1.1 HOST: www.example.com Content-Type: application/x-www-form-urlencoded Content-Length: 25 username=ME&password=pass I think '25' is the correct length. As an exercise you could download HTTP tools that allow debugging like WireShark and then log in to a general...
5,216,071
5,216,238
SSE and C++ containers
Is there an obvious reason why the following code segfaults ? #include <vector> #include <emmintrin.h> struct point { __m128i v; point() { v = _mm_setr_epi32(0, 0, 0, 0); } }; int main(int argc, char *argv[]) { std::vector<point> a(3); } Thanks Edit: I'm using g++ 4.5.0 on linux/i686, I might not know...
The obvious thing that could have gone wrong would be if v wasn't aligned properly. But it's allocated dynamically by vector, so it isn't subject to stack misalignment issues. However, as phooji correctly points out, a "template" or "prototype" value is passed to the std::vector constructor which will be copied to all...
5,216,125
5,216,325
"Undefined reference to class::function..." - am I linking incorrectly?
I'm working on this NeuralNet class: class NeuralNet { public: // Public functions private: vectors vect; // Point-of-access for functions in class vectors // Private functions }; And I'm using this extremely simple makefile: all: nnet.exe nnet.exe: main.o neuralnet.o vectors.o g++ -o nnet.exe main.o v...
Unless you've defined fn_name() in-line in vectors.h, merely including that header from neuralnet.cpp and neuralnet.h is not sufficient. Make sure you can actually point your finger at that function body. You probably intended for it to be in vectors.cpp. Being a template changes everything. You should define the templ...
5,216,370
5,216,474
variables not initializing in my constructor
So my problem is simple, the data i am initalizing in my constructor is not saving at all. basically I have pin pointed to this one point. I have a constructor in a class strSet::strSet(std::string s){ std::vector<std::string> strVector; strVector.push_back(s); } and in my main file i have else if(command == ...
looks, like your class body already has strVector, so you was declaring it again in constructor, which was wrong, because compiler referenced your new local strVector and not class strVector. you need to change constructor to: strSet::strSet(std::string s){ strVector.push_back(s); }