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
963,982
964,037
Should I use return/continue statement instead of if-else?
In C, C++ and C# when using a condition inside a function or loop statement it's possible to use a continue or return statement as early as possible and get rid of the else branch of an if-else statement. For example: while( loopCondition ) { if( innerCondition ) { //do some stuff } else { //do ...
The compiler will almost certainly generate the same code. Even if it didn't, the difference will be probably irrelevant. Hence, the relevant argument is certainly how people would read it. Therefore the question is how similar "//do some stuff" and "do other stuff" are. If they are conceptually similar, use if/else. ...
964,139
965,794
Huge Integer JavaScript Library
Is there any JavaScript library that can be used for calculations involving 700+ Digits? Also, how about the same thing in C++?
JavaScript: Leemon Baird's BigInt library. This seems to be popular. It's made specifically for cryptographic uses. My own BigInteger library. Similar to the Java BigInteger class, but all calculations are done in base-10. jsbn. Another BigInteger class similar to Java's. I've never used this one, but the API looks si...
964,249
964,267
Linux Shared Libraries c++
I have a Shared Library wise.so. How I can use it in my programm? Do I need to include headers of that library? I work with Eclipce under Linux. I have set a path to the library using -L and -l. But my function is not visible in the program. Could you explain me how does Shared Library work? Regards. EDIT: I get the f...
You need to include the header file in your application and link against it. Have a look at how to use libraries in shared libraries and Linux howto. If the header file is not in the same directory as your application (which it usually isn't) then you need to tell compiler where to look for it, you use -I/path/to/inclu...
964,396
1,032,054
absolute path... confused (ubuntu)
So in Code::Blocks in Ubuntu (latest). I have a project in which I load a file and read a number from it. #include <fstream> using namespace std; int main(){ ifstream in("data/file.t"); int n;in>>n; } now with a cout<<n it shows -1203926 (and other random numbers) though the number in the file is 0. data is wh...
After using the absolute path I found the mistake. In codeblocks you can enter the working directory (that in wich it will launch the program) and I accidentally put a . in there.
964,719
965,872
WaitForSingleObject( )
I have got myself stuck into a really amazing issue here.The code is like as below. class A { public: A(){ m_event = CreateEvent(NULL, false, false, NULL); // create an event with initial value as non-signalled m_thread = _beginthread(StaticThreadEntry, 0, this); // create a thread...
The problem is your use of the _beginthread API. You cannot use the handle returned from this function with the Win32 wait functions. You should use _beginthreadex or CreateThread. From MSDN: If successful, each of these functions returns a handle to the newly created thread; however, if the newly created thread ex...
965,093
3,394,305
Selectively disable GCC warnings for only part of a translation unit
What's the closest GCC equivalent to this MSVC preprocessor code? #pragma warning( push ) // Save the current warning state. #pragma warning( disable : 4723 ) // C4723: potential divide by 0 // Code which would generate warning 4723. #pragma warning( pop ) // Restore warn...
This is possible in GCC since version 4.6, or around June 2010 in the trunk. Here's an example: #pragma GCC diagnostic push #pragma GCC diagnostic error "-Wuninitialized" foo(a); /* error is given for this one */ #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wuninitialized" foo(b); ...
965,316
965,368
How can Unix pipes be used between main process and thread?
I am trying to channel data via pipes whenever a signal arrives from a thread to the main process. Is this possible? How can this be done? The problem: A child thread reads data and puts it into a queue. Main application does its own stuff, however, when data is available on the queue, it should be notified by the th...
Yes its possible through pipes. Step one call pipe to get a pipe: #include <unistd.h> int main(...) { int fileDescriptors[2]; pipe(fileDescriptors); Step 2 pass the fileDescriptors[0] to the main process, and fileDescriptors1 to the thread. In Main you wait for the pipe to be written to to by reading ...
965,401
965,461
C++ memory management and vectors
I'm getting very confused with memory management in relation to vectors and could do with some basic concepts explaining. I have a program that uses big vectors. I created the vectors with the new operator and release them at the end of the program with delete to get the memory back. My question is, if the program cras...
I suspect your questions are about std::vector< T > (as opposed to an array T[]). When your application crashes or gets aborted for whatever reason, the OS reclaims the memory. If not you are using a truly rare OS and have discovered a bug. You need to distinguish between the memory used by the vector itself and the m...
965,725
965,873
Large file support in C++
64bit file API is different on each platform. in windows: _fseeki64 in linux: fseeko in freebsd: yet another similar call ... How can I most effectively make it more convenient and portable? Are there any useful examples?
Most POSIX-based platforms support the "_FILE_OFFSET_BITS" preprocessor symbol. Setting it to 64 will cause the off_t type to be 64 bits instead of 32, and file manipulation functions like lseek() will automatically support the 64 bit offset through some preprocessor magic. From a compile-time point of view adding 64...
966,520
966,732
Is there a way to extract a custom request header with cgicc
I am using Cgicc , which has some methods to extract specific request headers, e.g. getUserAgent would return "User-Agent" header. Is there a generic method that can return an arbitrary header value, e.g. something like getHeaderValue("x-my-header"); Is there a way to do this using cgicc? and if cannot be done with c...
No, cgicc does not support this direcly. However, it is just a wrapper around CGI. http://en.wikipedia.org/wiki/Common_Gateway_Interface and it uses "getenv" in CgiInput class to extract all information provided by the web server. So if the client send some header that is not supported directly by CgiCC but does suppor...
966,541
966,548
C++ template with map allocator problem
I define a template function which loads a map from a CSV file: template <class T> bool loadCSV (QString filename, map<T,int> &mapping){ // function here } I then try to use it: map<int, int> bw; loadCSV<int>((const QString)"mycsv.csv",&bw); But get htis compile time error: error: no matching function for call to...
Drop the ampersand, you don't want to pass a pointer to the map (notice the asterisk at the end of the error message). Also, you don't have to explicitly cast the string literal. Moreover, the compiler should be able to deduce the template argument automatically. loadCSV("mycsv.csv", bw);
966,544
966,549
I get "no member function declared in class" error on my copy constructor when I compile a templated class
I am using C++ and I am trying to create a templated class (a Stack). I would like to define the copy constructor and the assignment operator. There are defined in the header and then I implement them in the cpp file. Here are the problems I get: - For the copy constructor: prototype for ‘Stack::Stack(const Stack&)...
You can't compile templates into separate compilation units. In short, all the template code has to all be in one header. This is likely whats causing your problem. The reason is that templates don't define true classes. Templates specify how code can be generated. So when you make a Stack<int> myStack; The compiler...
966,605
966,793
Program Deployment Failing
The project my team has been working on has reached a point where we need to deploy it to computers without the development environment (Visual Studio 2005) installed on them. We fixed the dependency issues we had at first, but we're still having issues. Now, once the installer is finished, our project gets stuck somew...
Is it possible the hang occurs while some global variable is initialized? That happens before WinMain, and from a global variable's constructor any code could be run. Also, take a look at the busy thread's stack using Process Explorer (make sure you deploy the PBD in order to get a meaningful stack trace). The stack tr...
966,688
1,022,121
Show window in Qt without stealing focus
I'm using the Qt library to show a slideshow on the second monitor when the user isn't using the second monitor. An example is the user playing a game in the first monitor and showing the slideshow in the second monitor. The problem is that when I open a new window in Qt, it automatically steals the focus from the prev...
It took me a while to find it but I found it: setAttribute(Qt::WA_ShowWithoutActivating); This forces the window not to activate. Even with the Qt::WindowStaysOnTopHint flag
966,757
966,768
Is there a way to "delete" a pure virtual function?
I have an abstract class with a couple pure virtual functions, and one of the classes I derive from it does not use one of the pure virtual functions: class derivative: public base { public: int somevariable; void somefunction(); }; anyways, when I try to compile it, I get an error (apparently, a class is stil...
If your derived class doesn't "use" the base class pure virtual function, then either the derived class should not be derived from the base, or the PVF should not be there. In either case, your design is at fault and needs to be re-thought. And no, there is no way of deleting a PVF.
966,905
966,924
Stuck on C++ template - deriving from std::map
I'm going to extend the existing std::map class and add a new function to it: template<typename key_type, typename value_type> class CleanableMap : public Cleanable, public std::map<key_type, value_type> { CleanableMap(const CleanableMap& in); //not implemented CleanableMap& operator=(const CleanableMap& in); ...
Adding onto Neil's answer. One concrete reason you should not be deriving from std::map is that it does not have a virtual destructor. This means you simply cannot guarantee any resources you allocate as a part of your map will be freed during the destruction of your implementation via a std::map pointer. std::map...
966,960
966,986
What does -fPIC mean when building a shared library?
I know the '-fPIC' option has something to do with resolving addresses and independence between individual modules, but I'm not sure what it really means. Can you explain?
PIC stands for Position Independent Code. To quote man gcc: If supported for the target machine, emit position-independent code, suitable for dynamic linking and avoiding any limit on the size of the global offset table. This option makes a difference on AArch64, m68k, PowerPC and SPARC. Use this when building shared...
967,141
967,627
Portable way to "fork()" in Qt4 application?
Say, I need to run a bunch of code that is prone to crash so I need to run it on a different process. Typically I'd do it like this: pid = fork(); if (pid == -1) { std::cout << "Cant Spawn New Thread"; exit(0); } else if (pid == 0) { std::cout << "Im a child that will crash\n"; char *foo = (char *...
Windows flat-out doesn't have fork() in any publicly consumable way, so there's no Qt call to emulate it; you'll need to do something like start yourself with special command-line params or something.
967,219
1,796,379
Adding and removing items without invalidating iterators
I have an object that has a list of 'observers'. These observers get notified of things, and they might respond to this change by adding or removing themselves or other observers from the object. I want a robust, and not unnecessarily slow, way to support this. class Thing { public: class Observer { public: ...
The sane way to manage this chaos is to have a flag so the remove code knows whether it's iterating the observers. In the remove, if the code is in an iteration, then the pointer is set to null rather than removed. The flag is set to a third state to indicate that this has happened. The observers must be iterated with...
967,352
967,363
Why can't I access a protected member from an instance of a derived class?
I haven't done C++ in a while and can't figure out why following doesn't work: class A { protected: int num; }; class B : public A { }; main () { B * bclass = new B (); bclass->num = 1; } Compiling this produces: error C2248: 'A::num' : cannot access protected member declared in class 'A' Shouldn't protecte...
yes protected members are accessible by derived classes but you are accessing it in the main() function, which is outside the hierarchy. If you declare a method in the class B and access num it will be fine.
967,538
967,555
C++ Member Functions vs Free Functions
I keep on getting confused about this design decision a lot of the time when I'm writing programs, but I'm not 100% sure when I should make a function to be a member function of a class, when to leave it as a normal function in which other source files can call the function when the function declaration is exposed in a...
The Interface Principle by Herb Sutter For a class X, all functions, including free functions, that both (a) "mention" X, and (b) are "supplied with" X are logically part of X, because they form part of the interface of X. For in depth discussion read Namespaces and the Interface Principle by Herb Sutter. EDIT Actually...
967,930
967,947
Creating program libraries in Windows and LINUX [C++]
I am planning to use libraries in my C++ program. Development is happening on Linux but application is designed to compile on both Linux and Windows. I understand direct equivalent for shared libraries(.so) in windows is DLL, right? In Linux using g++, I can create shared library using -fPIC and -shared flags. AFAIK, ...
We specify __declspec(dllexport) for class: #define EXPORT_XX __declspec(dllexport) class EXPORT_XX A { }; You can then check for platform and only define the macro on windows. E.g.: #ifdef WIN32 #define EXPORT_XX __declspec(dllexport) #else #define EXPORT_XX #endif We mostly build static libraries so there might be...
968,001
968,112
determine size of array if passed to function
Is it possible to determine the size of an array if it was passed to another function (size isn't passed)? The array is initialized like int array[] = { XXX } .. I understand that it's not possible to do sizeof since it will return the size of the pointer .. Reason I ask is because I need to run a for loop inside the o...
The other answers overlook one feature of c++. You can pass arrays by reference, and use templates: template <typename T, int N> void func(T (&a) [N]) { for (int i = 0; i < N; ++i) a[i] = T(); // reset all elements } then you can do this: int x[10]; func(x); but note, this only works for arrays, not pointers. How...
968,177
968,213
Sending string data between threads (Win32)
This is a fairly straightforward question, I'm basically looking for a 'best practice' approach to what I'm trying to do. I have a Win32 GUI application which starts up a worker thread to do a bunch of blocking calls. I want this thread to send string messages back to the GUI so they can be displayed to the user. Curre...
WM_COPYDATA would work fine, but I think it's better to simply define your own private window message. Allocate the string on the worker thread and free it on the GUI thread when you're done. Use PostMessage instead of SendMessage so that you don't block your worker unnecessarily.
968,324
968,355
How to run regasm.exe from a C++ program?
I want to write a program which runs regasm.exe to create a tlb file programatically. How can I do this?? Ur help is greatly appreciated... Thanks in advance.
You have to use the CreateProcess() function to run the command line like "fullPathToRegasm /somekeys filename". The main problem is to detect the regasm location - use GetCORSystemDirectory() function for that. First use first LoadLibrary() to load the mscoree.dll, then call GetProcAddress() to locate the GetCORSystem...
968,435
968,460
What could cause a deterministic process to generate floating point errors
Having already read this question I'm reasonably certain that a given process using floating point arithmatic with the same input (on the same hardware, compiled with the same compiler) should be deterministic. I'm looking at a case where this isn't true and trying to determine what could have caused this. I've compile...
In almost any situation where there's a fast mode and a safe mode, you'll find a trade-off of some sort. Otherwise everything would run in fast-safe mode :-). And, if you're getting different results with the same input, your process is not deterministic, no matter how much you believe it to be (in spite of the empiric...
968,602
968,667
Error C2678 after migrating C++ code from VC6 to VS2008 - no operator found which takes a left-hand operand of type 'type'
This piece of code compiles file in VC6 but in VS 2008 it gives an error. Can anyone tell me why? I guess it is because you can no longer compare a pointer to NULL (which is a typedef for 0). If that is the case, how do I do this comparison in VC9? for ( std::vector<aCattrBase*>::iterator iT = attrLst.begin(); iT < att...
The type for 'std::vector::iterator' is not necessarily a pointer type so you can not compare it to NULL. In your old compiler it just happened to be a pointer and so your code compiled. But you just got lucky (as shown when you moved the code to a different compiler). The only test on iterator you have is to compare i...
968,621
975,949
Dynamic SQL vs Static SQL
In our current codebase we are using MFC db classes to connect to DB2. This is all old code that has been passed onto us by another development team, so we know some of the history but not all. Most of the Code abstracts away the creation of SQL queries through functions such as Update() and Insert() that prepend somet...
The ATL OLE DB consumer database classes are absolutely the way to go. Beyond the risks of injection (mentioned by Skurmedel), piles of string-concatenated queries will become impossible to maintain very quickly. While the ATL classes can be initially tedious, they provide the benefit of strong-typed and named columns,...
968,725
968,740
change variable name with a loop
Is there a way without using arrays to write the following with a loop: cout<<"This variable c1 ="c1 cout<<"This variable c2 ="c2 cout<<"This variable c3 ="c3 for(i=1,i<8,i++) cout<<"This variable c%d =",i<<**????**<< This is obviously not what I Need to be done but is the easiest example I could think of with the sa...
If I understand correctly, you are trying to create variable names dynamically. AFAIK this is not possible with C++.
968,945
969,005
Sending SMS with delivery message
How can i write code for send SMS with delivery message in Windows Mobile? please guide me with C# or C++ code. I want to use SmsSendMessage API in this code because this API have more features.
You could use SmsSendMessage to send the message and use SmsGetMessageStatus to get the status report of the sent SMS. This is all C++ code, but you can pinvoke it as well.
969,232
969,374
Why does virtual assignment behave differently than other virtual functions of the same signature?
While playing with implementing a virtual assignment operator I have ended with a funny behavior. It is not a compiler glitch, since g++ 4.1, 4.3 and VS 2005 share the same behavior. Basically, the virtual operator= behaves differently than any other virtual function with respect to the code that is actually being exec...
Here's how it goes: If I change [1] to a = *((Base*)&b); then things work the way you expect. There's an automatically generated assignment operator in Derived that looks like this: Derived& operator=(Derived const & that) { Base::operator=(that); // rewrite all Derived members by using their assignment operat...
969,394
969,409
How to split long lines of code in c++?
I need to make sure none of the lines in my code exceeds a a certain length. Normally I separate lines where there's a comma or another suitable break. How can I separate this line into 2? cout<<"Error:This is a really long error message that exceeds the maximum permitted length.\n"; If I just press enter somewhere in...
Two options: cout << "Error:This is a really long " << "error message that exceeds " << "the maximum permitted length.\n"; Or: cout << "Error:This is a really long " "error message that exceeds " "the maximum permitted length.\n"; The second one is more efficient.
969,496
969,537
Access Iterator in BOOST_FOREACH loop
I have a BOOST_FOREACH loop to iterate over a list. Unfortunately, I also need to cache an iterator to a particular item. typedef List::iterator savedIterator; BOOST_FOREACH(Item &item, list) { // stuff... if (condition) savedIterator = &item; // this won't work // do more stuff... } Obviously I can do th...
This is not possible, as you do not have access to an iterator pointing to the current item inside the loop. You could fetch an iterator from the list somehow using the current items data but I don't know if this is a good idea to follow, also performance-wise. I'd suggest you use the solution you already proposed your...
969,939
969,957
Force instantiation of objects with gcc
In the following code, gcc does not instantiate the NSP::Admin and NSP::Server objects. It just skips them. int main(int argc, char **argv) { // Here we bootstrap google logging // we also install the signal handler google::InitGoogleLogging(argv[0]); google::InstallFailureSignalHandler(); // now we parse the...
It does not instantiate them because NSP::Admin admin(); does not create any objects. Instead it is a declaration of a function prototype of a function which returns NSP::Admin object and takes void arguments. It is one of those wierd C++ syntaxes. The second one works because, compiler doesn't get 'confused' thinki...
969,974
970,127
Optional reference member - is it possible?
I have the following class class CItem { public: CItem(CRegistry &Registry) _Registry(Registry) {Registry.Register();} ~CItem() {_Registry.Unregister()}; private: CRegistry &_Registry; } After a while it turns out that not all CItem objects need to be registered so I need a version of...
If you want to keep a single class, just change the attribute into a raw pointer and allow it to be null. As Neil points out, there is a widespread unjustified jihad against raw pointers that is not fully justified. Use a raw pointer and clearly document (comment) that the object holds no ownership of the pointed memor...
970,306
970,379
How come the WaitForDeath() can kill the thread in the sample?
class Thread { public: Thread ( DWORD (WINAPI * pFun) (void* arg), void* pArg) { _handle = CreateThread ( 0, // Security attributes 0, // Stack size pFun, pArg, CREATE_SUSPENDED, &_tid); } ~Thread () { CloseHandle (_handle); } void Resume () { ...
The thread is not killed, it just dies by itself when the function passed as a parameter exits. WaitForSingleObject waits for that termination.
970,382
970,496
"Cannot convert parameter" using boost::variant iterator
I want to create a function that can take different types of iterators which store the same type of object: The first is a std::map containing shared_ptr<Foo> (typedef-ed as FooMap) and the other is a std::list which also contains shared_ptr<Foo> (FooList). I really like the solution MSalters suggested for a similar qu...
I suspect you are missing cases on your do_compare static_visitor. Remeber, the variants might have anything, so you need all possible combinations, like comparing a FooList::const_iterator to a FooMap::const_iterator. It's complaining because the compiler is trying to find some match for that case, and can't convert a...
970,472
970,509
Extracted Interface naming conventions
I'm currently refactoring some code to make it more testable. Specifically, I am extracting the interface of several classes to allow easy creation of test doubles. I'd like to keep the public interface the same to this code, naming the interface after the original class. However this leaves me with the problem of wha...
I would change the name of the interface class. class ServiceClientInterface {}; Then place the concrete implementations in seprate namespaces: namespace MyService { class Client: public ServiceClientInterface {}; } namespace MyServiceTest { class TestClient: public ServiceClientInterface {}; } Or something...
970,498
970,576
Instantiate a new STL vector
I have a situation where I have a pointer to an STL vector. So like vector<MyType*>* myvector; I have to set this pointer to NULL in the constructor and then lazy load when the property is touched. How can I instantiate this to a new instance of a vector?
I have to set this pointer to NULL in the constructor and then lazy load when property is touched. How can I instantiate this to a new instance of a vector? I'm not sure I understand you all the way. Why not simply leave the vector empty, and set a Boolean that says whether the property was loaded or not? Alternative...
970,753
970,789
Passing data from C++ to PHP
I need to pass a value from PHP to C++. I think I can do with PHP's passthru() function. Then I want C++ to do something to that value and return the result to PHP. This is the bit I can't work out, does anyone know how to pass data from C++ to PHP? I'd rather not use an intermediate file as I am thinking this will slo...
You could have your c++ app send its output to stdout, then call it from PHP with backticks, e.g. $output=`myapp $myinputparams`;
971,409
971,455
Unit testing , approval testing and datafiles
(Leaving aside hair-splitting about if this is integration-testing or unit-testing.) I would rather first test at the large scale. If my app writes a VRML file that is the same as the reference one then the VRML exporter works, I don't then have to run unit tests on every single statement in the code. I would also lik...
Have a look at Approval Tests, written by a couple of friends of mine. Not C++, but it's the general idea of what you're after, also known as Golden Master tests. Good stuff, whether it's unit tests or not.
971,478
971,515
C++ SQL database library comparison
I am starting development on a medium-scale C++ project that has to work with a Microsoft SQL Server database. I have done database work before using .NET technologies but I don't find using a .NET approach to be appropriate this time. I would like to get some feedback concerning the various free (as in GPL, LGPL, Boos...
I can highly recommend OTL. Not only does it support all major DBs, it's also very STL-ish and is generally written according to to proper C++ methodology (IMO). It worked for me just fine on VC8 (I used the MySQL ODBC connector). Moreover, it's a one-header library. So there's no linkage issues or anything. Just inclu...
971,528
1,012,124
FileSystemWatcher does not fire when using C++ std::ofstream
I'm trying to add a log monitor to an in-house test utility for a windows service I'm working on. The service is written in C++ (win32) and the utility is in .NET (C#) The log monitor works for many other C++ apps I've written, but not for my service. The only main difference I can see is that the other apps use the o...
I really wanted to be able to pick one of the previous answers as "the answer", but all of them contributed to me being able to figure out the final solution. After a great deal of trial and error with each solution, I found that I could get it to work (without modifying the C++ logging code) by setting NotifyFilter to...
971,645
971,760
What are my options for C++ DLL to call a C# DLL?
I have a C++ DLL that needs to call a function (pass a value, return a value) in a C# class library. Is my only option to give the C# DLL a COM interface and call it from C++ with IDispatch? Is this the best method?
Couple of options available for you here Use a mixed mode C++/CLI assembly as a bridge between the C++ and C# DLL Use the a COM bridge by exposing several of the key C# types as COM objects. This can then be accessed via the C++ code by normal COM semantics
971,668
972,315
Pointer-to-Exception Clean-Up
We all know that throwing pointers to exception is bad: try { ... throw new MyExceptionClass(); } catch (MyExceptionClass* e) { ... } What's your approach to cleaning the catch targets up in legacy code? I figure that I can fix the first part by making operator new private: class MyExceptionClass { public:...
If I understand you correctly, you want to turn a bad practice into a compilation error. By making the exception type non-heap-allocatable, you've managed to make this illegal: throw new MyExceptionClass(); Alas, the next part can't be done like you want it. There's no way to make the catch block illegal. Although, ...
971,726
972,908
Can the signal system call be used with C++ static members of the class?
Is the following supported across *nix platforms? #include <cstdio> #include <sys/types.h> #include <signal.h> #include <unistd.h> class SignalProcessor { public: static void OnMySignal(int sig_num) { printf("Caught %d signal\n", sig_num); fflush(stdout); ...
Technically no you can't. You just happen to be getting lucky that your compiler is using the same calling convention that it uses for 'C' functions. As the C++ ABI is not defined the next version of the compiler is free to use a completely different calling convention and this will mess with your code with no warning ...
971,804
971,821
create a control programmatically using MFC
I just wonder how to do it. I write : CEdit m_wndEdit; and in the button event handler (dialog app), I write : m_wndEdit.Create(//with params); but I still don't see the control appear in the UI. I actually wrote this in the button handler : CWnd* pWnd = GetDlgItem(IDC_LIST1); CRect rect; pWnd->GetClientRect(&rect)...
Check with the following set of flags as the example mentioned in MSDN: pEdit->Create(ES_MULTILINE | WS_CHILD | WS_VISIBLE | WS_TABSTOP | WS_BORDER | ES_NOHIDESEL | ES_READONLY, rect, this, 105);
971,809
971,829
Trouble using ReadFile() to read a string from a text file
How can I make the code below to read correct text. In my text file has Hello welcome to C++, however at the end of the text, it has a new line. With the code below, my readBuffer always contains extra characters. DWORD byteWritten; int fileSize = 0; //Use CreateFile to check if the file exists or not. HANDLE hFile ...
Either remove the new line character from the file or use _tcsstr for checking the existence of the string "Hello Welcome to C++".
972,128
972,145
Refactoring build system to use Autotools
Over the past couple of days I have been reading into using autotools to build my project instead of the Makefiles I have pieced together over the past couple of months. Unfortunately I have not found an example that gave me enough insight towards how my project structure is currently. I have three libraries that are i...
Here are a few I found that don't look to bad: http://www.lrde.epita.fr/~adl/autotools.html http://www.developingprogrammers.com/index.php/2006/01/05/autotools-tutorial/ http://sources.redhat.com/autobook/ The last one is a free book Good Luck
972,152
972,197
How to create a template function within a class? (C++)
I know it's possible to make a template function: template<typename T> void DoSomeThing(T x){} and it's possible to make a template class: template<typename T> class Object { public: int x; }; but is it possible to make a class not within a template, and then make a function in that class a template? Ie: //I have...
Your guess is the correct one. The only thing you have to remember is that the member function template definition (in addition to the declaration) should be in the header file, not the cpp, though it does not have to be in the body of the class declaration itself.
972,206
972,269
Corba request timeout
I am working on a Corba client for some time. One problem that I run in is that I am not really able to define a timeout configuration. I am using a Mico C++ orb but it seems to be a global problem because I found noone who could describe if there is a Corba defined method to configure a request timeout. Does anyone kn...
The Messaging section of the CORBA spec defines RelativeRequestTimeoutPolicy and RelativeRoundtripTimeoutPolicy for that. You may look at the section named "Programming client timeouts" in http://www.cs.wustl.edu/~schmidt/PDF/C++-report-col19.pdf for more information. I don't have experience with MICO, but it seems tha...
972,511
972,529
View array in Visual Studio debugger?
Is it possible to view an array in the Visual Studio debugger? QuickWatch only shows the first element of the array.
You can try this nice little trick for C++. Take the expression which gives you the array and then append a comma and the number of elements you want to see. Expanding that value will show you elements 0-(N-1) where N is the number you add after the comma. For example if pArray is the array, type pArray,10 in the wat...
972,705
972,738
Is there a way to initialize an array with non-constant variables? (C++)
I am trying to create a class as such: class CLASS { public: //stuff private: int x, y; char array[x][y]; }; Of course, it doesn't work until I change int x, y; to const static int x = 10, y = 10; Which is impractical, because I am trying to read the values of x and y from a file. So is there any way to ...
The compiler need to have the exact size of the class when compiling, you will have to use the new operator to dynamically allocate memory. Switch char array[x][y]; to char** array; and initialize your array in the constructor, and don't forget to delete your array in the destructor. class MyClass { public: MyClass...
972,865
4,173,606
Code metrics and warnings for C++
I have a pretty new code base written in C++. Already I'm starting to see some bad practices creeping into the project (class file with 1000+ lines of code, functions with a lot of parameters, ...). I would like to stop on these right away with some automated tools which can hook into the build and check for poor co...
As with the others I'm not sure of a tool that will judge style. But CCCC will produce numerous metrics that can help you find the trouble spots. Metrics like cyclomatic complexity will give you quantitative evidence where the problem spots are. The downside is that you will have to incorporate these metrics with a st...
972,927
972,971
How to check the status of mail server (SSL, SMTP port 465) in C++
Ping is not working. Telnet is not an option, sending a mail also. Preferably a function from a library that returns true or false. Thanks.
If by working you mean open, you can just connect to the port and see if the socket opens successfully. If you mean that it's accepting valid SMTP over SSL, then you'd need a library that connects and issues a trivial SMTP command like HELO or something. Chilkat has library code and examples for this. Example connect c...
973,000
973,007
What patterns do you use to decouple interfaces and implementation in C++?
One problem in large C++ projects can be build times. There is some class high up in your dependency tree which you would need to work on, but usually you avoid doing so because every build takes a very long time. You don't necessarily want to change its public interface, but maybe you want to change its private member...
The pimpl pattern: In your header file, only declare the public methods and a private pointer (the pimpl-pointer or delegate) to a forward declared implementation class. In your source, declare the implementation class, forward every public method of your public class to the delegate, and construct an instance of your ...
973,146
973,158
How to include header files in GCC search path?
I have the following code in a sample file: #include "SkCanvas.h" #include "SkDevice.h" #include "SkGLCanvas.h" #include "SkGraphics.h" #include "SkImageEncoder.h" #include "SkPaint.h" #include "SkPicture.h" #include "SkStream.h" #include "SkWindow.h" However, this code is located in various folders within /home/me/de...
Try gcc -c -I/home/me/development/skia sample.c.
973,439
973,447
How to set the don't fragment (DF) flag on a socket?
I am trying to set the DF (don't fragment flag) for sending packets using UDP. Looking at the Richard Steven's book Volume 1 Unix Network Programming; The Sockets Networking API, I am unable to find how to set this. I suspect that I would do it with setsockopt() but can't find it in the table on page 193. Please sugges...
You do it with the setsockopt() call, by using the IP_DONTFRAG option: int val = 1; setsockopt(sd, IPPROTO_IP, IP_DONTFRAG, &val, sizeof(val)); Here's a page explaining this in further detail. For Linux, it appears you have to use the IP_MTU_DISCOVER option with the value IP_PMTUDISC_DO (or IP_PMTUDISC_DONT to turn it...
973,939
973,955
How to run regasm.exe from command line other than Visual Studio command prompt?
I want to run regasm.exe from cmd. which is available in c:\windows\Microsoft.net\framework\2.057 I do like this c:\ regasm.exe It gives regasm is not recognized as internal or external command. So I understood that I need to set the path for regasm.exe in environment variable. For which variable do I need to set the p...
In command prompt: SET PATH = "%PATH%;%SystemRoot%\Microsoft.NET\Framework\v2.0.50727"
973,983
974,028
error C2440: 'initializing' : cannot convert from 'std::_Vector_iterator<_Ty,_Alloc>' to 'type *'
I am getting the following error while migrating VC6 code to VS2008. This code works fine in VC6 but gives a compilation error in VC9. I know it is because of a compiler breaking change. What is the problem and how do I fix it? error C2440: 'initializing' : cannot convert from 'std::_Vector_iterator<_Ty,_Alloc>' ...
If it worked before, I am guessing MUX_NOTIFICATION_VECTOR is a typedef typedef std::vector<STRUCT_MUX_NOTIFICATION> MUX_NOTIFICATION_VECTOR; The iterator for a container can often be mistaken with a pointer (because it works the same way) and, in the case of some stl implementations, it can actually be a pointer (it ...
974,250
994,255
Windows Mobile/Pocket PC: How do I change the border color of focused/unfocused CEdit, CListCntl, CButton in MFC or Win32
How do I change the border color of focused/unfocused CEdit, CListCntl, CButton in WinCE/Windows Mobile 5/6 with MFC or Win32 API?
There's this trick I found here to draw a borderless control and then draw the border from its parent. or make a static control slightly bigger than the control just to draw the border. Is there any better Idea? such as making use of Window Clipping Region or something? update: Here is a discussion with an MSFT on the...
974,454
974,468
Game Programming as Hobby, should I use Java or C++
Presently, i am learning Java from the book The Art and Science of Java and following Standford's Programming Methodology Course. I would like to do game programming, but only as a hobby. I was thinking, would Java be a good choice or is C++ the defacto in game programming.
Since you are learning Java i would recommend that you stick to it. If you are only developing games for fun, it won't really matter what language you use.
974,512
974,602
Ignoring source code in the debugger
How can I get the Visual Studio debugger to ignore certain source files? In other words, I would like it to behave as if the functions defined in those files had no debugging info, so that: When stepping into code, it will ignore functions defined in those files (a smart pointer operator-> is an example where this is ...
Here's a tutorial / explanation from an msdn blog.
974,815
974,846
How to save c++ object into a xml file and restore back?
How to save c++ object into a xml file and restore back?
Boost.Serialization and libs11n can both do this. The libs11n manual (available here) has an extensive comparison of the two. As Tobias said, the C++ FAQ has good background information.
974,964
975,011
best practice when returning smart pointers
What is the best practice when returning a smart pointer, for example a boost::shared_ptr? Should I by standard return the smart pointer, or the underlying raw pointer? I come from C# so I tend to always return smart pointers, because it feels right. Like this (skipping const-correctness for shorter code): class X { p...
There is no "right" way. It really depends on the context. You can internally handle memory with a smart pointer and externally give references or raw pointers. After all, the user of your interface doesn't need to know how you manage memory internally. In a synchronous context this is safe and efficient. In an asynchr...
975,028
975,045
Converting argv back to a single string
I'm writing a (Win32 Console) program that wraps another process; it takes parameters as in the following example: runas.exe user notepad foo.txt That is: runas parses user and then will run notepad, passing the remaining parameters. My problem is that argv is broken down into individual parameters, but CreateProcessA...
Manually recombining them is hard: You could try to re-combine them, I think it would work, but be sure to following the same command line escaping rules that windows has. This could be more than the trivial solution you're looking for. Also if there are any parameters that have spaces in them, then you would want t...
975,371
975,415
C++0x performance improvements
One of the C++0x improvements that will allow to write more efficient C++ code is the unique_ptr smart pointer (too bad, that it will not allow moving through memmove() like operations: the proposal didn't make into the draft). What are other performance improvements in upcoming standard? Take following code for exampl...
Yes C++ solves the problem through something called move semantics. Basically it allows for one object to take on the internal representation of another object if that object is a temporary. Instead of copying every byte in the string via a copy-constructor, for example, you can often just allow the destination string ...
975,511
975,526
visual studio doesn't show new members
I've editted a struct, added some members, removed others. But when I'm debugging, it doesn't show the new members, but is still showing some old members. It's very annoying. This is the struct. It doesn't show the firstFreeSpot int. But a vector called appointments, which I removed. This is the struct. struct Appointm...
Maybe try Rebuild solution?
975,513
975,614
Books about how linking, compiling, etc and how it all fits together?
I'm having trouble understanding how compilers and linkers work and the files they create. More specifically, how do .cpp, .h, .lib, .dll, .o, .exe all work together? I am mostly interested in C++, but was also wondering about Java and C#. Any books/links would be appreciated!
There are suprisingly few books on this topic Here are some thoughts: Do not bother withn the Dragon Book unless you are actually writing a compiler using a table driven approach. It is a very hard read abd does not cover the simplest approach to parsing - recursive descent - in any detail. Caveat: I haven't read the ...
975,792
975,820
How does delete[] know the size of an array?
I am curious how delete[] figures out the size of the allocated memory. When I do something like: int* table = new int[5]; delete[] table; I understand that the memory of the table is freed. But what would happen if I reassigned the pointer to some different table. int* table = new [5]; int* table2 = new [9]; table =...
It would delete an array of size 9. It deletes the array pointed to by the pointer. It is unspecified how the size information is stored, so each compiler may implement it in a different way, but a common way to do it is to allocate an extra block before the array. That is, when you do this: int* table = new int[5]; i...
976,002
2,656,893
xsd-based code generator to build xml?
I have a schema (xsd), and I want to create xml files that conform to it. I've found code generators that generate classes which can be loaded from an xml file (CodeSynthesis). But I'm looking to go the other direction. I want to generate code that will let me build an object which can easily be written out as an xml ...
To close this out: I did wind up using CodeSynthesis. It worked very well, as long as I used a single xsd as its source. Since I actually had two xsds (one imported the other), I had to manually merge them (they did some weird inheritance that needed manual massaging). But yes, Code Synthesis was the way to go.
976,015
976,087
Why do I need to close fds when reading and writing to the pipe?
Here is an example to illustrate what I mean: #include <stdio.h> #include <unistd.h> #include <sys/types.h> int main(void) { int fd[2], nbytes; pid_t childpid; char string[] = "Hello, world!\n"; char readbuffer[80]; pipe(fd); if((childpid = fork()) == -1) ...
Your pipe is a unidirectional stream - with a file descriptor for each end. It is not necessary to close() either end of the pipe to allow data to pass along it. if your pipe spans processes (i.e. is created before a fork() and then the parent and child use it to communicate) you can have one write and and one read end...
976,152
976,236
CArray and const template parameter
Is it possible to use const parameter to CArray I am currently using CArray like this but it won't compile: typedef CArray<const CString, const CString&> data_container; And I always get this compile error : error C2664: 'ATL::Checked::memcpy_s' : cannot convert parameter 1 from 'const CString *' to 'void *'
The code that CArray uses expects your TYPE to be non-const, so it can cast to void* (as noted by the compilation error message). You could store const CString pointers, which would give you a const CString when dereferenced. You do have the burden of allocating/cleaning up that memory now. An alternative is to wrap ...
976,476
976,504
Which is more similar to AS3, Java or C++?
I am ActionScript 3/Flex programmer, it is the first language I learned. I want to learn either Java or C++. Would one of these be easier to learn based on my current knowledge?
It really depends what you want to do. C++ is more powerful and fast. But Java has a smaller learning curve. I'd say learn C++, only because it will require you to gain a better understanding of how computers work under the hood. It will also help position you to learn Java, C#, or any other language down the road.
976,573
978,912
Stopping a service in c++ when do I use the ExitProcess() func
I'm stopping a service in my application wanted to know what is the usage of ExitProcess and if I should use it
You should never need to use ExitProcess() to stop a service. In fact, you should never need to use ExitProcess() at all. Services are deeply intertwined with the SCM, and if a service that it thinks should be running just vanishes it will take some action to repair it. In extreme cases, it will force the system to reb...
976,834
976,845
C++ overloaded operator declaration and definition problems
I am having a hard time getting this to work file: myclass.hpp Class MyClass { public: template <class T> MyClass &operator<<(const T &val); }; file: myclass.cpp template <class T> MyClass &MyClass::operator<<(const T &val) { ... } I can compile this in to a object without a problem, But when other fu...
If you want to define instances of your template in separate compilation units (which is typically the case) then you can't define template methods in a separate cpp. Every template method must be visible to the compiler when compiling compilation units that use that template class. Therefore when using the template ac...
976,993
977,118
Issues with seeding a pseudo-random number generator more than once?
I've seen quite a few recommendations for not seeding pseudo-random number generators more than once per execution, but never accompanied by a thorough explanation. Of course, it is easy to see why the following (C/C++) example is not a good idea: int get_rand() { srand(time(NULL)); return rand(); } since calling ...
Each time you call a pseudo-random number generator function, the generator takes some internal state and produces a pseudo-random number and a new internal state. The algorithm for transforming the internal state is carefully chosen so the output appears random. When you seed the random number generator, you're basica...
977,105
977,138
Ever done a total rewrite of a large C++ application in C#?
I know Joel says to never do it, and I agree with this in most cases. I do think there are cases where it is justified. We have a large C++ application (around 250,000 total lines of code) that uses a MFC front end and a Windows service as the core components. We are thinking about moving the project to C#. The reasons...
Have you thought about instead of re writing from scratch you should start to separate out the GUI and back end layer if it is not already, then you can start to write pieces of it in C#. the 250,000 lines were not written overnight they contains hundreds of thousands of man years of effort, so nobody sane enough would...
977,265
977,356
Sleep while holding a boost::interprocess::scoped_lock causes it to be never released
I'm doing IPC on Linux using boost::interprocess::shared_memory_object as per the reference (anonymous mutex example). There's a server process, which creates the shared_memory_object and writes to it, while holding an interprocess_mutex wrapped in a scoped_lock; and a client process which prints whatever the other one...
Your theory is correct. If you look at the bottom of the anonymous mutex example in the reference you linked, you'll see As we can see, a mutex is useful to protect data but not to notify to another process an event. Releasing the mutex doesn't notify anyone else that might be waiting on it, and since your process ju...
977,543
977,561
Under what circumstances is it advantageous to give an implementation of a pure virtual function?
In C++, it is legal to give an implementation of a pure virtual function: class C { public: virtual int f() = 0; }; int C::f() { return 0; } Why would you ever want to do this? Related question: The C++ faq lite contains an example: class Funct { public: virtual int doit(int x) = 0; virtual ~Funct() = 0; }; ...
Declared destructors must always be implemented as the implementation will call them as part of derived object destruction. Other pure virtual functions may be implemented if they provide a useful common functionality but always need to be specialized. In the case, typically derived class implementations will make an e...
977,553
977,575
Inheritance issue when wrapping (inheriting) from a C++ library
The library I'm using has class G and class S which inherits G. I needed to add functionality to them, so I wrapped G and S, rather I inherited from them making Gnew and Snew respectively. So, my inheritance is: G --> Gnew | v S --> Snew But, I want to use Gnew in Snew and when I try to include ...
Where's the cycle? And why would Gnew include the header of Snew? [Edit] OK, I think your inheritance arrows are opposite of what's customary. But this should get you sorted out: In Gnew.h: #pragma once #if !defined(Gnew_h) #define Gnew_h #include "G.h" class Gnew : public virtual G { // added functionality here. }...
977,629
977,876
OpenGL Rotation Matrices And ArcBall
I have been tasked with creating a OpenGL scene implementing ideas such as simple movement, and an Arcball interface. The problem I am having is dealing with the rotation matrix which NeHe's Arcball class (http://nehe.gamedev.net/data/lessons/lesson.asp?lesson=48) computes. What I have so far is a very simple solar sy...
Well, maybe I am wrong, but what I think that is happening to you is that you are rotating around the center of coordinates and not around the planet (that it's what you want to do). To correct that what you have to do is: Translate the point you want to rotate around (the center of the planet) to the center of coordi...
977,653
980,028
GUI thread detecting in the Qt library
I need to know in the context of which thread my function is running, is it main GUI thread or some worker thread. I can't use a simple solution to store QThread pointer in the main function and compare it to QThread::currentThread() because I'm writing a library and I do not have access to the main function. I can of ...
If you have Qt in the lib you can ask for the thread of the application object. The application object is alway living in the main gui thread. void fooWorker() { const bool isGuiThread = QThread::currentThread() == QCoreApplication::instance()->thread(); }
977,927
977,946
Why does this derived class need to be declared as a friend?
I'm learning C++ on my own, and I thought a good way to get my hands dirty would be to convert some Java projects into C++, see where I fall down. So I'm working on a polymorphic list implementation. It works fine, except for one strange thing. The way I print a list is to have the EmptyList class return "null" (a stri...
Because tail is a List<T>, the compiler is telling you that you can't access a protected member of another class. Just as in other C-like languages, you can only access protected members in your instance of the base class, not other people's. Deriving class A from class B does not give class A access to every protected...
978,222
2,581,498
OpenMp C++ algorithms for min, max, median, average
I was searching Google for a page offering some simple OpenMp algorithms. Probably there is an example to calculate min, max, median, average from a huge data array but I am not capable to find it. At least I would normally try to divide the array into one chunk for each core and do some boundary calculation afterwards...
OpenMP (at least 2.0) supports reduction for some simple operations, but not for max and min. In the following example the reduction clause is used to make a sum and a critical section is used to update a shared variable using a thread-local one without conflicts. #include <iostream> #include <cmath> int main() { do...
978,247
978,279
Is there any kind of "expression class" (C++)
I am creating a game that lets the player enter input, changes some states, then checks if a "goal value" is true (obviously this description is muchly simplified), and I want to be able to have that goal value be anything from if the players life is below a certain value to if the amount of enemies remaining is equal ...
Dynamic expressions If you want to receive a string from the user and built an expression from that, maybe the C++ Mathematical Expression Library fits your bill? template<typename T> void trig_function() { std::string expression_string = "clamp(-1.0,sin(2 * pi * x) + cos(x / 2 * pi),+1.0)"; T x; exprtk::symbo...
978,311
978,405
C++ Boost ptr_map serialization error
I have some code that I want to build. The code uses boost::ptr_map class to serialize certain objects. I have Visual Studio 2008 with boost1.38 and I am getting following error from compiler. I wonder if any one else has seen any thing like this. C2039: 'serialize' : is not a member of 'boost::ptr_map' Looks like some...
It looks like there is a boost/ptr_container/serialize_ptr_map.hpp, that is probably important to #include.
978,627
1,463,512
C# app to C++ dll back to the C# app via callbacks
I'm writing a C# application that calls a C++ dll. This dll is a device driver for an imaging system; when the image is being acquired, a preview of the image is available from the library on a line-by-line basis. The C++ dll takes a callback to fill in the preview, and that callback consists basically of the size of...
Turns out the delay is in the C++ side, by a developer who swore up and down it wasn't.
978,644
978,653
recursive file search
I'm trying to figure out how to work this thing out .. For some reason, it ends at a certain point.. I'm not very good at recursion and I'm sure the problem lies somewhere there.. Also, even if I checked for cFileName != "..", it still shows up at the end, not sure why but the "." doesn't show up anymore.. void find_...
From the FindFirstFile documentation: If the function fails or fails to locate files from the search string in the lpFileName parameter, the return value is INVALID_HANDLE_VALUE and the contents of lpFindFileData are indeterminate. You should only exit from the one iteration not the whole program: if( fH...
978,739
978,768
Command pattern without virtual functions (C++)
For performance reasons, I am using the the Curiously Reoccuring Template Pattern to avoid virtual functions. I have lots of small commands which execute millions of times. I am trying to fit this into the Command Pattern. I want to add tons of commands to a queue, and then iterate through them executing each one by...
The CRTP does its magic by resolving the run time type of the object at compile time so that the compiler can inline the function calls. If you have a vector of pointers to a generic type, the compiler cannot determine the specific concrete type, and will not be able to do its compile time resolution. From just the inf...
979,141
979,161
How to programmatically cause a core dump in C/C++
I would like to force a core dump at a specific location in my C++ application. I know I can do it by doing something like: int * crash = NULL; *crash = 1; But I would like to know if there is a cleaner way? I am using Linux by the way.
Raising of signal number 6 (SIGABRT in Linux) is one way to do it (though keep in mind that SIGABRT is not required to be 6 in all POSIX implementations so you may want to use the SIGABRT value itself if this is anything other than quick'n'dirty debug code). #include <signal.h> : : : raise (SIGABRT); Calling abort() ...
979,164
979,170
C++ / CLI - Change all files to UNMANAGED by default
Does anyone know how to change the default behavior of the /clr switch to make all files unmanaged by default? The default behavior of the switch is to make all files managed. I know I can mark each .cpp file individually, but there are ALOT of them...
I ended up leaving the switch OFF in the project properties and then tried turning it on only for those .cpp files that needed it, this worked once I fixed the incompatible options like /RTC1 and /Gm, etc. EDIT In solution explorer, you can right click on the .cpp file and set properties for it, and these will be separ...
979,174
979,188
Does an STL map always give the same ordering when iterating from begin() to end()?
It appears to from my simple testing but I'm wondering if this is guaranteed? Are there conditions where the ordering will be not be guaranteed? Edit: The case I'm particularly interested in is if I populate a map with a large number of entries, will the order of the itertator be the same across multiple runs of my exe...
Yes, it maintains an internal order, so iteration over a set that isn't changing should always be the same. From here: Internally, the elements in the map are sorted from lower to higher key value following a specific strict weak ordering criterion set on construction.
979,182
980,288
learning c++ from boost library source code
I am very interested in c++ and want to master this language. I have read a lot of books about c++. I want to read some library source code to improve my skill, but when I read the boost library source code, I find it is very difficulty. Can anyone give me some advice about how to read boost source code and before I ...
Since you mention that you want to learn the dark art of meta programming then I would recommend "Modern C++ Design" by Andrei Alexandrescu. Meta programming is a very complicated area and is not required most of the time. Once you learn about it, it is very easy to think that it can solve all your problems. It becom...
979,397
979,410
What's wrong with my random number generator?
I'm just diving into some C++ and I decided to make a random number generator (how random the number is, it really doesn't matter). Most of the code is copied off then net but my newbie eyes cannot see anything wrong with this, is there any way this can be tweaked to give a number other than "6" each time? #include <io...
Add srand before the loop srand((unsigned)time(0)); for(int i =0;i < 100;i++) { std::cout << random_number(3,10) << endl; }
979,436
979,465
Help with c++ template templates
Ok, so I wrote an stl-like algorithm called cartesian_product. For those who don't know, the cartesian product is every possible pair of elements from two sets. So the cartesian product of {1, 2, 3} and {10, 20, 30} is {(1,10), (1,20), (1,30), (2,10), (2,20), (2,30), (3,10), (3,20), (3,30)} So the function looks like t...
The template parameter list for vector isn't just one element, it takes two: template < class T, class Allocator = allocator<T> > class vector so in order to accept vector, you need to have a template template parameter with two blanks: template <typename ObjA, typename ObjB, template <typename, typename> class Contai...
979,443
979,491
how to open a file (ie. .txt file) in C++ (kinda like double clicking it in windows)?
I'm wondering how I can open a file literally in C++ (like double clicking it)?
Provided you have the ".txt" extension registered (and text files should be associated with Notepad in a default installation, or something else if you've changed it from Explorer - you'd have to work pretty hard to disassociate them), Windows will open it for you without you having to specify the executable name: Shel...
979,759
979,768
Operator< and strict weak ordering
How to define operator< on n-tuple (for example on 3-tuple) so that it satisfy strict weak ordering concept ? I know that boost library has tuple class with correctly defined operator< but for some reasons I can't use it.
if (a1 < b1) return true; if (b1 < a1) return false; // a1==b1: continue with element 2 if (a2 < b2) return true; if (b2 < a2) return false; // a2 == b2: continue with element 3 if (a3 < b3) return true; return false; // early out This orders the elements by a1 being most siginificant and a3 least signific...
979,814
979,833
C++ References and Java References
//C++ Example #include <iostream> using namespace std; int doHello (std::string&); int main() { std::string str1 = "perry"; cout << "String=" << str1 << endl; doHello(str1); cout << "String=" << str1 << endl; // prints pieterson return 0; } int doHello(std::string& str){ str = "pieterson"; ...
Java does not have pass by reference (which you were using in the C++ code) at all. The references are passed by value. (The values of str and str1 aren't objects at all, they're references - it really helps to keep the two concepts very separate.) Typically you would use a return value to return a new reference if you...
979,877
979,947
Concat string in C++(STL)
i have code like this string xml_path(conf("CONFIG")); xml_path+=FILE_NAME; Where, conf function returns char * and FILE name is const char * I want to combine it to one line like xml_path(conf("CONFIG")).append(FILE_NAME) how do i do it? any suggestions ??
Question asked for one line: string xml_path = string(conf("CONFIG")) + string(FILE_NAME); (I assume xml_path is the name of the variable, and not some sort of call in a library I don't know about).