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
2,232,012
2,232,035
C++, Seg Faults, and Memory Management
I'm moving from Java to C++ and have really enjoyed it. One thing I don't enjoy is not understanding memory at all because Java used to do that for me. I've purchased a book : Memory as a Programming Concept in C and C++ - Frantisek Franek Are there some good sites for me to go and learn interactively about C/C++ and...
Try these: http://www.mycplus.com/tutorials/cplusplus-programming-tutorials/memory-management/ http://www.cantrip.org/wave12.html http://linuxdevcenter.com/pub/a/linux/2003/05/08/cpp_mm-1.html And in wikibook: http://en.wikibooks.org/wiki/C++_Programming/Memory_Management This article will compare the Java memory manag...
2,232,056
2,232,343
Input asked for better programming practices
As I'm learning C++ I started implementing some common datastructures as a form of practice. The first one being a Stack (this was the first to spring in mind). I've done some programming and it's working, but now I need some input as to what I should do otherwise. Like deleting certain stuff or other pro tips. What sh...
Did a first pass of fixes on your code: template <class T> class Stack { private: int* values; int capacity; int itemsOnStack; public: //Stack() : //{ // Stack(32); // doesn't do what you expect. This would create an unnamed temporary stack object //} Stack(const int sz = 32) // C+...
2,232,206
2,232,388
Invalid conversion char to char* - Copying char in string array to another string array
I'm a beginner in C++ Programming language. I wanted to write a program that take the alphabets in a string array called str, and copy it in a new array called str_alpha. And the same goes to numbers, the program copies it from str array to str_digit array. There's my humble code, it might be full of errors and stuff. ...
First of all, strcpy copies C strings (character arrays) not chars. Additionally, the lines strcpy(str_digit[i],str[i]) and strcpy(str_alpha[i], str[i]) would still probably be wrong even if this wasn't the case. Since you haven't initialised the arrays str_digit and str_alpha, you'll get a lot of garbage values while ...
2,232,226
2,232,234
initialize reference in initialization list
I was told the reference variable must be initialized in the initialization list, but why this is wrong? class Foo { public: Foo():x(0) { y = 1; } private: int& x; int y; }; Because 0 is a temporary object? If so, what kind of object can reference be b...
0 is not an lvalue, it's an rvalue. You cannot modify it, but you're trying to bind to a reference where it could be modified. If you make your reference const, it will work as expected. Consider this: int& x = 0; x = 1; // wtf :( This obviously is a no-go. But const&'s can be bound to temporaries (rvalues): const int...
2,232,243
2,232,696
c++, truncate a char array
I'm working on a project where I have a Time class and I need to format the time. void Time::FormatTime(char *string, unsigned int max_string_len) { ostrstream fd; ft << hour << ":" << minutes; cout << ft.str() << endl; } The user passes in a pointer to their string and the max length of the string a...
Always use strncpy() to safely truncate a string into a char[N]. void Time::FormatTime(char *str, unsigned int max_string_len) { if ( max_string_len == 0 ) return; ostringstream ft; // strstream is obsolete, use stringstream ft << hour << ":" << minutes; strncpy( str, ft.str().c_str(), max_string_len );...
2,232,309
2,464,470
Creating a System::String object from a BSTR in Managed C++ - is this way a good idea?
My co-worker is filling a System::String object with double-byte characters from an unmanaged library by the following method: RFC_PARAMETER aux; Object* target; RFC_UNICODE_TYPE_ELEMENT* elm; elm = &(m_coreObject->m_pStructMeta->m_typeElements[index]); aux.name = NULL; aux.nlen = 0; aux.type = elm->type; aux.leng = el...
Actually, the issue was not with the .NET string as an output buffer, but with the input buffer instead. The sprintf("%s") class functions (including wsprintf and so on) will perform a strlen-type operation on any parameters on the string - EVEN if it is snwprintf - the "n" part only limits the amount WRITTEN to the st...
2,232,493
2,232,522
Accessing data members shadowed by parameters
In Java you can access variables in a class by using the keyword this, so you don't have to figure out a new name for the parameters in a function. Java snippet: private int x; public int setX(int x) { this.x = x; } Is there something similar in C++? If not, what the best practice is for naming function parameters...
If you want to access members via this, it's a pointer, so use this->x.
2,232,496
2,232,519
Is it wrong to use C++ 'using' keyword in a header file?
I've been told it's bad to have "using namespace ns123" in a header file, but I can't remember what the reason given was. Is it in fact a bad thing to do, and why?
It's a bad practice, in general, because it defeats the purpose of namespaces. By defining in a header you're not enforcing strict control over the scope of the using declaration, meaning that you can run into name clashes in unexpected places.
2,232,580
2,232,651
Win32: BitTest, BitTestAndComplement, ... <- How to disable this junk?
WinNT.h has the following lines in it, in the VS2008 SP1 install: #define BitTest _bittest #define BitTestAndComplement _bittestandcomplement #define BitTestAndSet _bittestandset #define BitTestAndReset _bittestandreset #define InterlockedBitTestAndSet _interlockedbittestandset #define InterlockedBitTestAndReset _inter...
Unfortunately, Microsoft believes it's OK to make their APIs use macros for names since they do it for 95% or more of their APIs to make them work 'transparently' for ANSI vs. Unicode APIs. It doesn't look like they've provided a clean way to prevent the macro from being defined. I think you're stuck with choosing fro...
2,232,692
2,232,891
Detecting a misspelt virtual function
I've been caught by this problem more than once: class A{ public: virtual ~A() {} virtual int longDescriptiveName(){ return 0; } }; class B: public A{ public: virtual int longDescriptveName(){ return 1; } // Oops }; If the function is pure virtual, the compiler catches the error. But if it's not this can be a ...
One possibility is the little-used pure virtual function with implementation: virtual int longDescriptiveName() = 0 { return 0; } This forces deriving classes to override it. They can then call the base-class implementation alone if they only want that behaviour. Also you need to make sure your inheritance hierar...
2,233,149
2,233,176
Two classes and inline functions
I have two classes and both of them uses some of the other class, on example: // class1.h class Class1; #include "class2.h" class Class1 { public: static Class2 *C2; ... }; // class2.h class Class2; #include "class1.h" class Class2 { public: static Class1 *C1; ... }; And when I define it like in example...
You need to delay including the header, but then include it and define your inline methods. By doing this in each header, they are self-sufficient and including one will always include the other, with include guards preventing infinite recursion. A.hpp #ifndef INCLUDE_GUARD_B9392DB18D114C1B8DFFF9B6052DBDBD #define INC...
2,233,166
2,233,180
Most efficient way to find the greatest of three ints
Below is my pseudo code. function highest(i, j, k) { if(i > j && i > k) { return i; } else if (j > k) { return j; } else { return k; } } I think that works, but is that the most efficient way in C++?
To find the greatest you need to look at exactly 3 ints, no more no less. You're looking at 6 with 3 compares. You should be able to do it in 3 and 2 compares. int ret = max(i,j); ret = max(ret, k); return ret;
2,233,401
2,239,081
Are redundant include guards necessary?
Are 'redundant include guards' necessary in Codegear RAD Studio 2009? Is the compiler smart enough to deal with this on it's own? For example, I might have the following 'include guard' in foo.h: #ifndef fooH #define fooH // ... declaration here #endif and the following 'redundant include guard' in use_foo.h: #ifndef ...
The portion of the code you marked as "redundant include guard" is not necessary but it is a possible optimization. In the case of C++Builder, there is logic to detect header guards, so it should not be necessary. In the general case, the preprocessing pass is usually pretty fast anyhow, so it's unlikely that this opt...
2,233,503
2,233,521
How to get the size of the used space in an array? (NOT sizeof); c++
#include<iostream> using namespace std; int main() { char arr[200]; while(1) { cin >> arr; int i = sizeof(arr); cout << "The arr input is "<< arr << " and the size of the array is "<< i << endl; } return 0; } For the input of 34, This code outputs :The arr input i...
Maybe you want strlen(arr) here. It must be null terminated, otherwise the cout << arr would not have worked. You would need to #include <cstring>
2,233,578
2,233,585
FxCop (or equivalent) for non-.Net C++ code
Is there a way to get FxCop to analyze unmanaged C++ code? Setting the /clr flag allowed FxCop to open the .exe. It find a LOT of C++ items, but the analysis on the code is very weak. For example, the following code was skipped: int i=0; if (i=2) printf("Don't worry..everything will be okay."); I would like a tool...
MSVC (at least VC9/VS2008) already warns about your specific example: warning C4706: assignment within conditional expression (Oops: I just realized that I have my test projects settings cranked up to Warning level 4 - /W4. MSVC doesn't issue this warning at the default setting). So set the project settings to /W4 an...
2,233,932
2,233,949
C++ Confused about Threads
Basicly this is what I have: Server:: Server (int port) { cout << "Initializing server.\n"; (...) pthread_t newthread; pthread_create(&newthread, NULL, &Server::_startListening, NULL); cout << "Exit\n"; pthread_exit(NULL); // <-- Question } void* Server::_startListening (void* param) ...
you probably intend to use pthread_join rather than exit.
2,234,039
2,235,920
Slow writing to array in C++
I was just wondering if this is expected behavior in C++. The code below runs at around 0.001 ms: for(int l=0;l<100000;l++){ int total=0; for( int i = 0; i < num_elements; i++) { total+=i; } } However if the results are written to an array, the time of execution shoots ...
The first example can be implemented using just CPU registers. Those can be accessed billions of times per second. The second example uses so much memory that it certainly overflows L1 and possibly L2 cache (depending on CPU model). That will be slower. Still, 15 ms/100.000 writes comes out to 1.5 ns per write - 667 Mh...
2,234,046
2,235,107
Software to track several memory errors in old project?
I am programming a game since 2 years ago. sometimes some memory errors (ie: a function returning junk instead of what it was supposed to return, or a crash that only happen on Linux, and never happen with GDB or Windows) happen seemly at random. That is, I try to fix it, and some months later the same errors return to...
The Totalview debugger (commercial software) may catch the crash. Purify (commercial software) can help you find memory leaks. Does your code compile free of compiler warnings? Did you run lint?
2,234,071
2,234,088
The relationship between iterators and containers in STL
Good Day, Assume that I am writing a Python-like range in C++. It provides all the characteristics of Random Access containers(Immutable of course). A question is raised in my mind about the following situation: I have two different iterators, that point to different instances of the range container. The thing is that ...
By default, in the STL, two iterators from two different container are not comparable. This means, the behavior is unspecified. So you do whatever you want, nobody should even try. edit After looking carefully at the standard, section 24.1, paragraph 6 states: An iterator j is called reachable from an iterator i if ...
2,234,133
2,234,152
Break out of an overloaded extraction operator? (C++)
I'm trying to use an overloaded ">>" to scan input from a file. The problem is, I have no idea how to deal with end of file. In this case, my file is composed of a number, followed by several chars Ex: 9rl 8d 6ff istream &operator>>(istream &is, Move &move) { char c; int i = 0; c = is.get(); if (!isalnum(c))...
Return is. Callers should check the stream for errors. Be sure to set error bits as appropriate: std::istream &operator>>(std::istream &is, Move &move) { char c; int i = 0; c = is.get(); if (is.eof()) return is; else if (c < '0' || c > '9') { is.setstate(std::ios::badbit); return is; } else ...
2,234,135
2,234,241
Fastest way to convert 16.16 fixed point to 32 bit float in c/c++ on x86?
Most people seem to want to go the other way. I'm wondering if there is a fast way to convert fixed point to floating point, ideally using SSE2. Either straight C or C++ or even asm would be fine.
It's easy as long as you have a double-precision FPU: there are 53 bits of significant figures. SSE2 has double-precision. float conv_fx( int32_t fx ) { double fp = fx; fp = fp / double(1<<16); // multiplication by a constant return fp; }
2,234,257
2,234,260
How do I append a string to a char?
How do I append a string to a char? strcat(TotalRam,str); is what i got but it does not support strings
std::String has a function called c_str(), that gives you a constant pointer to the internal c string, you can use that with c functions. (but make a copy first)
2,234,294
2,234,313
position.hh:46: error: expected unqualified-id before ‘namespace’
Here's my code: 34 35 /** 36 ** \file position.hh 37 ** Define the example::position class. 38 */ 39 40 #ifndef BISON_POSITION_HH 41 #define BISON_POSITION_HH 42 43 #include <iostream> 44 #include <string> 45 46 namespace example 47 { 48 /// Abstract a position...
this happen when a ; or some other closing thing is lacking before the namespace. Are you sure that the lines before 34 have no code? If they have code (even if that code is other #include) the error is there. EDIT: Or in case all 34 lines have no code, the error is on the file that includes this header, most likely th...
2,234,310
3,597,032
Using Mysql blocking API with Boost::asio
I am building a aync single threaded server that receives data from clients. It processes the data and then saves it to the MySQL Database. The problem is that, MySQL C API does not support non-blocking calls and asio mainly does not like blocking calls. So I am thinking something like Python Twisted's deferToThread() ...
There was a post to the Asio mailing list over the summer describing a generic asynchronous service class that seems like it might be useful for you. This pseudo code is from the author's email I linked: // Create a command processor with 5 threads allocated // to processing the commands. async_command_processor proces...
2,234,508
2,234,678
Initialization of list with for_each to random variables
I'm trying to initialize a list to random integers using a for_each and a lambda function. I'm new to boost.lambda functions so I may be using this incorrectly but the following code is producing a list of the same numbers. Every time I run it the number is different but everything in the list is the same: srand(time(0...
Boost lambda will evaluate rand before the functor is made. You need to bind it, so it's evaluated at lambda evaluation time: #include <boost/lambda/lambda.hpp> #include <boost/lambda/bind.hpp> // for bind #include <algorithm> #include <cstdlib> #include <ctime> #include <iostream> #include <vector> int main() { n...
2,234,553
2,235,131
UseQueryResult is not a member of mysqlpp
That's the error I get when I run this code : if(mysqlpp::UseQueryResult res = conn.query(sql).use()) Whats more interesting is that the next line doesn't have any problems while(mysqlpp::Row row = res.fetch_row()) Really driving me crazy. I've even manually included result.h I tried all combos of these include resu...
Is it possible that you're using an old version of MySQL++? The StoreQueryResult class used to be called Result before version 3.0.0. Edit: Er... and UseQueryResult used to be called ResUse, which is a bit more relevant to your error message.
2,234,557
2,234,955
C++ using getline() prints: pointer being freed was not allocated in XCode
I'm trying to use std:getline() but getting a strange runtime error: malloc: * error for object 0x10000a720: pointer being freed was not allocated * set a breakpoint in malloc_error_break to debug This is the code that produces this error: //main.cpp #include <iostream> #include <sstream> int main (int argc, char ...
At least one person has reported problems with g++ 4.2.1 on Apple that seem possibly related to yours having to do with an improper configuration of the standard library with the _GLIBCXX_FULLY_DYNAMIC_STRING definition (not that I understand any of what I'm typing here). You might get a bit of a clue from the newsgro...
2,234,952
2,234,980
Ambiguity between IID_IDropTarget and Virtualtrees::IID_IDropTarget
I'm currently going through a process of refactoring includes to reduce compile time, and I've come across the following compile error: [C++ Error] some_class.cpp(53): E2015 Ambiguity between 'IID_IDropTarget' and 'Virtualtrees::IID_IDropTarget' The line of code it points to is: if (iid == IID_IUnknown || iid == IID_I...
COM's IID_DropTarget is declared like so: EXTERN_C const IID IID_IDropTarget; Since it's extern "C", it's in the root namespace: ::IID_IDropTarget
2,235,137
2,243,559
c++: following piece of code crashes
#include <iostream> using namespace std; class B { public: B() { cout << "Base B()" << endl; } ~B() { cout << "Base ~B()" << endl; } private: int x; }; class D : public B { public: D() { cout << "Derived D()" << endl; } virtual ~D() { cout << "Derived ~D()" << endl; } }; int main ( void ) { B...
What you are doing is UB, but for the specific compiler you are using behavior can be described as follows. To ease the ASCII-graphics below, modifying the example, adding a y member to D and modifying main. #include <iostream> using namespace std; class B { public: B() { cout << "Base B()" << endl; } ~B() { c...
2,235,208
2,306,125
How to decode huffman code quickly?
I have implementated a simple compressor using pure huffman code under Windows.But I do not know much about how to decode the compressed file quickly,my bad algorithm is: Enumerate all the huffman code in the code table then compare it with the bits in the compressed file.It turns out horrible result:decompressing 3MB ...
One way to optimise the binary-tree approach is to use a lookup table. You arrange the table so that you can look up a particular encoded bit-pattern directly, allowing for the maximum possible bit-width of any code. Since most codes don't use the full maximum width, they are included at multiple locations in the table...
2,235,219
2,235,274
Overloading the global type conversion operator
To test and display the result of some functions of my library, I am creating a set of handy functions. I have an execute function that looks like : template <typename R, typename I> std::string execute( const std::string& func_name, R(*func_ptr)( const I& ), const I& func_input ); It calls the function, and display t...
Conversion operators (cast operators) must be a member of the convertible class that produces the converted type. As assignment operators, they must be member functions, as your compiler is telling you. Depending on how much effort you want to put into the debug part of it, you could try to use metaprogramming to forwa...
2,235,325
2,235,349
Simple C++ syntax question about colon
I just saw a code snippet with a piece of syntax that I have never seen before. What does bool start : 1; mean? I found it inside a class definition in a header file.
struct record { char *name; int refcount : 4; unsigned dirty : 1; }; Those are bit-fields; the number gives the exact size of the field, in bits. (See any complete book on C for the details.) Bit-fields can be used to save space in structures having several binary flags or other small fields, and they can ...
2,235,360
2,235,382
Making a borderless window with for Qt
I'm new to Qt C++. I downloaded the latest windows version, did some tutorials and its great. I saw some styling options that the Qt framework has and its great, but now I need to build my application that its main windows (form) it designed/skinned with image without the rectangle borders (borderless?). How can I do ...
If your looking for some advanced styling in the shape of a widget, maybe this example will help you: Shaped Clock Example Or maybe you're simply looking for this kind of flag: Qt::CustomizeWindowHint or simply Qt::FramelessWindowHint.
2,235,366
2,235,393
How to assign a string to char *pw in c++
How to assign a string to char *pw in c++ like... char *pw = some string ??
For constant initialization you can simply use const char *pw = "mypassword"; if the string is stored in a variable, and you need to make a copy of the string then you can use strcpy() function char *pw = new char(strlen(myvariable) + 1); strcpy(pw, myvariable); // use of pw delete [] pw; // do not forget to free all...
2,235,447
2,236,083
XML in C++ Builder 6
How can I use XML as a simple data storage in Borland C++ Builder 6? Is there an internal class, which I could use? Thank's for help
I'm not sure whether the TXmlDocument is implemented in C++Builder 6, but a more simple solution would be to use the TinyXML [1] library, which is indeed simple, and easy to use. I have used it with different versions of C++ Builder and it works like a charm. [1] http://www.grinninglizard.com/tinyxml/
2,235,457
2,235,492
How to explain undefined behavior to know-it-all newbies?
There'a a handful of situations that the C++ standard attributes as undefined behavior. For example if I allocate with new[], then try to free with delete (not delete[]) that's undefined behavior - anything can happen - it might work, it might crash nastily, it might corrupt something silently and plant a timed problem...
"Congratulations, you've defined the behavior that compiler has for that operation. I'll expect the report on the behavior that the other 200 compilers that exist in the world exhibit to be on my desk by 10 AM tomorrow. Don't disappoint me now, your future looks promising!"
2,235,767
2,235,838
Storing function pointers
The following uses a simple function pointer, but what if I want to store that function pointer? In that case, what would the variable declaration look like? #include <iostream> #include <vector> using namespace std; double operation(double (*functocall)(double), double wsum); double get_unipolar(double); double get...
You code is almost done already, you just seem to call it improperly, it should be simply double operation(double (*functocall)(double), double wsum) { double g; g = functocall(wsum); return g; } If you want to have a variable, it's declared in the same way double (*functocall2)(double) = get_bipolar; or ...
2,235,826
2,235,983
Winsock2 recv() hook into a remote process
I was trying to hook a custom recv() winsock2.0 method to a remote process, so that my function executes instead of the one in the process, i have been googling this and i found some really good example, but they lack description typedef (WINAPI * WSAREC)( SOCKET s, char *buf, int len, int flags ) = recv; Now my quest...
where did you find such an example ? the first line tries to define a new type WSAREC, which is a pointer to a function having the same signature as recv(). unfortunately, it is also trying to declare a variable of this type to store the address of the recv() function. the typedef is wrong since the function is lackin...
2,236,007
2,236,139
ActiveX code from Visual C++ port to Borland C++ Builder
I have the following code example for Visual C++ which creates an ActiveX object which can then be used. // create a smart pointer for ActiveDSO _DActiveDSOPtr activeDSO; HRESULT hr = activeDSO.GetActiveObject(__uuidof(ActiveDSO)); if (FAILED(hr)) { hr = activeDSO.CreateInstance(__uuidof(Activ...
I used to know how to do this, but I haven't used C++ Builder in more than 5 years. I do remember that C++ Builder comes at ActiveX from a completely different direction, and that code sample won't "translate". Better to find C++ Builder tutorials and work from there (looking at Deliphi tutorials will also help, they...
2,236,182
2,236,232
What is the difference between using a struct with two fields and a pair?
What is the difference regarding memory allocation and efficiency between using a struct with two fields and a pair?
std::pair provides pre-written constructors and comparison operators. This also allows them to be stored in containers like std::map without you needing to write, for example, the copy constructor or strict weak ordering via operator < (such as required by std::map). If you don't write them you can't make a mistake (...
2,236,197
2,236,227
What is the easiest way to initialize a std::vector with hardcoded elements?
I can create an array and initialize it like this: int a[] = {10, 20, 30}; How do I create a std::vector and initialize it similarly elegant? The best way I know is: std::vector<int> ints; ints.push_back(10); ints.push_back(20); ints.push_back(30); Is there a better way?
One method would be to use the array to initialize the vector static const int arr[] = {16,2,77,29}; vector<int> vec (arr, arr + sizeof(arr) / sizeof(arr[0]) );
2,236,302
13,014,365
Crashing C++ application including ada dll does not generate core dump
How do I get a C++ application including a loaded ada shared library to generate a core dump when crashing? I have a C++ application which loads a ada shared library, inside the ada code I get a stack overflow error which causes program termination along with the console output: raised STORAGE ERROR No core dump file ...
Now, almost 2 years later (still working at the same company as Kristofer did when he asked the question), was the question raised again - and finally I think that I understands why no core-dump is generated!! The problem is caused by the Ada run-time, which by default implements a signal handler for some POSIX-signal...
2,236,445
2,236,519
deleting element (objects) within a vector (not referenced by pointer) , memory handling
This is an extension of this question . I have searched on the web but couldn't find a satisfactory answer. I have a class A which defines a vector that contains a number of instances of class Region. The memory handling for these Region instances need to be managed by Class A My questions are: 1. In the following co...
In the following code snippet, do I need to explicitly delete these instances in the desctuctor of class A? No - they will be automatically deleted for you - if you don't create it with new, you don't delete it. Should I create instances as new Region(i) ? Is it better over the first option (not using new) Cla...
2,236,467
2,379,414
CMake + find package or check out and install
I just switched to CMake. And yet found it very useful and realized some simple apps and libs. Somewhere I read that it's possible to query git to checkout repositories from within cmake scripts. I'd like to check for the existence of a package with my Find(package).cmake If it doesn't exist i'd like to initiate a chec...
You're probably thinking about the ExternalProject module added in CMake 2.8. It's documented at http://www.cmake.org/cmake/help/cmake-2-8-docs.html#module:ExternalProject with an intro to it at page 14 of http://www.kitware.com/products/archive/kitware_quarterly1009.pdf. It allows you checkout/download a project and b...
2,236,699
2,236,792
Will `typedef enum {} t` allow scoped enum element identifiers in C++0x?
I believe the new C++ standard allows for an extra "scope" for enumerated types: enum E { e1, e2 }; E var = E::e1; Since I know lots of source files containing the old C-style enum typedef, I wondered if the new standard would allow using the typedef for these otherwise anonymous enumerated types: typedef enum { d1, ...
The new standard will add a new type of strong enum, but the syntax will be slightly different, and old style enums will be compatible (valid code in C++03 will be valid C++0x code) so you will not need to do anything to keep legacy code valid (not the typedef, not anything else). enum class E { e1, e2 }; // new syntax...
2,236,924
2,236,963
C++ and Enum and class members
Following code is not compiling, can anybody please help what is wrong here class CTrapInfo { public: enum GenericType { ColdStart, WarmStart, LinkDown, LinkUp, AuthenticationFailure, EGPNeighborLoss, EnterpriseSpecific }; CTrapInfo(); ...
It compiles for me, in VS2005, if I forward declare class CAPTrapInfo and class DOMSTring.
2,237,100
2,237,515
Is there any way to specify a generic argument to a function with the restriction that it should implement a given interface
Example: I have a function that works with vectors: double interpolate2d(const vector<double> & xvals, const vector<double> & yvals, double xv, double yv, const vector<vector<double> > &fvals) { int xhi, xlo, yhi, ylo; double xphi, yphi; bracketval(xvals,xv,xhi,xlo,xphi); bracketval(yvals,yv,yhi,ylo,yph...
This works with std::vector, boost::array, built-in arrays an generally with anything that is indexable. I've also included a suggestion of how you should implement the bracketval function: template<class Vec> void bracketval(Vec const & xvals, double xv, int xhi, int xlo, double xphi) { } template <class Vec, class V...
2,237,582
2,237,701
Can someone tell me why my code generates a segmentation on SPOJ? and what is the segmentation fault error ?(FCTRL2)
#include<stdio.h> #include<iostream> #include<string> #include<string.h> using namespace std; char arr[200],res[200]; char table[150][200]; string multiply(char n[],int m) { int N=strlen(n),M,temp=0,x=0; for(int i=0;i<N;i++) arr[i]=n[N-1-i]; for(int i=0;i<N;i++) { x=m*(arr[i]-'0')+temp; ...
If you replace the return type of the function multiply from string to void the segfault is gone. A segmentation fault happens when you try to read/write memory you don't have access to. For instance you can try writing on read only memory, or reading at address 0x00000000. A common way to achieve segfaults is by using...
2,237,603
2,237,647
Questions about the static keyword with functions and data
I have a few questions about the static keyword in C++ (and probably with other languages as well.) What is the purpose of declaring a function as static? void static foo(int aNumber) { ... } How about a static inline function? void static inline foo(int aNumber) { ... } Is there any benefit to using the static keyword...
Depends on Context: Like many things in C++, static means different things depending on its context. It's very common in C++ for the same word to mean different things depending on its context. For example: * is used for multiplication, dereferencing a pointer, and creating pointers. & is used to get the address...
2,237,775
2,237,837
How to return different classes from one function?
I have a question, though it is not limited to C++. How to return totally different class from one function? f() { in case one: return A; in case two: return B; in case three: return C; } For example, I have two balls in the space, according to the position and the size, there are three situations for the two ball...
If you can afford Boost then this sounds like a perfect application for Boost.Variant. struct NoIntersection { // empty }; struct Point { // whatever }; struct Circle { // whatever }; typedef boost::variant<NoIntersection, Point, Circle> IntersectionResult; IntersectionResult intersection_test() { ...
2,237,980
2,237,998
How do I convert a char* to an int?
I need to convert a char* to an integer. For example: data.SetBytFldPos(*attribute->value()); The value in the attribute class is a char*. 'SetBytFldPos" takes an int.
Lots of ways. Simplest is to use the strtol() function.
2,238,166
2,238,463
What is the difference between asio::tcp::socket's async_read_some and async_receive?
What is the difference between: boost::asio::tcp::socket::async_read_some() boost::asio::tcp::socket::async_receive() As far as I can tell their documentation is identical. Which should I prefer?
Their specification in the networking TR2 proposal (5.7.10.2 basic_stream_socket members) is identical too: On async_receive: Effects: Calls this->service.async_receive(this->implementation, buffers, 0, handler). On async_read_some: Effects: Calls this->service.async_receive(this->implementation, buffers, 0, handler...
2,238,170
2,244,824
Forward declaration of nested enum
I have code similar to the following: class B { } class A { enum { EOne, ETwo } EMyEnum; B myB; } I want to declare a member of type EMyEnum in class B (which is declared before A). Is this possible? I realise the solution is to declare class B second, but for clarity I would prefer not to.
It's not possible... but it can be faked with inheritance abuse :) namespace detail { class A_EMyEnum { public: enum { EOne, ETwo } EMyEnum; protected: A_EMyEnum() {} A_EMyEnum(const A_EMyEnum&) {} A_EMyEnum& operator=(const A_EMyEnum&) { return *this; } ~A_EMyEnum() {} ...
2,238,224
2,239,157
String and character mapping question for the guru's out there
Here's a problem thats got me stumped (solution wise): Given a str S, apply character mappings Cm = {a=(m,o,p),d=(q,u),...} and print out all possible combinations using C or C++. The string can be any length, and the number of character mappings varies, and there won't be any mappings that map to another map (thus av...
Definitely possible, not really difficult... but this will generate lots of strings that's for sure. The first thing to remark is that you know how many strings it's going to generate beforehand, so it's easy to do some sanity check :) The second: it sounds like a recursive solution would be easy (like many traversal p...
2,238,241
2,238,434
Is it possible to use COM visible .NET classes with registration free COM?
We're developing a ClickOnce application with a mixture of .NET components and legacy C++ COM components. Currently we're adding the C++ COM components to the user's machine using an MSI (this is a prerequisite to installing our ClickOnce app) which means we can register the COM objects on the user's machine beforehand...
Yes, that's possible. You'll need to use the <clrClass> element in the manifest. There's a decent how-to located here. The SDK docs are otherwise pretty miserable, you'll need Junfeng Zhang's blog to get better background info.
2,238,456
2,238,533
How does C's "extern" work?
I have a C/C++ program that's a plugin to Firefox. Because it's a plugin, it has non-main entry points. Those entrypoints need to be compiled in C because otherwise they get name mangled.However, other functions are over-loaded, so they need to be C++. The solution is extern "C". That much I've already figured out. How...
Extern "C" should apply to function prototype, so if you have separate prototype and implementation, put extern declaration around prototypes. Implementation, provided prototype is visible, will be extern as well and not mangled. It is not a bug.
2,238,639
2,238,702
why does MS C++ add this code to assembly?
i have some code(inline assembly). void NativeLoop() { int m; __asm { PUSH ECX PUSH EDX MOV ECX, 100000000 NEXTLOOP: MOV EDX, ECX AND EDX, 0X7FFFFFFF MOV DWORD PTR m, EDX DEC ECX JNZ NEXTLOOP POP EDX POP ECX } } M...
It is the standard function entry and exit code. It establishes and tears down the stack frame. If you don't want it you can use __declspec(naked). Don't forget to include the RET if you do. However, your snippet relies on a valid stack frame, your "m" variable requires it. It is addressed at [ebp-10]. Without the...
2,238,840
2,238,853
C++, #ifdef question
Not coding in C++ right now but a question came up when I have a question in C#. Hope experts here can easily give a anwser. Class A{ #ifdef AFlag public void methodA(){...} #endif } Class B{ ... A a; a.methodA(); ... } Class C { ... A a; a.methodA(); ... } If the AFlag is NOT defined anywhere, what wi...
There will be a compile error.
2,238,896
2,238,957
C++ templated typedef
I have a templated class template <T> class Example { ... }; inside which there are many methods of the following type: template <class U> <class V> method(....) Inside these I use tr1::shared_ptr to U or V or T. Its tedious typing tr1::shared_ptr<const U> or tr1::shared_ptr<const V>. The obvious thing to do: templ...
You can use an inner type: template <typename U> struct sptr { typedef tr1::shared_ptr<U> t; }; Then say sptr<U>::t, or unfortunately often typename sptr<U>::t. C++0x has template typedefs, you could check whether your compiler can be persuaded to accept them: template<typename U> using sptr = tr1::shared_ptr<U>; ...
2,239,380
2,239,401
what does the operator string() { some code } do?
I have the following code in a class: operator string() { return format("CN(%d)", _fd); } And wanted to know what this operator does. I am familiar with the usual string operators: bool operator==(const string& c1, const string& c2); bool operator!=(const string& c1, const string& c2); bool operator<(const str...
operator Type() { ... } is the (implicit) conversion operator. For example, if class Animal implements operator string(), then the code Animal a; ... do_something_with ( (string)a ); will become something like do_something_with ( (Animal::operator string)(&a) ); See http://publib.boulder.ibm.com/infocenter/comphelp/...
2,239,389
2,239,649
How can I implement Google Maps-like tile scrolling in Qt?
I'm using Qt/C++ and trying to draw a large and complex QGraphicsScene. Once I add a lot of objects, panning and zooming become unpleasantly slow. (No surprise here, of course). I've played with device coordinate caching (helps with panning to a point) and minimal viewport updates and so on, but eventually there's j...
Take a look here: Generating content in threads. It sounds like this is similar to what you are trying to do. Tile mechanisms are very common ways to load in large amounts of data. Other than the link posted, I have not seen a simple example using QGraphicsView. 40000 Chips also shows some things about managing large...
2,239,519
2,239,571
Is there a way to specify how many characters of a string to print out using printf()?
Is there a way to specify how many characters of a string to print out (similar to decimal places in ints)? printf ("Here are the first 8 chars: %s\n", "A string that is more than 8 chars"); Would like it to print: Here are the first 8 chars: A string
The basic way is: printf ("Here are the first 8 chars: %.8s\n", "A string that is more than 8 chars"); The other, often more useful, way is: printf ("Here are the first %d chars: %.*s\n", 8, 8, "A string that is more than 8 chars"); Here, you specify the length as an int argument to printf(), which treats the '*' in ...
2,239,591
2,239,807
How to capture CTRL + CTRL key presses in my Win32 application?
How would I capture the user pressing Ctrl twice (Ctrl + Ctrl) globally. I want to be able to have my application window hidden and then make it visible when the user invokes it with the CtrlCtrl key presses similar to Google Quick Search Box. The user may have focus on a different window. I've looked at RegisterHotKey...
To create such a hotkey, do this: ATOM hotkey = GlobalAddAtom("Your hotkey atom name"); if(hotkey) RegisterHotKey(hwnd, hotkey, MOD_CONTROL, VK_CONTROL); else { ...error... } And then handle the WM_HOTKEY message: case WM_HOTKEY: if(wParam == hotkey) { // CTRL pressed!!! } break; I guess you'll fig...
2,239,607
2,239,770
Can a recursive function write to a file in C++?
I'm going to have two class functions. The first class function opens the file. Then it calls a second function that writes to the file and recursively calls itself. When the second function finishes, the original function closes the file. Is it possible to do this?
Sure, as long as you pass the file handle/object to the recursive function: void recursion(int data, int maxdepth, ostream &os) { // must eventually break out if (maxdepth == 0) return; // write data os << data << std::endl; // and call one deeper recursion(data + 1, maxdepth - 1, os);...
2,239,730
2,239,787
Compiling C++ for MacOSX 10.5 and 10.6
I have a reasonably simple C++ program that I can successfully compile on OSX 10.6 using: g++ -O3 -funroll-loops -I /usr/local/include/boost-1_39/ myfile.cpp -o build/myfile However, a user on OSX 10.5 gets the error: dyld: unknown required load command A support forum post suggests adding -isysroot /Developer/SDKs/M...
This questions has been solved, I believe, using the suggested command.
2,239,872
2,239,945
How to get list of folders in this folder?
How to get list of folders in this folder?
If you can't use .NET & Managed code, you can go through the win32 api's Here is an example that you can modify to only get Folders. (Basically the following check:) ... TCHAR szDir = _T("c:\\"); // or wherever. HANDLE hFind = FindFirstFile(szDir, &ffd); ... do { if (ffd.dwFileAttributes & FILE_ATTRIBUTE_DI...
2,239,952
2,247,090
VS2008 attaching a debugger (C++) to handle assert(...)
There are two scenarios that I'm interested to improve in my assert. 1) a debug build app is started regularly, if there is an assertion I'm getting "Debug assertion failed" dialog box with "Abort", "Retry", "Ignore". Abort and Ignore answers are working fine. The problem with Retry. If I hit retry I'm getting that use...
Take a look at the registry entry HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\AeDebug. I think that if you set Auto to 1, that the debugger is automatically started. And of course changing the assert implementation can also help you (take a look at the SuperAssert of John Robbins from his famous Deb...
2,240,083
2,240,105
versions of C++ standard library
What are difference between The GNU C++ Library (libstdc++), "C++ Standard Library", "Standard Template Library" and "SGI STL". When programming in Linux with compiler GCC and programming in Windos in MSVC (MicroSoft Visual C++), which the standard C++ libraries are using by default? Thanks!
C++ standard library - the generic definition of what functionality / behavior must be provided by the library (strings, pairs, iostream, containers, algorithms, etc. although the specifics vary depending on the version of the C++ standard). Standard Template Library (STL) - the part of the C++ standard library that ha...
2,240,094
2,240,128
Initializing a Char*[]
Question is in the title, how do I initialize a char*[] and give values to it in C++, thank you.
Though you're probably aware, char*[] is an array of pointers to characters, and I would guess you want to store a number of strings. Initializing an array of such pointers is as simple as: char ** array = new char *[SIZE]; ...or if you're allocating memory on the stack: char * array[SIZE]; You would then probably wa...
2,240,227
2,240,248
Detecting whether cookies are enabled through IWebBrowser2 Interface
Is it possible to detect whether cookies are enabled in Internet Explorer through the IWebBrowser2 Interface or through some other WebBrowser Control C/C++ interface? I can't see any obvious way to do it, but was wondering whether there is a subtle way.
You can pass the URL to InternetGetPerSiteCookieDecision() and it should tell you what the policy is for that site. It is a pretty terribly named API. :-/
2,240,269
2,240,965
Writing XML strips trailing spaces
I am trying to write an XML file using MSXML4. It works fine except when I have a data element with a trailing space which must be preserved. Given the following code to insert a new element: const _bstr_t k_Parent (ToBSTR("ParentNode")); const _bstr_t k_Child (ToBSTR("ChildNode")); const _bstr_t k_Data ...
Mystery solved. Don't preview your XML in Internet Explorer. It hides trailing spaces. Use notepad instead.
2,240,289
2,240,659
Need transparent overlay window to draw lines on top of window drawing video? ::MFC,C++,windows::
How do you create a transparent window that can be placed over another window that is actively having streaming video drawn to it. I want to create a window on top of the video window that I can draw on without video constantly drawing back over it. I can create a window from a transparent dialog resource and set its ...
Video is rendered to a hardware overlay in the video adapter. You'll need to create your own to overlay that overlay. I think DirectX provides that capability, you can also get it by using the WS_EX_LAYERED window style and the SetLayeredWindowAttributes(). Which you'll need to set the transparency key. Not so sure...
2,240,405
2,240,457
byte array assignment
byte test[4]; memset(test,0x00,4); test[]={0xb4,0xaf,0x98,0x1a}; the above code is giving me an error expected primary-expression before ']' token. can anyone tell me whats wrong with this type of assignment?
What Ben and Chris are saying is. byte test[4]={0xb4,0xaf,0x98,0x1a}; If you want to do it at run time, you can use memcpy to do the job. byte startState[4]={0xb4,0xaf,0x98,0x1a}; byte test[4]; memcpy(test, startState, sizeof(test));
2,240,620
2,240,691
C++ Template class using STL container and a typedef
I have a class looking like this: #include <vector> #include "record.h" #include "sortcalls.h" template< typename T, template<typename , typename Allocator = std::allocator<T> > class Cont = std::vector> class Sort: public SortCall { This code is working and I'm calling it like this from other classes: Compar...
Don't use template template parameters (Cont in your code), they are brittle and inflexible. Use a rebind mechanism if you need to (std::allocator is an example), but you don't in this case: template<class T, class Cont=std::vector<T> > struct Sort { typedef Cont container_type; // if you need to access it from outs...
2,240,669
2,241,001
Virtual inheritance bug in MSVC
It seems that my problem is a bug in MSVC. I'm using the Visual Studio 2008 with Service Pack 1, and my code works with GCC (as tested on codepad.org). Any official info on this bug? Any ideas how to work around it? Is the bug fixed in VS2010? All insights would be greatly appreciated. The code: struct Base { Base(...
It looks as though the compiler is not correctly adjusting the this pointer when calling through A::clone. If you remove the declaration of A::clone then everything works fine. Digging in deeper, when you have A::clone, the vtable looks like this: [0x0] 0x002f1136 [thunk]:B::`vector deleting destructor'`vtordisp{...
2,240,773
2,240,780
Compiling error: Function Parameters using Object References are Confused by Constructed Objects
In the unit test of a class, I try to declare a class variable by calling explicitly the empty constructor and pass it to a function that excepts a reference to the interface of the type I'm declaring, but the compiler produces error. When I just declare it without any explicit constructor call the function accepts it...
This line: CTestController controllerB(); is the declaration of a function that takes nothing and returns a CTestController. For default construction, you must simply leave off the parenthesis. This is related to something called the "most vexing parse". Consider: struct S {}; int main() { S s(S()); // copy const...
2,240,947
2,241,095
Can i call shell command and output of this save to string on Windows?
In other words something like pipe in windows
The boilerplate code is in this MSDN Library article.
2,241,089
2,241,330
Alpha/texturing issues in an OpenGL wrapper
I'm in the process of writing a wrapper for some OpenGL functions. The goal is to wrap the context used by the game Neverwinter Nights, in order to apply post-processing shader effects. After learning OpenGL (this is my first attempt to use it) and much playing with DLLs and redirection, I have a somewhat working syste...
I don't quite understand how your code is supposed to integrate with the Neverwinter Nights code. However... It seems like you're most likely changing some setting that the existing code didn't expect to change. Based on the description of the problem, I'd try removing the following line: glDisable(GL_TEXTURE_2D); Th...
2,241,166
2,241,320
C or C++ for OpenGL graphics
there is any drawback in choose C++ and an object oriented model (classes) to implement a simulation in OpenGL (or DirectX)? It's preferred to use C and a procedural programming paradigm ?
The most common drawback of object oriented programming in the context of high performance graphics (games etc.) is the memory bottleneck. OOP often (but not necessarily) leads to writing functions that operate on single elements and leveraging the standard library to generalize these to arrays. It might be preferable ...
2,241,327
2,241,444
How do I pass a C++11 random number generator to a function?
Do they all inherit from a base class? Do I have to use templates? (I am referring to these http://www.codeguru.com/cpp/cpp/cpp_mfc/stl/article.php/c15319/) I am doing this right now: typedef std::mt19937 RNG; and then class Chooser { public: Chooser(RNG& rng, uint n, uint min_choices, uint max_choices): In othe...
They don't all inherit from a base (which is a little surprising), but it doesn't matter because that's not how C++ functors work. For arbitrary RNGs of a single given type, you got it right as (now) posted. If you mean, how do I define a function which accepts any random number generator as an argument. template< clas...
2,241,475
2,241,778
Strange runtime error, seemly microsoft related
I am using the debug_new tool that come in the pack of tools NVWA made by Wu Yongwei. http://wyw.dcweb.cn/ I turned it off once to track a heisenbug, that now is fixed. But as I turned it on, my program throws a bizarre error: It loads, but before accepting any input it quits and writes on the console: "This applicatio...
If you're running under the Visual Studio debugger, go to the Debug/Exceptions menu and check the box for the "C++ Exceptions" item - this will cause the debugger to break whenever an exception is thrown. You might need to fiddle with the various sub-options (std:exception, void, etc) for the exception types if your co...
2,241,699
2,241,728
Is shallow copy sufficient for structures with char[]?
I have a structure containing character arrays with no any other member functions. I am doing assignment operation between two instances of these structures. If I'm not mistaken, it is doing shallow copy. Is shallow copy safe in this case? I've tried this in C++ and it worked but I would just like to confirm if this be...
If by "shallow copy", you mean that after assignment of a struct containing an array, the array would point to the original struct's data, then: it can't. Each element of the array has to be copied over to the new struct. "Shallow copy" comes into the picture if your struct has pointers. If it doesn't, you can't do ...
2,241,786
2,241,832
Is it safe to pass (synchronously) stack-allocated memory to other thread?
Recently I heard that memory in the stack is not shared with other thread and memory in the heap is shared with other threads. I normally do: HWND otherThreadHwnd; DWORD commandId; // initialize commandId and otherThreadHwnd struct MyData { int data1_; long data2_; void* chunk_; }; int abc() { MyData myData;...
I think 2 different issues are being confused by whoever you "heard that memory in the stack is not shared with other thread": object lifetime - the data on the stack is only valid as long the thread doesn't leave the scope of the variable's name. In the example you giove, you're handling this by making the call to t...
2,241,808
2,241,818
Checking if a folder exists (and creating folders) in Qt, C++
In Qt, how do I check if a given folder exists in the current directory? If it doesn't exist, how do I then create an empty folder?
To check if a directory named "Folder" exists use: QDir("Folder").exists(); To create a new folder named "MyFolder" use: QDir().mkdir("MyFolder");
2,241,821
2,365,229
Qt 4.6 - How to drag and drop into a QGraphicsView in QtCreator?
I've been trying to figure out how to drag and drop an image into a QGraphicsView using Qt and the QtCreator IDE. I have read the documentation here: http://doc.trolltech.com/4.6/qgraphicsscene.html#dragEnterEvent This documentation is too general for me to understand. Can anyone give me an example that works? I also ...
DragAndDrop: DragEnterEvent is to be overridden (in code) on a QWidget of your choice. Look at some basic code examples in QtAssistant on how to drag and drop. QGraphicsView is a type-of QWidget. Promotions: Lets say you designed a class X that inherits from QGraphicsView. While you are in QtCreator, you can add a QGra...
2,241,834
2,241,876
Why is my char* writable and sometimes read only in C++
I have had really big problems understand the char* lately. Let's say I made a recursive function to revert a char* but depending on how I initialize it I get some access violations, and in my C++ primer I didn't find anything giving me the right path to understand so I am seeking your help. CASE 1 First case where I g...
The key is that some of these pointers are pointing at allocated memory (which is read/write) and some of them are pointing at string constants. String constants are stored in a different location than the allocated memory, and can't be changed. Well most of the time. Often vulnerabilities in systems are the result ...
2,241,835
2,241,884
C++ How come I can't assign a base class to a child class?
I have code like this: class Base { public: void operator = (const Base& base_) { } }; class Child : public Base { public: }; void func() { const Base base; Child child; child = base; } My question is: since Child derives from Base (hence it should inherit Base's operator= ), how come when the statement...
The standard provides the reason for your specific question in 12.8/10 "Copying class objects" (emphasis added): Because a copy assignment operator is implicitly declared for a class if not declared by the user, a base class copy assignment operator is always hidden by the copy assignment operator of a derived class (...
2,241,897
2,241,923
What does the C++ language standard say about how static_cast handles reducing the size of an integer?
I would like to know the rules specified by the C++ language standard for situations like: long x = 200; short y = static_cast<short>(x); Is y guaranteed to be 200, or does the standard leave this up to the implementation to decide? How well do various compilers adhere to the standard?
In this case the static_cast<> is an 'explicit type conversion. the standard has this to say about integral conversions in 4.7/3 "Integral conversions": If the destination type is signed, the value is unchanged if it can be represented in the destination type (and bit-field width); otherwise, the value is implementat...
2,241,944
2,241,987
'class X' has no member 'Y'
This error is inexplicably occurring. Here is the code and output: timer.cpp: #include "timer.h" #include "SDL.h" #include "SDL_timer.h" void cTimer::recordCurrentTime() { this->previous_t = this->current_t; this->current_t = SDL_GetTicks(); } timer.h: #include "SDL.h" #include "SDL_timer.h" class cTimer ...
Works for me. Are you sure you've got the right timer.h? Try this: cat timer.h and verify that it's what you think it is. If so, try adding ^__^ at the beginning of your .h file and seeing if you get a syntax error. It should look something like this: [/tmp]> g++ -Wall -I/tmp/foo -c timer.cpp In file included from tim...
2,241,949
2,241,963
Why does my C++ code fail to delete all nodes in my BST?
This is supposed to traverse a BST and delete every node, including the root node. However, at the end, I get the message "root still has a left node." Why aren't all nodes deleted? void deleteTree() { deleteNode(root); if(root->right) cout << "root still has a right node" << endl; if(root->lef...
Your are deleting p at the end (root) and then trying to access its contents in deleteTree(), where root no longer points to allocated memory. The result is going to be undefined.
2,242,057
2,242,070
Using 'virtual' in derived class
I saw code in a derived class recently in which the programmer put virtual in front of the functions overridden. Is this common? I thought it was very odd and it kind of caught me off guard. Edit: I'm not asking what virtual does, I'm asking why someone would put virtual in a derived class that is already overriding v...
virtual is needed for overrideable functions at the highest (least derived) level. It is optional, but harmless at lower (more derived) levels. It's good for self-documenting the code.
2,242,097
2,242,129
How to print out a BST in C++
My C++ program creates a binary search tree. I know how to print out the values in pre-order, post-order, and in-order. However, I want to do something a little more difficult. I want to print out the values the way they would look if someone drew the tree on paper. It would have the root at the center at the top, i...
This article contains code for what you need, it seems: alt text http://www.cpp-programming.net/wp-content/uploads/2007/12/ascii_tree.jpg Edit: that site went offline Here's another one exploring some other options.
2,242,370
2,242,382
How to convert these lines of c code to c++
I'm trying to import some c code into my c++ program. There are three lines that don't import directly: The first: free(t); The second: new_node = (Tree *) malloc (sizeof (Tree)); The third: Tree * delete(int value, Tree * t) How can these be changed to work in C++?
The first two lines should be valid C++, assuming you've included stdlib.h, and have defined Tree as a class/struct/type somewhere. The third line will need to be changed, since 'delete' is a keyword in C++ and can't be used as a function name. Try doing a global replace in the C code and changing all instances of 'de...
2,242,593
2,242,600
When comparing for equality is it okay to use `==`?
When comparing for equality is it okay to use ==? For example: int a = 3; int b = 4; If checking for equality should you use: if (a == b) { . . . } Would the situation change if floating point numbers were used?
'==' is perfectly good for integer values. You should not compare floats for equality; use an tolerance approach: if (fabs(a - b) < tolerance) { // a and b are equal to within tolerance }
2,242,619
2,242,694
Testing for Type Equality without RTTI
Say B and C are derived from A. I want to be able to test whether any two instances of classes derived from A are instances of the same class, that is, whether A* foo and A* bar both point to B instances, without using RTTI. My current solution is something like this: class A { protected: typedef uintptr_t Code; ...
You should just use RTTI instead of reinventing the wheel. If you insist on not using RTTI, you could use CRTP and a function-local static variable to avoid having to write the function to every derived class. Adapt from this example code I wrote for Wikipedia: http://en.wikipedia.org/wiki/Curiously_recurring_template_...
2,242,687
2,243,577
Help streaming over http in C++
I'm looking to use a web service that offers a streaming api. This api can typically be used by the java method java.net.URL.openStream(); Problem is I am trying to design my program in C++ and have no idea what libraries (I've heard the cUrl library is very good at this sort of thing) to use, or how to use them to do...
Boost.Asio socket iostreams seem to be what you're after. Your code will look like this: ip::tcp::iostream stream("www.someserver.com", "http"); if (!stream) { // Can't connect. } // Use stream as a regular C++ input stream: std::string text; std::getline(stream, text); If you're new to C++ and have no experience w...
2,242,696
2,242,769
C structure and C++ structure
Could anybody please tell me what is the main difference between C & C++ structures.
In C++ struct and class are the exact same thing, except for that struct defaults to public visibility and class defaults to private visiblity. In C, struct names are in their own namespace, so if you have struct Foo {};, you need to write struct Foo foo; to create a variable of that type, while in C++ you can write ju...
2,242,774
2,242,778
converting c style string to c++ style string
Can anyone please tell me how to convert a C style string (i.e a char* ) to a c++ style string (i.e. std::string) in a C++ program? Thanks a lot.
std::string can take a char * as a constructor parameter, and via a number of operators. char * mystr = "asdf"; std::string mycppstr(mystr); or for the language lawyers const char * mystr = "asdf"; std::string mycppstr(mystr);
2,242,821
2,242,828
STL compilation error when defining iterator within template class
The code below gives the error: error: type ‘std::list<T,std::allocator<_Tp1> >’ is not derived from type ‘Foo<T>’ error: expected ‘;’ before ‘iter’ #include <list> template <class T> class Foo { public: std::list<T>::iterator iter; private: std::list<T> elements; }; Why and what should this be to...
You need typename std::list<T>::iterator. This is because list depends on the template parameter, so the compiler cannot know what exactly is the name iterator within it going to be (well, technically it could know, but the C++ standard doesn't work that way). The keyword typename tells the compiler that what follows i...
2,242,838
2,242,896
regarding file i/o in c++
I have a part of a code that does the following: It reads in sentences from a file in a particular format, puts them in a vector. To probe whether the strings in the vector are stored correctly, I put debugging cout statements. I found that the last string member member of the vector is "". Why is this so? The file I a...
Because you are not handling end of file (eof) correctly. You can only tell that you've reached the eof when you've tried to read beyond the end of the file. Consider the case of a 0 length file. When that happens, this will be the case. FILE *fp = fopen(..., "r"); assert(!feof(fp)); // guaranteed, even if the file ...