question_id
int64
25
74.7M
answer_id
int64
332
74.7M
title
stringlengths
20
150
question
stringlengths
23
4.1k
answer
stringlengths
20
4.1k
4,764,328
4,764,356
Map SQL table rows to C++ structures
I'm trying to implement some kind of persistent storage of C++ structures into an SQLite database. It looks nice in the beginning but then it becomes complicated with all those SQL requests, data binds and manual getting field values one after another. Ideally I'd like to have some kind of mapping from a table row in S...
Sounds like you want an Object Relational Mapper (ORM). Try reading through this stack overflow thread: https://stackoverflow.com/questions/74141/good-orm-for-c-solutions The selected answer there talks about Database Template Library; I'd look into there as well.
4,764,557
4,907,610
Android C++ Development with Visual Studio
I am trying to figure out how to setup android development with Visual Studio. I plan on using C++ (targeting 2.3 and above), but I see very little on the subject. Does anyone know how to do this? I know that Android development suggests Java/Eclipse, however, I want to do C++/VS.
vs-android vs-android is intended to provide a collection of scripts and utilities to support integrated development of Android NDK C/C++ software under Microsoft Visual Studio. Currently vs-android only works under Visual Studio 2010. Earlier versions lack the MSBuild integration with the C/C++ compilat...
4,764,590
4,764,658
Can I use a lambda function or std::function object in place of a function pointer?
I've got a library that I need to use that defines the following: typedef void CallbackFunction(const int& i); and has a function to register your callback that looks like: void registerCallback(CallbackFunction* pCallback); Because I'd like to capture the state of several variables to be used in the callback, I can'...
In general, no you can't use a lambda or function object where a function pointer is required. Function objects are full-fledged objects that have overloaded the application operator (()) so you can use them as functions syntactically. The standard algorithms are written as templates, which allows you to pass either ...
4,764,661
4,798,158
Error Calling Unmanaged DLL Function from Managed Code
I've written a DLL in unmanaged visual C++, and I'm having a little trouble getting it to work with both C# and C++ applications. Here's what the prototype in the C++ DLL looks like: extern "C" __declspec(dllexport) int WINAPI ZBNConnect( UCHAR dev, LPARAM hWnd, ZBCallbackFn rfn, ZBCallbackFn nfn, int DevType, byte * ...
It turned out that adding WINAPI to the function declaration and definition was causing the function name in the DLL to be mangled. Unfortunately, WINAPI was required to maintain compatibility with applications already deployed. The fix was to add an extra export to the linker: #pragma comment(linker, "/EXPORT:ZBNCon...
4,764,858
4,764,903
foreach not recognized in C++
In my the cs106b book we use the expression "foreach" to go through a list of words in a Map. I implemented the code and banged my head against the wall facing mysterious errors. Here's the code: void DisplayWordCounts(Map<int> & wordsCount) { foreach (string word in wordsCount) { cout << left << setw(...
foreach is not a standard C++ feature. This was something Eric Roberts and I developed for the Stanford introductory programming sequence and predates the more modern C++11 range-based for loop. Now that C++11 compiler support is more widespread, we've stopped using foreach and just opted to go with the standard C++ en...
4,764,897
4,764,909
Converting a C-style string to a C++ std::string
What is the best way to convert a C-style string to a C++ std::string? In the past I've done it using stringstreams. Is there a better way?
C++ strings have a constructor that lets you construct a std::string directly from a C-style string: const char* myStr = "This is a C string!"; std::string myCppString = myStr; Or, alternatively: std::string myCppString = "This is a C string!"; As @TrevorHickey notes in the comments, be careful to make sure that the ...
4,764,917
19,260,724
Wow64DisableWow64FsRedirection and GetNamedSecurityInfo - unavoidable ERROR_BAD_EXE_FORMAT?
I am using Wow64DisableWow64FsRedirection / Wow64RevertWow64FsRedirection to disable and restore WOW-64 file redirection (making system32\ to syswow64\ and some registry changes). The MSDN page warns that you should use these pairs very close together because they effect all I/O operations, including loading DLLs. I ha...
It's enough that you pre-load ntmarta.dll before calling Wow64DisableWow64FsRedirection (LoadLibrary("ntmarta.dll")). In this way GetNamedSecurityInfo / SetNamedSecurityInfo API will not return ERROR_BAD_EXE_FORMAT before that module is preloaded before (see ADVAPI32!AccProvpLoadMartaFunctions function code).
4,765,007
4,765,028
How does std::map operator[] cause memory leak with fundamental data types?
I'm using Visual Leak Detector to detect memory leaks, and have encountered many instances of memory leaks in lines such as: class SomeClass { // ... std::map<long,long> some_map; void func(long a_long, long b_long) { some_map[a_long] = b_long; // here be a memory leak } } How is this eve...
The code you've posted here is perfectly fine and shouldn't cause any leaks, so there are a few possible culprits: Some STL implementations use custom allocators that retain dynamically-allocated memory without freeing it in order to make future allocations faster. It's possible that you have such an implementation a...
4,765,137
4,765,160
Why does Map with a pointer to template functor as value_type not work?
Visual studio borks when I try to create a std::map with the value type being a pointer to template-functor. Am I doing something illegal here ? // Functor prototype template< class T, class evenT> class FunctionHandler {}; // std::Map definition template <class T, class evenT> map<int, FunctionHandler<T, evenT>* > lo...
The problem is that you cannot have a "variable template". It doesn't make any sense. You need to create a variable with a specific type (i.e. specific values for T and evenT), or do something like: template <class T, class evenT> class SomeClass { map<int, FunctionHandler<T, evenT>* > lookup; };
4,765,146
4,765,178
Segfault when using *this
I'm getting a segfault when I try to access a member of a class from within a method of that same class, which does not make sense to me at all. I have the Tree class: class Tree { public: Coord* root; Tree(int x, int y) { root = new Coord(x, y); populateTree(); } void populateTree() { queue<Coord*> nod...
You need to initialise the elements of Coord::children. They aren't guaranteed to be NULL, so in populateTree(), when you do the null test on each child, you will get non-null children although they will not point to a valid Coord. When they are popped off the queue, and you call getValidMoves() on the invalid Coord yo...
4,765,214
4,765,249
Boost::shared_ptr instantiated using this
Consider the following case: typedef boost::shared_ptr<B> BPtr; class A { public: A() { b_ptr = BPtr(new B); } void a_func() { C::c_func(b_ptr); } private: BPtr b_ptr; } class B { public: B() { b_ptr = BPtr(this); } void b_func() { C::c_func(b_ptr); } private: BPtr b_ptr; } class C { public: ...
Is it ok to instantiate a shared_ptr with this? No, for at least several reasons: If you create a A or B object on the stack or statically, you end up with a shared_ptr "owning" the object created on the stack; when the object is destroyed, the shared_ptr destructor will be called, calling delete on the object, and ...
4,765,512
4,766,765
C zip library that can create password protected zip files on windows?
Anyone know of a C library that can create password protected zip files on windows? It appears that the option to password protect zip files with the built-in zip utility has been removed from windows 7, but I don't think this is an issue. Can either zziplib or the 7-Zip SDK do this?
7-Zip SDK (LZMA SDK) supports password protected archive. Related SO post: https://stackoverflow.com/questions/221049/how-secure-is-7-zip LZMA SDK: http://www.7-zip.org/sdk.html
4,766,071
4,766,167
Observer pattern in c++
I am having a bit of trouble with observer pattern I have a beverage class that uses decorator fine. I am trying to implement observer to let an observer( say a cell phone/text message) in this case know when there order is done. i wont include the beverage/decorator classes since they work fine. In main i was going to...
One error is that Subject::Register is currently taking an Observer object, instead of a pointer to an Observer. This means that you're trying to instantiate an abstract object, which is illegal.
4,766,145
4,766,204
Getting the raw value of a c++ ofstream's put pointer (for storage)
To get the position of a c++ ofstream's output pointer, I call ostream::tellp() which returns a streampos object. I want to store this value, which may be quite large, into a binary file. However, I cannot find a way to get the raw value of the output pointer's position from this streampos object. If I were not worri...
streampos is a typedef for some (typically unsigned) integer type. Despite the position in the file often being called the "put pointer", there's not actually a pointer value to obtain. On most recent compilers, streampos is going to compile to a native 64 bit integer, (i.e. unsigned long long, or unsigned __int64 on m...
4,766,323
4,766,385
how to determine sizeof class with virtual functions?
this is kind of homework question. For the following code, #include <iostream> using namespace std; class A { public: virtual void f(){} }; class B { public: virtual void f2(){} }; class C: public A, public B { public: virtual void f3(){} }; class D: public C { public: virtual void f4(){} }; int m...
This is of course implementation-dependent. And it would make a terrible interview question. A good C++ programmer can just trust sizeof to be right and let the compiler worry about those vtable things. But what's going on here is that a typical vtable-based implementation needs two vtables in objects of class C or D...
4,766,942
4,766,952
C++ - #include "filename"
At this tutorial it mentions the following about #include "filename": #include "filename" tells the compiler to look for the file in directory containing the source file doing the #include. If that fails, it will act identically to the angled brackets case. What is meant by the bolded font sentence? Thanks.
While the exact details are implementation-dependent, there are a few common practices. In most common compilers, using the quotes #include "filename.h" searches the current directory by default. Using angle brackets #include <filename.h> searches system-defined library directories. What it is saying is that if the ...
4,766,951
4,766,989
C++ - Macro defines directive
At: http://www.learncpp.com/cpp-tutorial/110-a-first-look-at-the-preprocessor/ It mentions a directive called "Macro defines". What do we mean when we say "Macro"? Thanks.
A macro is a code fragment that gets substituted into your program by the preprocessor (before compilation proper begins). This may be a function-like block, or it may be a constant value. A warning when using a function-like macro. Consider the following code: #define foo(x) x*x If you call foo(3), it will become (...
4,766,964
4,766,985
How can the assignment from int to object be possible in C++?
class phone { public: phone(int x) { num = x; } int number(void) { return num; } void number(int x) { num = x; } private: int num; }; int main(void) { phone p1(10); p1 = 20; // here! return 0; } Hi, guys Just I declared a simple class like above one. After...
This is legal because C++ interprets any constructor that can be called with a single argument of type T as a means of implicitly converting from Ts to the custom object type. In your case, the code p1 = 20; is interpreted as p1.operator= (20); Which is, in turn, interpreted as p1.operator= (phone(20)); This behavi...
4,767,158
4,768,428
Playing RTP stream from embedded device using sockets
I'm writing an application on an embedded device which receives an RTP stream which carries G.729, PCM or H.264. The packets arrive to my application as a char* to the RTP packet. I would like to be able to see or listen to the stream (as a test), but on this device I don't have player. I thought I may forward this str...
no, you cannot. simple RTP doesn't contain any info about the stream format etc., only info about the packet itself: sequence number, timestamp, additional synchronization info. the simplest way to stream RTP is RTP/MPEG TS (MPEG Transport Stream). unfortunately I don't know ready to use solution. VLC can stream (and ...
4,767,228
4,767,273
C++ containers' iterators
This question may sounds lame, but I haven't found clear answer. Can I assume, that iterator returned by map's find() method will this points at the same data even if I'll add (or remove) other elements to the same map? It's unclear for me if map's iterator points at position in map or at specific data...
You can keep using the same iterator after insert or erase operations. The standard says (C++03 standard, Section 23.1.2, paragraph 8): The insert members shall not affect the validity of iterators and references to the container, and the erase members shall invalidate only iterators and references to the erased ele...
4,767,307
4,767,552
Algorithm finding path in an undirected tree
Suppose I am given a undirected tree and I need to find a path(the only path) between two nodes. What is the best algorithm to do it.I probably could use a Dijkstra's algorithm but there a probably something better for trees. C++ example would be helpful but not necessary Thank you
Supposing you have struct Node { std::vector<Node *> children; }; then what could be done is traversing the whole tree starting at root keeping the whole chain during the traversal. If you find e.g. node1 then you save the current chain, if you find node2 then you check for the intersection... in code (UNTESTED): ...
4,767,414
4,767,441
implementing operator * in C++
class Rational { const Rational operator*(const Rational& rhs) const ... }; Rational oneHalf(1,2); Rational result = oneHalf * 2; // fine (with non-explicit ctor) result = 2 * oneHalf; // error! (even with non-explicit ctor) It was mentioned by scott meyers in Effective C++ book as below Even whe...
When you write an operator, try to think of it in terms of an explicit function call. Rational oneHalf(1, 2); Rational result = oneHalf.multiply(2); // Ok, can convert Rational result = 2.multiply(oneHalf); // OWAIT, no such function on int. Since there is no such operator on an int, the compiler doesn't know how to h...
4,767,447
4,767,536
Open persistent connection
I want to implement a system that will open a persistent connection between a server and a client (iPhone, in this case), and when it's needed send information using this connection. How can I implement something like this? Maybe somebody already wrote something that reach this case?
The most obvious solution would be to use an NSStream. (The Cocoa libraries are incredibly rich, so there's nearly always a solution for common functionality like this.) However, are you sure you really require a persistent connection? (Especially on a mobile device that may occasionally drop signal/switch from WiFi to...
4,767,455
4,769,463
determining whether a window is in desktop bounds c++
I wrote some code to determinate whether a certain window is inside the desktop bounds. Somehow, it doesn't work. For every window, regardless whether it is inside or outside the desktop, false is returned. Something is terribly wrong here, but after staring at this piece of code for 3 hours now, I still don't know whe...
PostMessage(FindWindow(NULL, L"Window #1"), RegisterWindowMessage(L"PMSG"), (WPARAM)&R, d.dmPelsWidth); will not work if "Window #1" is in another process, you can't just pass a RECT pointer cross process, if you need to pass something larger than a pointer cross process, use WM_COPYDATA. Even if it is not cross proces...
4,767,524
4,767,551
Error in the standards?
§5/4 C++ standard i = 7, i++, i++; // i becomes 9 i = ++i + 1; //the behavior is unspecified That should be changed to i = 7, i++, i++; // the behavior is undefined i = ++i + 1; //the behavior is undefined right?
i = 7, i++, i++; // i becomes 9 is perfectly fine. Operator = has higher precedence than ,so the expression is equivalent to (i = 7), i++, i++; which is perfectly well defined behaviour because , is a sequence point. As far as i = ++i + 1; //the behavior is unspecified is concerned the behaviour is undefined in C...
4,767,609
4,767,838
What tool should I use to create my buildmachine?
I am working on my free time on a multiplatform/multi-architecture library written in C++. Before every release, I have to boot up several computers (One on Windows, one on Linux, another one on Mac OS, ...) just to make sure the code compiles and runs fine on every platform. So I decided to create my own buildmachine ...
I would setup 3 VMs (VirtualBox is free), one for each platform. Install TeamCity (or Hudson) on Linux and agents on the other VMs and then it's just a matter of configuring the build system. At the very basic level you should have 2 tasks: one to checkout the sources from Subversion and another to invoke scons. I'm...
4,767,620
4,767,654
Move constructor seemingly not executed
This is my first experiment with C++0x rvalue references and something strange seems to be going on. In the code sample below the factory function MakeWindow returns a Window object by value. The caller uses it to initialize a Window object. If I understood correctly, this should invoke the move constructor. In order t...
Isn’t it obvious? Your code returns a copy of the local temporary Window: Window MakeWindow() { return Window(CreateWindow()); } The compiler will in fact optimize this copy away (via return value optimization) – this is why your move constructor is never actually called – but for correctness a copy constructor mu...
4,767,665
4,767,814
pre-commit hook validating c++ code
Today I've updated our repository and tried to recompile it (it's a c++ application). It doesn't compile. My first reaction was to kill my coworker, but because I can't do it I need to find another solution. Is it possibile to prevent to commit code that doesn't compile? We have a Makefile and what the pre-commit hook ...
It's right in principle. However, it will likely cause major delays in committing (unless your application compiles in under a second). So you should really look for a different approach, where it lets users commit, but than starts a build process right away, and sends out email if it fails to build. One way of doing t...
4,767,667
4,767,767
C++ - enum vs. const vs. #define
At the end of the article here: http://www.learncpp.com/cpp-tutorial/45-enumerated-types/, it mentions the following: Finally, as with constant variables, enumerated types show up in the debugger, making them more useful than #defined values in this regard. How is the bold sentence above achieved? Thanks.
Consider this code, #define WIDTH 300 enum econst { eWidth=300 }; const int Width=300; struct sample{}; int main() { sample s; int x = eWidth * s; //error 1 int y = WIDTH * s; //error 2 int z = Width * s; //error 3 return 0; } Obviously each multiplication results in c...
4,767,677
4,767,683
C++ - constant variable, is it a correct term?
At the end of the artile here: http://www.learncpp.com/cpp-tutorial/45-enumerated-types/ It mentions the following sentence: Finally, as with constant variables, enumerated types show up in the debugger, making them more useful than #defined values in this regard. Is "constant variables" a correct term to use? Aren't c...
A constant is a variable. In C++ (and most languages), defining a variable as a constant simply tells the compiler that the variable is not allowed to be changed.
4,767,870
4,767,886
C++ - structs... function parameter issue
At: http://www.learncpp.com/cpp-tutorial/82-classes-and-class-members/ It has the following code: // Declare a DateStruct variable DateStruct sToday; // Initialize it manually sToday.nMonth = 10; sToday.nDay = 14; sToday.nYear = 2020; // Here is a function to initialize a date void SetDate(DateStruct &sDate, int nMon...
It means it will take as a first argument a reference to a DateStruct and that this reference will be called sDate in the function's body. The sDate reference is then used in each lines of the body: sDate.nMonth = nMonth; sDate.nDay = nDay; sDate.nYear = nYear;
4,767,920
4,768,012
How to read integers elegantly using C++ stream?
I have a file full of lines in this format: 1 - 2: 3 I want to only load numbers using C++ streams. Whats the most elegant way to do it? I only thought about cin.get() and checikng each char if it is number or not.
You can use a locale to change what things are read from the file as it is being read. That is, you will filter out all non-numeric values: struct numeric_only: std::ctype<char> { numeric_only(): std::ctype<char>(get_table()) {} static std::ctype_base::mask const* get_table() { static std::vector...
4,767,925
4,767,951
How to force gcc to link unreferenced, static C++ objects from a library
I'm using a C++ library that can be built as either a shared or a static library. This library uses a factory technique, where static objects register themselves when the program starts and the static objects get created. This works fine as long as the shared library is used. When the static version is used, none of th...
You can use -Wl,--whole-archive -lyourlib , see the manpage for ld for more info. Any static libraries mentioned after -Wl,--whole-archive on the command line gets fully included, you can turn this off again too if you need to , as in e.g. -Wl,--whole-archive -lyourlib -Wl,--no-whole-archive -lotherlib
4,768,125
4,768,495
How to compile C++ files organized in a directory structure?
I've written a bunch of code now, and sorted it in a fashion similar to this outline: project/ + include/ | + bar/ | | bar.hpp | foo.hpp + src/ | + bar/ | | bar.cpp | foo.cpp | main.cpp My question is, how do I call g++ now, so that it links everything together nicely? I've already figured out that I need to...
I would recommend using some kind of build tool like CMake or Autotools. Creating your own Makefiles can be kind of a PITA to get right. If you have a small directory structure with some C++ files which you want to quickly compile, you can do something like this: find src/ -name "*.cpp" | xargs g++ -I include/
4,768,271
4,768,293
strncpy documentation question
At the following regarding strncpy: http://www.cplusplus.com/reference/clibrary/cstring/strncpy/, it mentions the following: No null-character is implicitly appended to the end of destination, so destination will only be null-terminated if the length of the C string in source is less than num. What is meant by this s...
It means that, for example, if your source string is 20 characters plus a null terminator and your strncpy specifies less than 21 characters, the target string will not have a null appended to it. It's because of the way it works: strncpy guarantees that it will write exactly N bytes where N is the length value passed ...
4,768,294
4,768,360
Multithreading in c++
I want to run one function with different parameters on different threads: int threads = 3; int par1[] = {1, 2, 3}; int par2[] = {4, 5, 6}; for (int i=0; i<threads; i++){ //new_thread function(par1[i], par2[i]); } I know nothing about threads. I tried to do something the windows API (can't use other libraries), but ...
One sample example for Windows, #include <Windows.h> struct thread_data { int m_id; thread_data(int id) : m_id(id) {} }; DWORD WINAPI thread_func(LPVOID lpParameter) { thread_data *td = (thread_data*)lpParameter; cout << "thread with id = " << td->m_id << endl; return 0; } int main() { for (int i=0; i< 10; i++) ...
4,768,508
4,768,553
C++ subclassing access modifier?
I'm C++ newbie, and I have many years of experience about OO languages such as C/C#/Objective-C. Now, I'm learning C++. I saw this C++ code: class World : public State { }; It seems class World inherits the class State publicly. Public subclassing? It's hard to understand. What's the concept of this featu...
The need for the public keyword there is just that for classes defined with the keyword class, the default access modifier (for everything - data members, member functions, and base classes) is private. So class World : State {}; is the same as: class World : private State {}; and that's probably not what you want - ...
4,768,903
4,769,368
Restricting std::sort to random access iterators
I was just wondering, since you can only pass random access iterators to std::sort anyway, why not enforce that restriction by defining it only for random access iterators in the first place? #include <iterator> #include <type_traits> template <typename ForwardIterator> typename std::enable_if< std::is_same< ...
The core language has always been expressive enough to handle such checks, but when the first standard was being prepared (around 1996/1997), the tricks that you can play with SFINAE (what enable_if is based upon) were not yet known and the support for advanced template wizardry was limited in the compilers. So, the re...
4,768,956
4,768,981
I need someone who explain me these lines of code
I need someone who explain me this code, line by line. I specially don't understand this line: operator std::map<T, U>() Thank you very much. template <typename T, typename U> class create_map { std::map<T, U> m_map; public: create_map(const T& key, const U& val) { m_map[key] = val; } ...
operator std::map<T, U>() { return m_map; } This is user-defined conversion function. That means, you can write this: //obj is an object of type create_map create_map<int,std::string> obj(1,"Nawaz"); //obj implicitly converts into std::map type! std::map<int,std::string> map_inst=obj; See this t...
4,769,034
4,769,133
Automatically deducing the type of bind1st(mem_fun(&my_class::f), this)?
I would like to pass the bind1st(mem_fun(&my_class::f), this) functor to for_each. Unfortunately it is very difficult to read so I would like to give it a more readible name like this: (the type I am looking for) meaningful_name = bind1st(mem_fun(&my_class::f), this); for_each(v.begin(), v.end(), meaningful_name); Is...
This depends on the argument and return types of my_class:f. If the function is T my_class::f(A arg) then you need binder1st<mem_fun1_t<T,my_class,A> > meaningful_name = bind1st(mem_fun(&my_class::f), this); This kind of thing will be nicer with C++0x: auto meaningful_name = bind1st(mem_fun(&my_class::f), this);
4,769,052
4,769,195
Reducing amount of if/if code (C++)
In my program I have to create an object, which looks like that: Library::Param1<Library::Param2>::Param3 (don't know how to name Param, types maybe?) Similar to std::vector<std::string>::iterator. So, these Param's need to be changed by strings. For example: if(param1 == "1_VALUE1") { if(param2 == "2_VALUE1") ...
I agree with Mark B that a factory would be nice, but I'm not sure if this is possible if you do not have a base class that all these types inherit from. If I understand the problem correcty, you have 15 types for Value 1 and 15 types for Value2 which leads to 15*15 if-statements. You can reduce them to 2*15 with the ...
4,769,229
4,769,269
How will _Exit behave in a C++ program?
C99 offers the _Exit function, which exits "immediately", although it does may close file descriptors. Unix/POSIX extends this behavior by mandating the closing of all fd's without flushing (and offers the synonym _exit). Will these functions call destructors for static objects when called from a C++ program? Does the ...
It simply doesn't exist in standard C++, so there are no guarantees. It is planned for inclusion in C++0x. That specifies (§18.5): The function _Exit(int status) has additional behavior in this International Standard: — The program is terminated without executing destructors for objects of automatic, thread, ...
4,769,308
4,770,590
send mouse position data from QGraphicsItem to label on mainwindow
I created a custom QGraphicsItem and I am able to find the mouse position over the image by overriding the hoverMoveEvent. How can I send that position data to a QLabel that is in my main window, that has my GraphicsView so that the label is always showing the pixel coordinates over the main label? Do I have to use a t...
I would use the signal/slot mechanism of Qt to do this. Declare a custom signal in your QGraphicsItem. Connect your signal with the setNum or setText slot of the QLabel. emit the signal after you read the mouse position.
4,769,318
4,769,354
C++ - How can I avoid this header from appearing twice?
At: http://www.learncpp.com/cpp-tutorial/110-a-first-look-at-the-preprocessor/ Under Header guards, there are those code snippets: add.h: #include "mymath.h" int add(int x, int y); subtract.h: #include "mymath.h" int subtract(int x, int y); main.cpp: #include "add.h" #include "subtract.h" How can I avoid #include "m...
The lines right below that example explain it. Your mymath.h file should look like this: #ifndef MYMATH_H #define MYMATH_H // your declarations here #endif Every header file should follow this basic format. This allows a header file to be included by any file that needs it (both header and source files), but the a...
4,769,420
4,769,467
C++ sort vector using non-static member function
I have a class called Sorter. It has two public items. int type variable choice member function called compare with a int type return value that accepts two objects as parameter. I tried creating an instance of Sorter while passing choice with a value to the constructor, Then i wanted to use C++ sort function to sort...
If you can change the structure of your Sorter class, you could make it a function object by defining operator () like this: bool Sorter::operator ()(const MyObject &o1, const MyObject &o2) { // return true if o1 < o2 } Then you can just pass an instance of your Sorter class to std::sort.
4,769,454
4,769,475
Setting a C++ Class char* in constructor
I am writing a simple client / server program to mess around with socket programming. I made two classes, one for the client and one for the server. I can run my server with no problems and also my client can connect. But now I am attempting to modify my client so it accepts the hostname and port number in the construc...
If you're going to be coding in C++ may I suggest using std::string instead of char pointers? class Client { public: Client(const string& in_hostname, int in_port) : hostname(in_hostname), port(in_port) { } ~Client() {} private: std::string hostname; int port; }; Edit: In r...
4,769,479
4,769,508
C++ inlining class methods causes undefined reference
I'm getting a compiler error when I try to inline a method of one of my classes. It works when I take away the "inline" keyword. Here's a simplified example: main.cpp: #include "my_class.h" int main() { MyClass c; c.TestMethod(); return 0; } my_class.h: class MyClass { public: void TestMethod(); }; my_cla...
The body of an inline function needs to be in the header so that the compiler can actually substitute it wherever required. See this: How do you tell the compiler to make a member function inline?
4,769,585
4,769,591
Official C++ language and base class library documentations?
I'm newbie on C++. And I have multiple years of C# background. In C#, official language standard and basic class library documentations can be found on MSDN. What's the equivalent for C++? And what's the most basic library of C++? There are many libraries. Boost, STL, ATL, and etc... What's the most basic and I should ...
The equivalent is The ISO C++ Standard. The last revision was published in 2003 (the link is to where you can purchase the PDF of that document). The next revision, what is called C++0x, is slated to be finished sometime around the end of this year (the latest draft can be downloaded freely from the C++ committee web...
4,769,660
4,769,783
Problem trying to detour function with assembly
Just for the fun of it, I am trying to make a simple detouring library that will detour member functions by modifying the vtable of the class to create a detour. I am getting some odd behaviour. Here is the entire program (I am using MSVC++ 2010): fixed It's jmping to the address of the new function correctly, but it ...
Found the problem. Turns out you have to subtract 5 from the address to calculate it correctly, since it's the relative address not from the end of the instruction but from the beginning.
4,769,822
4,769,869
Compilation fails in VS2010 for C++ programs building fine in Linux
My C++ project builds and runs fine on Linux. Now I am trying to compile it in VS2010. I get many errors seemingly from cmath library like the following one. Error 1 error C2061: syntax error : identifier 'acosf' c:\program files\microsoft visual studio 10.0\vc\include\cmath 19 1 MyPROJ Also I get many file o...
lseek and write are unix (posix?) calls that are not part of the C standard. They are available on windows but using the names _lseek and _write not sure about acosf though EDIT: acosf should be available, are you include math.h Edit more: Looking more closely at the original post the error is in cmath which is fine a...
4,769,887
4,769,908
How to declare function prototype that returns std iterator?
So as a class assignment I'm reimplementing std::vector, and I'm having trouble with declaring the prototype for: iterator insert ( iterator position, const T& x ); The template for my iterator class looks like this template<typename T> class VectorIterator : public std::iterator<std::input_iterator_tag, T> The templ...
That function doesn't return a std::iterator; it returns a std::vector<T, Alloc>::iterator. You need to typedef your VectorIterator in your Vector: template <typename T> class Vector { typedef VectorIterator<T> iterator; }; This is the return type of the insert function. Any references to iterator and const_iter...
4,770,049
4,770,064
Is it safe using `$` as an identifier in C/C++?
Is it safe to use $ character as part of identifier in C/C++? Like this, int $a = 10; struct $b; class $c; void $d();
No. The C standard only guarantees the use of uppercase and lowercase English letters, digits, _, and Unicode codepoints specified using \u (hex-quad) or \U (hex-quad) (hex-quad) (with a few exceptions). Specific compilers may allow other characters as an extension; however this is highly nonportable. (ISO/IEC 9899:199...
4,770,061
6,198,732
Is DLIB a good open source library for developing my own machine learning algorithms in C++?
Is DLIB a good open source library for developing my own machine learning algorithms in C++? How about other ones, such as libSVM, SHOGUN?
A good source for information about machine learning open source software is mloss.org, where you can find 20 projects that use C++. Study the descriptions and tags to select one that fits your needs.
4,770,240
4,770,384
C++ code gets strangely skipped with no optimizations. Any ideas why?
I looked for an answer for two days to this with no success. I've never come across this problem before so I'll try my best. Please bear with me. I returned to a C++ project I created over a year ago, which at the time ran without problems. I came across this interesting and incredibly annoying problem the other day as...
short is 16 bits long and its range is -32768 to 32767. So it can never be 40000 or 45000 and compiler eliminated dead code (as it will never be reached).
4,770,304
4,770,332
Hooking API Calls in Current Process?
How do I go about hooking/redirecting a function in a DLL (say, CreateThread from Kernel32.dll) loaded in the current process? (I don't have control over which pieces of code call CreateThread, so it's not like I can just have the code something else instead.) The language doesn't matter much; I'm guessing C/C++ would ...
Check out http://easyhook.codeplex.com/ It's an API Hooking framework. Its open source, very easy to use!
4,770,351
4,770,374
Compiling a specific boost library
I only require a single .lib and .dll but I don't want to go through compiling process of all using bjam.exe How can i do that?
You can use the bcp tool to create just the subset of Boost that you need.
4,770,442
4,770,508
Link error when using lex and yacc output in Visual Studio
I am using this windows version of flex (lex) and bison (yacc) to port my query compiler from linux to Windows. The output files, lex.yy.c, y.tab.c and y.tab.h are getting generated properly. However, I am getting the following link error. Error 29 error LNK2001: unresolved external symbol _yylval G:\Project\lex.yy.obj...
This could happen because you're mixing C++ and C files together in one project. So if you're including y.tab.h into a .cpp file then make sure it has extern "C" { ... } around it. Like this: extern "C" { #include "y.tab.h" } Update: From your comment I understood that y.tab.c is y.tab.cc now. This causes a li...
4,770,468
4,770,538
Displaying Hexadecimal numbers
We would display Hexadecimals in A03Eh format which A=10 & E=14, and A is a nibble. But I have seen another display like this : 0x002314A8 , How can we convert the above number into this format ? what is this format ?
The format 0x is the standard Unix way of representing hexadecimal numbers. I am used to seeing 0x at the beginning and not h at the end. That is the only difference. Like Péter Török said, if you're using C/C++ there are ways to modify what is shown when you print.
4,770,574
4,831,843
How to establish Tcp connection between IOS and windows?
I'm trying to implement tcp connection between my Ipod as client and PC as server. I use QTcpServer to provide a server. What is the best way to realize the connection?
Using CFSocket. An awesome cocoa class has been written to wrap CFSocket for you asynchronously! It supports both UDP and TCP, I am using it myself in an IM application. AsyncSocket on iphone
4,770,636
4,770,644
What does this symbol mean in C++? "~"
If we use ~ before a function like this: ~func();, what does this mean? Thanks.
If it's part of a class definition, it's a destructor for that class, provided the function name is the same as the class name (Otherwise it would be a syntax error). class stuff { stuff(); // constructor for stuff ~stuff(); // destructor for stuff }; It could also be a bit-wise not operator. i.e. int x = ~func();...
4,770,871
4,770,917
What are the advantages of developing applications in C++ as compared to managed languages?
Hi I want to know why people develop library applications and employee management applications in C++ (this application, for example), when clearly the same thing can be done in C# and VB.NET in a much prettier way. Even banking applications are mostly in C++. Is there a good reason why, apart from the fact that compil...
C: 1972 C++: 1979 C#: 2000 Now think of the lifetime of a library, especially in a bank, plus, you get to use the libraries (theoretically) on almost every computersystem in existence (as opposed to C#) You will also still find a lot of COBOL (1960) there.
4,770,918
4,770,945
Converting C++ object file from linux .o to Windows .obj
I'm sorry if this sounds crazy. Is there anyway I can convert .o file that I get from g++ compiler to *obj that is compatible with Visual Studio. This is the reason I am considering doing this conversion.
No, there is no way, especially as the .o file was not compiled with a cross-compiler on Linux. In any case, this sounds like a very strange approach to solve a single linking error.
4,770,953
4,771,290
CUDA: embedded for loop kernel
I have some code that I want to make into a cuda kernel. Behold: for (r = Y; r < Y + H; r+=2) { ch1RowSum = ch2RowSum = ch3RowSum = 0; for (c = X; c < X + W; c+=2) { chan1Value = //some calc'd value chan3Value = //some calc'd value chan...
Let's suppose you have a kernel that computes the three values. Each thread in your configuration will compute the three values for each (r,c) pair. __global__ value_kernel(Y, H, X, W) { r = blockIdx.x + Y; c = threadIdx.x + W; chan1value = ... chan2value = ... chan3value = ... } I don't believe y...
4,770,968
4,771,101
Storing function pointer in std::function
I'm trying to write a C++0x wrapper around dlopen()/dlsym() to dynamically load functions from shared objects: class DynamicLoader { public: DynamicLoader(std::string const& filename); template<class Signature> std::function<Signature> load(std::string const& functionName); private: void *itsLi...
try this: static_cast<Signature*>() seems works in VC10 complete test: #include <functional> void test() {} template <typename Signature> std::function<Signature> cast(void* f) { return static_cast<Signature*>(f); } int main() { std::function<void()> f = cast<void()>(&test); return 0; }
4,771,368
4,771,383
Imparting expert knowledge for predicting branch statements in C# or C++
I know some CPUs attempt to predict branch statements when deciding what code to pre-fetch, I was wondering if there was a way to help or hard code those branch predictions in C# (or C++). An example would be an error checking if statement which I know will return false 99.9999999% of the time, I would like to tell the...
To the best of my knowledge there is no cross-platform solution to this problem. I would expect that C# VM would do some sort of runtime analysis to optimize for these sorts of predictions, though I don't know this for a fact. For C/C++, there are a few platform-specific tools to help optimize this. You can usually f...
4,771,398
4,771,406
When to use overloaded assignment operator?
Possible Duplicate: What is The Rule of Three? When you require to define to your own assignment operator?
Generally, you'll need to define your own assignment operator under the same circumstances when you need to define your own copy constructor - i.e. when a default copy won't cut it. This happens in cases when your object manages dynamically allocated memory or other resources which need to be specially copied. For e...
4,771,417
4,771,534
How to get the signature of a C++ bind(...) expression
I am trying to write a metafunction named signature_of which, given the type of a function (pointer), functor, or lambda, returns its signature. Here's what I have so far: #include <boost/mpl/pop_front.hpp> #include <boost/mpl/push_front.hpp> #include <boost/function_types/is_member_function_pointer.hpp> #include <boos...
You've got more problems than the fact that a binder's operator() is templated, it also has an arbitrary count of parameters. Remember that you're supposed to be able to invoke the result of bind with any number of extra arguments. For example: int f(int); auto bound = boost::bind(f, _2); bound may now be called wi...
4,771,445
4,771,486
Efficient implementation of a Z-Buffer
I am currently implementing my own renderer using the Z-Buffer algorithm. Once I have done the necessary calculations (read: My Z-Buffer is filled with the correct values) I use SDL to colour in the necessary pixels. I'm using an HWSurface for this. My question is, how can I render this as fast as possible? With this ...
Software implementations are incredibly slow- that is, WARP renders Crysis on an i7 hexacore at a tenth the FPS that an 8800GT does. You won't find any competitive performance in a software-implemented Z-buffer. A Z-buffer is not a particularly complex algorithm and it's pretty unlikely that you'll find one implementat...
4,771,533
4,771,579
Low latency capture of button click
I want to have a physical button (not a software button) that I put into my custom rig. When I click this button, I want to receive a signal in my software e.g. by registering my callback function. The goal is to have a panel of physical button that when click will perform certain tasks in the software. The interrupt (...
You can use the device driver dev kit to write an hardware interrupt handling object Connectivity wise - easiest way is a parrallel port - ideally a real one on a card not a USB adaptor, otherwise somethign like a an arduino talking to thePC as a serial port over the USB link is easiest. Edit - for 50 buttons you will ...
4,771,780
4,771,827
C++ Stack Implementation (not working right)
Here's the previous thread where I got help with this same lab. My stack is misbehaving, to say the least, when I add an item to stack, to print out later, it doesn't seem to add right. I always print out plus'(+), not matter if I enter another operand(*,/,+). I am using a stack to convert a, user inputed, infix expres...
Your loop calls front(), but then calls pop_back(). This will always return the first element in the vector, until all elements are popped, since you are never erasing the front element. Your ReturnFront() method should probably be: char ReturnBack(){ return Well.back(); } And then your loop at the end: ...
4,771,867
4,773,883
Adapting checking for member functions existence to function arguments
I've been trying to adapt this solution for enabling the existence of ordinary (non-member) functions. In my case, I have a lot of global string-utility-type functions that take any string type T such that T has has, say, a char const* c_str() const member function. The goal is to eliminate weird compiler error message...
If I understand the question correctly, applying enable_if to f itself like the following will solve the problem: template<class StringType> typename enable_if<has_c_str(StringType),StringType>::type f( StringType const& s ) {....} Hope this helps.
4,772,119
4,772,134
Use c++ libraries at C#
I'm working myself on a project, because performance is important i want to write some part of the code on c++ and want to call c++ codes from C#. I will write c++ library and want to write a C# wrapper, how can i do it? Have you any suggestion where i should begin to study? [any website, any link, any book] Thanks !
Example: Windows: [DllImport("User32.dll")] public static extern void SetWindowText(int h, String s); Linux: [System.Runtime.InteropServices.DllImport("/root/Desktop/q3noclient/libnoclient.so")] static extern int DisconnectClient (string strServerIP, int iServerPort, string strClientIP, int iClientPort); C#:...
4,772,146
4,772,196
C++: More precise timing intervals
I need to periodically do a particular task and am currently using nanosleep. The task needs to be run every second or every 10 seconds. Is there a better way to do this than: while(true) { doTask(); sleep(); } Walter
One of the options could be to create a thread that will do the task with specified timeout.
4,772,148
4,772,160
Compile error with EasyBMP library
I'm trying to write a program that can rotate a given BMP file 180 degrees and create a new BMP file with the rotated image. I'm using the EasyBMP library. However, every time I try to compile, I get these warnings: EasyBMP Warning: Attempted to access non-existent pixel (359, 236); Truncating request ...
If should be for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { color = in(x, y); *(out(width - x - 1, height - y - 1)) = *color; } } (Note < instead of <= and - 1 added).
4,772,208
4,772,222
Unhelpful (maybe wrong?) gcc error message
I just spent a couple of hours debugging a compiler error that I could have fixed immediately if the compiler's error message had been more helpful. I've reduced it to a simple example: template <typename T> int f(int); template <typename U> auto g(U x) -> decltype(f(x)); int main() { g(0); } The error is: test....
You are most likely hitting the "extended SFINAE" rules in C++0x; since the call to f(x) is not working within the instantiation of the return type of g (because of the inability to deduce T for the call to f), g has an invalid return type and thus is removed from the overload set silently. This is a feature, despite ...
4,772,219
4,772,257
empty base class optimization
Below is a simple test on ebco, I compiled it on both vc9 and g++. The outputs differ on both compilers. What I want to know is that whether the behavior of vc is conformant. #include <iostream> class empty { }; class empty_one : public empty {}; class empty_two : public empty {}; class non_empty : public empty_...
pe10 == pe11. Can two sub-objects of two objects have the same address? Is this conformant? No, two different objects cannot have same address. If they've, the compiler is not Standard Complaint. By the way, which version of VC++ you're using? I'm using MSVC++2008, and it's output is this: I think, you meant pe...
4,772,303
4,772,319
memcpy and C++ class templates - how to use it?
So.. How can we call something like memcpy(dataCopy, data, length); to copy abstract data T? Or if abstract T is not safe lets say we know that T is a POD (plain old data, basically a C struct) - is it possible to copy it?
Do you mean working for some arbitrary C++ type T? Unless you know that T is a POD (plain old data, basically a C struct) type, it is not safe to copy objects of type T with memcpy. That would prevent T's copy constructor from running, for example, which might lead to an incorrect copy (trying to memcpy an std::vecto...
4,772,325
4,772,526
Best way to compare std::strings
What is the best way to compare std::strings? The obvious way would be with if/else: std::string input; std::cin >> input; if ( input == "blahblahblah" ) { // do something. } else if ( input == "blahblah" ) { // do something else. } else if ( input == "blah" ) { // do something else yet. } // etc. etc. ...
Here's an example using std::map. #include <map> #include <string> #include <iostream> #include <utility> void first() { std::cout << "first\n"; } void second() { std::cout << "second\n"; } void third() { std::cout << "third\n"; } int main() { typedef void(*StringFunc)(); std::map<std::string, StringFunc...
4,772,555
4,820,888
Where can I find a C++ csound tutorial?
I have just discovered csound and installed its C++ bindings. The API is documented here (after a usual installation on Linux): /usr/share/doc/libcsound64-doc/html/index.html However, what I am missing is a good tutorial to get me started with the API.
Here's an introduction to C API (pdf), which is practically the same as the C++ API. There are also a few examples in the Csound source code in the examples and frontends folders.
4,772,646
4,772,655
Order of Function arguments in C++
I was reading "Bjarne Stroustrup's C++ Style and Technique" FAQ where he mentioned about this FAQ What's the value of i++ + i++? In this he has mentioned "...the order of evaluation of function arguments are undefined." when he is refering to f(v[i],i++); example. I am aware of that the order of evaluation of function ...
The order of evaluation of function arguments is unspecified but the behaviour of the expression is undefined. Bjarne has just got it wrong. :-) Check out this thread to understand the difference between Unspecified Behaviour and Undefined Behaviour. I once asked Bjarne the difference between unspecified and undefined ...
4,772,680
4,772,923
Why the difference between int a[5] = {0} and int a[5]={1} (Missing Feature)
When we initialize an array like this int a[5] = {0}, the compiler makes all 5 elements 0. That is really good, compact-initialization and useful feature. But I wonder why the compiler doesn't initialize int a[5]={1} similarly? Why does it not make all 5 elements 1? Why the Standard doesn't mandate it? Would it not be...
I personally find more "logical" (i.e. simple) having a fixed default initializer instead of another rule of repeating last one just for arrays. That may appear "practical" (i.e. useful) but it's IMO more logically complex. That said however I think you're making a big mistake in trying to apply logic to a language lik...
4,772,729
4,772,863
Working with Box2D/Cocos2D in an external iOS project
I have followed the instructions as per this article and have been working with Cocos2D without much issues. Recently, I tried including the Box2D headers to try some physics like so: #import "Box2D.h" This resulted in a lot of errors where the Box2D.h file could not include the rest of the header files: ../cocos2d-ip...
I don't know if this is immediately obvious to other programmers, but I fixed this by checking the Always Search User Paths setting in the target settings. Hope it helps someone else.
4,772,745
4,772,767
How would I go about creating a file compressor similar to ZIP archives in a language like C/C++?
So I was thinking of how a .zip archive is structured and then I thought, how could I create my own archive format.
You would want to know what you want to compress. E.G. zip works great for many things, but not so well for audio files. FLAC works well for audio, but poorly on text files ( provided you could find a way to apply it ) Once you had a compression scheme you would allocate the appropriate metadata so you could later deco...
4,772,752
4,772,754
problem with sizeof operator
As i want to find array size dynamically in function, i used sizeof operator. But i got some unexpected result. here is one demo program to show you, what i want to do. //------------------------------------------------------------------------------------------ #include <iostream> void getSize(int *S1){ int S_siz...
void getSize(int *S1) When you pass an array to this function, it decays to pointer type, so sizeof operator will return the size of pointer. However, you define your function as, template<int N> void getSize(int (&S1)[N]) { //N is the size of array int S_size1 = N; int S_size2 = sizeof(S1)/sizeof(int); //wou...
4,772,802
4,772,842
Using Stacks In C++ for infix and postfix expressions
I'm writing a program that takes user input and uses stacks to convert an infix expression into a postfix expression based on precedence, with operands always going before operators. For example, if a user inputs: (a+b*c) then the program should display: abc*+ so far, I have this: #include <iostream> #include <stack> #...
else if (input == '*'||'/'||'+'||'-' && s.top() >= input) This does not do what you think it does. You need to do else if (input == '*'|| input == '/'|| input == '+'|| input == '-' && s.top() >= input) And this looks like an error too bool prec (char a, char b, char c, char d); That's the syntax for a function prot...
4,772,891
4,772,900
Initialization list std::pair
Is there a way of initializing a std::vector of std::pair<int,int> in the initialization list in a constructor? I have a std::vector<std::pair<int,int> > and I want to initialize a certain number of pairs to (0, 0). For example, I may want to initialize 3 pairs of (0, 0) for a member in a class. How would I go about do...
You can do this by using the std::vector constructor which takes in a size and a default value to use: class MyClass { public: MyClass(); /* ... */ private: std::vector<pair<int, int> > elems; }; MyClass::MyClass() : elems(3, std::make_pair(0, 0)) { /* ... */ }
4,772,932
4,772,941
Pointer addition and element size
At: http://www.fredosaurus.com/notes-cpp/arrayptr/26arraysaspointers.html Under: Pointer addition and element size There is the following code: // Assume sizeof(int) is 4. int b[100]; // b is an array of 100 ints. int* p; // p is a a pointer to an int. p = b; // Assigns address of first element of b. Ie, &b...
(I assume that you mean "1" in the last line, not "p") Pointer arithmetic in both C and C++ is a logical addition, not a numeric addition. Adding one to a pointer means "produce a pointer to the object that comes in memory right after this one," which means that the compiler automatically scales up whatever you're inc...
4,773,157
4,773,660
passing multidimensional arrays to function when the dimension size is not clear
I have a function in my class which should get a multi-dimensional array. the problem is that the value of these dimensions is calculated in the class, using another function and is stored in some public variables. so all the other functions within the class can read the value stored in these vars. the definition of fu...
The kind of arrays in you are using here (C-style) are not really designed to be used with dynamic sizes, though you can use new to allocate them that way. One solution for function calling is do use a double *** and three size_t parameters for dimensions to pass into a function, but that still requires you to declare...
4,773,211
4,773,363
Given a list of coordinates in the first quadrant, calculate how many right triangles can be formed which have one side parallel to x-axis
Given a list of coordinates in the first quadrant, calculate how many right triangles can be formed from these which have one side parallel to x-axis and one side parallel to y-axis. Recently I took part in a programming competition, more specifically INOI(Indian National Olympiad n Informatics) and this was the first ...
Lets numX[i] = how many points have i as their X coordinate and numY[i] = how many points have i as their Y coordinate. We will count how many triangles with the required property exist for a certain point p. Without loss of generality, we can assume that p is the point where the triangles make their right angle. For t...
4,773,265
5,444,560
ACE Reactor quits on interrupted system call
I have an ACE reactor that accepts socket connections and listens for the incoming data on those connections. The reactor runs in a dedicated thread. This is the thread's entry function: int TcpServer::svc() { LogDebug("The TCP server on %i is running", mLocalAddr.get_port_number()); // The current thread will...
Check how Reactor is constructed. ACE_Reactor::open() cal, takes "restart" parameter (default = false) that tells it to restart handle_events method automatically after interruption.
4,773,334
4,773,450
C++ - pointer function parameter
I asked a question here: C++ - class issue What I'm still not getting is the pointer parameter here: void setInfo(char *strName,int id,double wage) Where it is called by: abder.setInfo("Abder-Rahman",123,400); I know that the name of the array is a pointer. But, why should we have to have a pointer data type? Cannot ...
For reference, from the C++03 standard, § 8.3.5 3: After determining the type of each parameter, any parameter of type “array of T” or “function returning T” is adjusted to be “pointer to T” or “pointer to function returning T,” respectively. Furthermore, an array declared with [] is an incomplete object type (§ 8.3....
4,773,359
4,773,522
Right design pattern to deal with polymorphic collections of objects
Suppose I have the following classes: class BaseObject { public: virtual int getSomeCommonProperty(); }; class Object1: public BaseObject { public: virtual int getSomeCommonProperty(); // optional int getSomeSpecificProperty(); }; class BaseCollection { public: virtual voi...
I think you should go for option 1 but use a static cast instead. After all the derived collection knows the type of the member variable for sure. This answer explains it very well.
4,773,546
4,773,594
convert shared_ptr to auto_ptr?
I need to obtain auto_ptr from shared_ptr in my code. I can do reverse operation - convert auto_ptr to shared_ptr as shared_ptr has such constructor: template<class Y> explicit shared_ptr(std::auto_ptr<Y> & r); Can I convert shared_ptr to auto_ptr? Or it is impossible by design?
A shared pointer can be shared by many things, you can't just take it from them all somehow. This is elaborated by Artyom and peoro. One approach is to make a temporary auto_ptr, and release it from handling the pointer at the end of the scope. dalle outlines a first approach, but this suffers from lack of exception-sa...
4,773,592
4,773,613
Handcoding Windows GUI in C++ without IDE
Hey, I've seen some questions on this topic but most of them only try to point out if its better to or not to use an IDE for creating a GUI, well thats not my question. I want to use some IDE like Qt for writing bigger programs in the future, but at the moment i am new to c++ and especially GUIs, and want to learn how ...
Here's a tutorial for creating a GUI that doesn't require any library, as it targets the native Windows API: Creating Win32-Based Applications (C++): http://msdn.microsoft.com/en-us/library/bb384843.aspx (As user Nubok wrote in a comment above, programming against the Win32 API is quite strenuous. But you will learn ...
4,773,603
4,774,809
High precision arithmetric in Python and/or C/C++?
Abstract: Which Python package or C-Library is the best option for very high precision arithmetic operations? I have some functions which convert fractional days (0.0-0.99999..) to a human-readible format (hours, minutes, seconds; but more importantly: milliseconds, microsecond, nanoseconds). Conversion is done by thes...
The difference is due to a bug in your code, not due to any accuracy issue. The line output += self.nanosecond * (d(8.64) * d(10)**d(-9)) should be something like output += self.nanosecond / d(86400000000000) Furthermore, it is a Bad Idea to use floating point literals in your code and convert them to Decimal. This...
4,773,807
4,773,960
Searching in a sorted and rotated array
While preparing for an interview I stumbled upon this interesting question: You've been given an array that is sorted and then rotated. For example: Let arr = [1,2,3,4,5], which is sorted Rotate it twice to the right to give [4,5,1,2,3]. Now how best can one search in this sorted + rotated array? One can unrotate t...
This can be done in O(logN) using a slightly modified binary search. The interesting property of a sorted + rotated array is that when you divide it into two halves, atleast one of the two halves will always be sorted. Let input array arr = [4,5,6,7,8,9,1,2,3] number of elements = 9 mid index = (0+8)/2 = 4 [4,5,6,7,8...
4,773,849
4,773,863
Is it possible to delete C POD using delete in C++?
Having structs like struct ifoo_version_42 { int x, y, z; char *imageData; }; where imageData is something like imageData = new char[50000]; Can we perform something like: template< typename T > void del( T a ) // we promise to use this only on C Plain Old data structs=) { delete a; } on this structure an w...
Deleting the struct does not recursively delete any pointers in it, and hence doesn't free the array of char pointed to by imageData. I'm also a bit confused by your use of delete[]. You can free an array (allocated with new[]) using delete[], or free a single object (allocated with new) using delete. You can't mix the...
4,774,092
4,774,111
how can I get the IPs list reffering to an FQDN
In my C++ linux application how can I get the IPs list reffering to an FQDN? (static IPs + dynamic IPs) 10x
There is no principal difference between retrieving the mapping for a local and a fully qualified domain name. Therefore, you can call the getaddrinfo as you would with any other domain name. Note that there is no way to get the list of all IP addresses associated to a domain name because DNS servers are free to advert...
4,774,150
4,774,269
C++ - Strange output
Following the example at the external C++ learning resource that I'm reading. Which is as follows: #include <iostream> #include <cstring> class MyString { private: char *m_pchString; int m_nLength; public: MyString(const char *pchString="") { //find the length of the string //plus "1" for a terminator m_nLength=strlen...
The code you posted here is different from that in the tutorial. It introduces at least two errors: m_pchString=new char(m_nLength); This should be: m_pchString=new char[m_nLength]; The first one allocates a buffer for one character and initializes it with m_nLength. Another error: delete m_pchString; It should be: ...
4,774,257
4,774,285
Constructor Foo::Foo receiving a reference to Foo but not copy-constructor
Suppose i have a non-copyable class Foo, and one of its constructors just happens to receive a reference to Foo. class Foo { public: Foo(Foo& parent) {...} private: void operator=(Foo); // disabled ... }; The compiler thinks that this is a copy-constructor, while it does something entirely unrelated to co...
This appears to be an unfortunate ambiguity in the meaning of such a constructor. I think the most straight forward way to disambiguate this is to use a pointer class Frobnicator // provides the frobnication service { public: explicit Frobnicator(Frobnicator *parent): parent(parent) {} protected: virtual void f...