question_id
int64
25
74.7M
answer_id
int64
332
74.7M
title
stringlengths
20
150
question
stringlengths
23
4.1k
answer
stringlengths
20
4.1k
2,211,733
2,211,993
iPhone Quartz 2d development using C++?
Could I write c++ code that interacts with the iPhone Quartz 2D framework, or can I only using objective-c? Thanks
Yes. Quartz is a C framework. You can use C++ code that uses Quartz. You will need some Objective-C to launch your application and get a graphics context for a view to draw into.
2,211,755
2,211,866
Covert String to LPVOID and LPCWSTR in C++
I’m working with the winHTTP API in c++ and I have started to write a wrapper class for my application. For simplicity I have a number of functions that can take string parameters and use them in the winHTTP calls. However many of these require the data to be LPVOID or LPCWSTR. I can make it all work by making my wrapp...
Use this: bool httpWrapper::setPostData(const string &postData){ _postData = (LPWSTR)postData.c_str(); _postData_len = 47; // Something else, actually. return false; } LPWSTR _postData; You can pass a LPWSTR to methods which expect a LPCWSTR. So you can work with strings. btw, did you just try passing the s...
2,211,801
2,212,300
Generic member function pointer help
Hey, I've got a question about general member function pointers. I'm trying to achieve something similar to the following question How to define a general member function pointer Essentially what I want to be able to do is to register a member function pointer that accepts a generic Event object as its argument with a ...
(Here's a more direct answer to your boost::function/bind problem, without all the Boost.Signals2 stuff.) It seems you're not using the _1, _2, etc. placeholders when using boost::bind. This example illustrates how you should use them: struct KeyboardEvent { char key; }; typedef boost::function<void (KeyboardEvent)> K...
2,211,867
2,211,959
How do I call C++/CLI from C#?
I have a class implemented in C++ that's responsible for the arithmetic computation of the program, and an interface using WPF. I process the input with C# but then how can I use my C++ class? I've seen some comments about making a managed C++ wrapper class to interact with it, but I don't know where to start. Nor do I...
Have you take a look at C++/CLI? Let me give a very short example. Here is the source file from a Visual C++ -> CLR -> Class Library project. It basically get Windows username and return it. Please note that, in order to get this compiled, you have to go into project settings and mark "Additional Dependencies" as "Inhe...
2,211,915
2,212,063
Library function for Permutation and Combination in C++
What's the most widely used existing library in C++ to give all the combination and permutation of k elements out of n elements? I am not asking the algorithm but the existing library or methods. Thanks.
Combinations: from Mark Nelson's article on the same topic we have next_combination Permutations: From STL we have std::next_permutation template <typename Iterator> inline bool next_combination(const Iterator first, Iterator k, const Iterator last) { if ((first == last) || (first == k) || (last == k)) ...
2,211,933
2,260,791
How to call a function automatically?
I have rewrited a simple MFC application in MS Visual Studio 2008, and now it is working how i wanted. My only problem is, that i have to press a button, and i don't want. It should work automatically. I also noticed that the function are somehow called automatically. These function are called each after: CGetF...
PostMessage(WM_COMMAND, MAKEWPARAM(IDC_BUTTON_GET_FILE_LIST, BN_CLICKED), 0); This is the command what i needed. This command will manipulate my button like it has been clicked. Thanks for your help anyway. kampi
2,212,089
2,215,637
Thread limit in Unix before affecting performance
I have some questions regarding threads: What is the maximum number of threads allowed for a process before it decreases the performance of the application? If there's a limit, how can this be changed? Is there an ideal number of threads that should be running in a multi-threaded application? If it depends on what the...
This is actually a hard set of questions to which there are no absolute answers, but the following should serve as decent approximations: It is a function of your application behavior and your runtime environment, and can only be deduced by experimentation. There is usually a threshold after which your performance act...
2,212,582
2,220,582
Using a QNetworkAccessManager.get, how can I decide to abort?
I am attempting to use the QT QNetworkAccessManager class to manage some downloads in a multi-threaded C++/QT application. On worker thread (edit: the thread is seperate for other reasons aside from doing the download), I'm would like to do a get to an external server and be ready to receive the results with the code:...
You do not need a worker thread for using QNetworkAccessManager. It is asynchronous, so it is OK to use it from your main thread. In the QThread you implement a abortTheReply() slot and inside that you do m_reply->abort(). Then you connect your do_abort() signal to the abortTheReply().
2,212,607
2,428,783
RapidXML, reading and saving values
I've worked myself through the rapidXML sources and managed to read some values. Now I want to change them and save them to my XML file: Parsing file and set a pointer void SettingsHandler::getConfigFile() { pcSourceConfig = parsing->readFileInChar(CONF); cfg.parse<0>(pcSourceConfig); } Reading values from XM...
I think this is a RapidXML Gotcha Try adding the parse_no_data_nodes flag to cfg.parse<0>(pcSourceConfig)
2,212,661
2,212,685
C/C++ cool macro definitions?
Besides __LINE__ and __FILE__, are there other useful pre-defined macros, like __FUNCTION_NAME__? If not, but you know of other cool/useful defined macros (especially for debugging purposes), I'd love to hear about them. Some have asked about platform: I'm using gcc/g++ on MacOSX.
I can find the following (descriptions from C99 draft, but they are available in C89 too I think): __DATE__: The date of translation of the preprocessing translation unit: a character string literal of the form "Mmm dd yyyy", where the names of the months are the same as those generated by the asctime function, and th...
2,212,776
2,212,940
Overload handling of std::endl?
I want to define a class MyStream so that: MyStream myStream; myStream << 1 << 2 << 3 << std::endl << 5 << 6 << std::endl << 7 << 8 << std::endl; gives output [blah]123 [blah]56 [blah]78 Basically, I want a "[blah]" inserted at the front, then inserted after every non terminating std::endl? The difficulty here is NOT...
What you need to do is write your own stream buffer: When the stream buffer is flushed you output you prefix characters and the content of the stream. The following works because std::endl causes the following. Add '\n' to the stream. Calls flush() on the stream This calls pubsync() on the stream buffer. This calls...
2,212,847
2,212,953
Can I delete OpenGL vertex arrays after calling glDrawArrays?
I am generating the vertex arrays on the fly on each render and I want to delete the arrays afterwards. Does glDrawArrays immediately copy the vertex arrays to the server? Hence is it safe to delete the vertex arrays after calling glDrawArrays? float * vp = GetVertices(); // Regenerated on each render glVertexPointer(...
Yes, it is copied immediately, so once you've done the call you can do whatever you like with the array. Also, as dirkgently pointed out, you need to use delete[] vp to delete an array.
2,213,319
2,217,356
How to build C++ for OSX 10.4, 10.5 and 10.6 in Xcode with dynamic libraries
I'm building a C++ command line tool in Xcode. The project contains dylibs for curl, boost and log4cpp. Ideally id like to build an i386 universal binary that supports 10.4 through to 10.6. I cant seem to get Xcode to compile, when I target 10.4 it says things like no such file or directory. When i target 10.6 x_64 it...
The 3rd party libraries were built for 10.6 x_64, I needed to rebuild them for 10.4. I installed the 10.4u sdk by downloading xcode 3.2 and choosing 'install 10.4 support' during the installation process. After rebuilding each library with GCC 4.0 against the 10.4u sdk, my project compiled successfully. I also used sta...
2,213,342
2,213,380
Modify malloc strategy for 2D Array so malloc succeeds
We recently received a report that our application will occasionally fail to run. I tracked down the problem code to this: struct ARRAY2D { long[] col; } int numRows = 800000; int numCols = 300; array = (ARRAY2D*) malloc(numRows * numCols * sizeof(long)) This allocation of 800 Mb can fail if the user doesn't have ...
You can allocate smaller chunks of memory separately, instead of one huge block. long** array = NULL; array = (long**) malloc(numCols * sizeof(long*)); for (int i = 0; i < numCols; i++) array[i] = (long*) malloc(numRows * sizeof(long)); Generally, memory allocation may fail, every allocation. However, let's ...
2,213,664
2,213,750
In the generic programming/TMP world what exactly is a model / a policy and a "concept"?
I'd like to know the precise yet succinct definitions of these three concepts in one place. The quality of the answer should depend on the following two points. Show a simple code snippet to show how and what the concept/technique is used for. Be simple enough to understand so that a programmer without any exposure to...
A concept is a set of requirements on a type. For example, you could have a concept called "RandomAccessible", which places the requirement on a type that it implements operator[](int) in O(1) time. As concepts were dropped from the upcoming C++ standard, they only exist intangibly in C++ as documentation. As an exampl...
2,213,673
2,213,861
How to build boost library and others against OS X 10.4u SDK on OS X 10.6?
I'm trying to build the boost libraries and others against the os x 10.4u.sdk so I can include them in a project targeting 10.4 upwards. I'm not entirely sure what to do, am I aiming to put the .dylibs in 10.4.sdk/usr/local/.. or in my default 10.6 /usr/local/.. with support for 10.4? Any help much appreciated. Toby.
You need to distribute your libraries to the users, so it doesn't help installing them into your machiine's /usr/local. It's better to just set the linker search path to whatever directory you have the library. When you distribute an app, you're supposed to put every libraries you use inside the .app bundle (unless yo...
2,213,690
2,213,712
How to get the program path i am executing with "open with" method?
I have the problem that i am using relative paths for my files, so when i use "open with" method for opening a file into my program, all my paths are screwed (it will create my files in the folder where i used this "open with" method.) How i can retrieve the full path to the .exe file that im using to open the file wit...
#include <windows.h> #include <string> #include <iostream> using namespace std;; string ExePath() { char buffer[MAX_PATH]; GetModuleFileName( NULL, buffer, MAX_PATH ); string::size_type pos = string( buffer ).find_last_of( "\\/" ); if ( pos == string::npos ) { return ""; else { retu...
2,213,753
2,213,765
Added benefit of a pointer, when to use one and why
I'm learning C++ at the moment and though I grasp the concept of pointers and references for the better part, some things are unclear. Say I have the following code (assume Rectangle is valid, the actual code is not important): #include <iostream> #include "Rectangle.h" void changestuff(Rectangle& rec); int main() { ...
There really isn't any reason you can't. In C, you only had pointers. C++ introduces references and it is usually the preferred way in C++ is to pass by reference. It produces cleaner code that is syntactically simpler. Let's take your code and add a new function to it: #include <iostream> #include "Rectangle.h" void ...
2,213,894
2,213,898
Can I call a copy constructor explicitly?
I'm a little confused as to the mechanics of the copy constructor. Correct me if I'm wrong: If a method takes a reference to an object as a parameter, and the class defines a copy construtor, then the class uses the constructor to create a copy of itself and that gets passed to the function instead of a reference to t...
No, if a function take a reference: void f1( Object & o ); // call by reference then no copy is made. If a function takes a value: void f2( Object o ); // call by value then a copy is created by the compiler using the copy constructor. And yes, when you say: Object * obj = new Object(anotherObject); // not &a...
2,213,957
2,214,217
Member Function Pointer with base class argument accepting derived class argument
So I'm working on this event management class. I'm storing a list of pointers to member functions of the signature void (Event*) where Event is just a struct that stores some random data at the moment. typedef boost::function<void(Event*)> Callback; typedef vector<Callback> CallbackList; class EventManager { public: ...
So I found a solution that seems to be working for me, but I'm not sure if it's entirely safe to do. I changed the RegisterEventHandler method to cast all of the function pointers that I send in to the same type... template<typename T1, typename T2> void RegisterEventHandler(const String& type, T1 handler, T2* obj)...
2,214,053
2,215,085
C++ redirect outgoing connections
Is there any way in C++ on windows to monitor a program and redirect any outgoing requests it makes on a specific port? I have a simple C++ http proxy and want it to be able to automatically redirect all browser requests on port 80 through itself.
The simple way to do it is to create a Windows kernel hook to trap socket requests and reroute them to your proxy. Some useful documentation on this is: http://www.internals.com/articles/apispy/apispy.htm If you're using Windows Vista or better, consider Windows Filtering Platform (WFP): http://www.microsoft.com/whdc/d...
2,214,295
2,214,316
Is it impossible to use an STL map together with a struct as key?
I have the following code: struct Node { int a; int b; }; Node node; node.a = 2; node.b = 3; map<int, int> aa; aa[1]=1; // OK. map<Node, int> bb; bb[node]=1; // Compile error. When I tried to map an instance of my struct Node to an int, I got a compile error. Why?
For a thing to be usable as a key in a map, you have to be able to compare it using operator<(). You need to add such an operator to your node class: struct Node { int a; int b; bool operator<( const Node & n ) const { return this->a < n.a; // for example } }; Of course, what the real operator does depends o...
2,214,679
2,215,880
supplying dependency through base class
I have a list of Parts and some of them need a pointer to an Engine, lets call them EngineParts. What I want is to find these EngineParts using RTTI and then give them the Engine. The problem is how to design the EnginePart. I have two options here, described below, and I don't know which one to choose. Option 1 is fas...
Too bad that the reply stating that 'a part cannot hold the engine' is deleted because that was actually the solution. Since not the complete Engine is needed, I found a third way: class Part; class EngineSettings { private: Engine *engine friend class Engine; void SetEngine(Engine *e) {en...
2,214,727
2,214,808
Why am I getting Debug assertion failed after strcpy_s?
im just starting to learn about sockets and i have been given this code, and i have to make the port lookup logic work. But the problem is i keep getting this run time error and I dont know why? // portlookup.cpp // Given a service name, this program displays the corresponding port number. #include <iostream> #pragma ...
Your problem appears to be that you aren't passing a command line, you check argc < 2, but when it is < 2 you execute the strcpy_s anyway. In Visual Studio, Got to the Project Properties dialog, from there go to the Debugging page and add the service name to Command Arguments And fix your argument checking code if (arg...
2,214,805
2,214,832
How do you use a bubble sort with pointers in c++?
So here's what I have so far: void sortArray(int amountOfScores, int* testScores) { for(int i = 0; i < amountOfScores; i++) { for(int j = 0; j < amountOfScores-1; j++) { if(*(testScores+i) > *(testScores+j+1)) { int temp = *(testScores+j); ...
You problem might be here: if(*(testScores+i) > *(testScores+j+1)) Did you mean: if(*(testScores+j) > *(testScores+j+1)) (Note i replaced by j). btw, in Bubble sort, if there are no swaps, you should break. This will cause a speed up in some cases.
2,214,812
2,214,831
How to provide many constructors, but without too many dependencies?
This is a pretty basic C++ design question: I have a class that contains some data which is read-only, once the object is constructed: class Foo { private: class Impl; Impl* impl_; public: int get(int i); // access internal data elements }; Now, I'd like to implement several ways to construct a Foo object and ...
If you want to construct something from a range, perhaps: class X { public: template <class InputIterator> X(InputIterator first, InputIterator last); }; Usage: //from array X a(array, array + array_size); //from vector X b(vec.begin(), vec.end()); //from stream X c((std::istream_iterator<Y>(std::cin)), std:...
2,214,965
2,215,038
Cross platform Networking API
I was wondering if there was an API to do networking that would work on Windows, Mac and Linux. I would like to make a card game that 2 people can play through a TCP connection.
There are a few options for this, some easier to use than others: APR (Apache Portable Runtime) - Very popular. Quite easy to use. Includes lots of additional features handy for network programming (threads, mutexes, etc.) ACE - Popular among the embedded space. Personally, I found it quite a complicated API, and not ...
2,214,977
2,215,016
Compiling command line Linux program on Windows
I need to write a relatively simple command line C++ program to be run a Linux environment. However, I would like to code as well as compile this on Windows. The reason I don't want to port it to Linux is because it requires MySQL interactions, and that would require some messy porting (IMO). It does not have to run on...
(I'm assuming "..don't want to port it to Linux.." is a typo for "..from Linux" and that you want the code to run in Linux as you said in your first sentence. This means cygwin or mingw would only be used as cross compilers and aren't going to be very useful.) This program already builds and works (or mostly works) on...
2,215,033
2,215,111
MinGW vs Visual Studio 2008 output code quality
A few days ago I was told that recent versions of g++ produce "better" x86 code than MSVC 2008. Basically GCC with full optimization produces faster applications than MSVC with full optimizations. While it's certainly correct to state that this, if true, depends a great deal on the application and the C++ code used (an...
My experience is compiling my C++ JPEG-LS image compression project. http://charls.codeplex.com For me, Visual C++ was significantly faster. I compiled it mostly with G++ on linux. After a lot of tuning, the G++ version was still about 10-15% slower on the same hardware (the same physical machine, dual booted as linu...
2,215,040
2,215,225
operator overloading c++
When overloading operators, is it necessary to overload >= <= and !=? It seems like it would be smart for c++ to call !operator= for !=, !> for operator<= and !< for operator>=. Is that the case, or is it necessary to overload every function?
Yes, it is necessary, if you want all of them to work the way you want them to work. C++ does not force any specific semantics on most of the overloadable operators. The only thing that is fixed is the general syntax for the operator (including being unary or binary and things like precedence and associativity). This i...
2,215,132
2,215,266
Selecting nodes with probability proportional to trust
Does anyone know of an algorithm or data structure relating to selecting items, with a probability of them being selected proportional to some attached value? In other words: http://en.wikipedia.org/wiki/Sampling_%28statistics%29#Probability_proportional_to_size_sampling The context here is a decentralized reputation s...
This is what I'd do: int select(double *weights, int n) { // This step only necessary if weights can be arbitrary // (we know total = 1.0 for probabilities) double total = 0; for (int i = 0; i < n; ++i) { total += weights[i]; } // Cast RAND_MAX to avoid overflow double r = (double) ...
2,215,250
2,215,398
C++ Error: explicit qualification
What do these errors mean? Vector.cpp:13: error: ISO C++ forbids declaration of ‘Vector’ with no type Vector.cpp:13: error: explicit qualification in declaration of ‘void Vector::Vector(double, double, double)’ The C++ (Line 13 is the Vector::Vector( ...): #include <iostream> using namespace std; namespace Ve...
Looks like the major problem is that your cpp files didn't include your header file.
2,215,339
2,215,415
Can competing atomic operations starve one another?
Imagine a program with two threads. They are running the following code (CAS refers to Compare and Swap): // Visible to both threads static int test; // Run by thread A void foo() { // Check if value is 'test' and swap in 0xdeadbeef while(!CAS(&test, test, 0xdeadbeef)) {} } // Run by thread B void bar() { ...
As a theoretical matter, yes. If you could manage somehow to get the two threads running in lockstep like this time thread A thread B ---- -------- -------- || CAS || atomic_write || CAS \/ atomic_write Then CAS would never r...
2,215,365
2,215,418
partial specialization of function template
Can anybody explain why partial specialization is not valid for function template but it's fine for class template. I understand partial specialization might make the compiler get confused with function overloading, but I still need more information to make me totally understand. Can anybody offer me some neat examp...
Getting confused is enough of a reason, in this case. And there's an existing alternative solution: overloading. The committee spent a lot of effort (it seems to me, I wasn't there) getting function overload resolution working for templates, and surely part of the reason for that included not having to solve the less-...
2,215,441
2,215,506
With my global hook installed, how do I know when a window begins to move and when it stops moving?
Is there an easy way to figure this out? I guess I can use WM_MOVE to tell me when it begins by keeping a timer. If the window has not received a WM_MOVE message within the last 2 seconds, then I know that it has just begun to move. Then I set another timer and wait for their not to be a message within a period of time...
If you are in a position to see WM_MOVE messages, then you are also in a position to see WM_ENTERSIZEMOVE and WM_EXITSIZEMOVE messages.
2,215,549
2,215,660
How to use/link gdLibrary (libgd) with MS Visual C++ (e.g. 2008 Express Edition)? Getting LNK2019 errors
I have to use the gdLibrary (http://www.libgd.org) in a C++ App on MS Windows XP Prof. SP3 32bit - and I'm trying and googleing for two days now without success. Does anyone of you use libgd with MS VC++ 200x EE? My problem: It has to to compile with MS Visual C++ (e.g. the 2008 Express Edition - fixed 3rd party condit...
Did you put NODLL definition in your project? If you did that, you should use bgd_a.lib instead. And you also need to make sure you have defined WIN32. I tried to create a simple project with latest release and it does linked success. If I add NODLL without changing tot bgd_a then I get the same error message.
2,215,609
2,217,731
Problem in luabind with default_converter and tables
===Edit=== The problem is actually much simpler than this, any wrapped function that takes a table is causing the problem. If I wrap a function that takes luabind::object, and call that function with a table argument, then the gc causes an invalid free(). I'm starting to think that this may be some kind of crazy comp...
Yeah, I figured it out. Turns out that luabind didn't have any problems at all, except for the way it was built. The jam build system, on mac os x, causes the static lua library to be linked in with the luabind shared library, causing duplicate symbols (and duplicate static variables) when I link my final binary. It...
2,215,846
2,215,858
Values of Argv when something is not entered from command line
Hi I was wondering what values would argv[1] or argv[2] be, if i failed to provide it with command line arguments
It would be garbage NULL. Therefore you should always first test the argc (argument count) before trying to access the command line arguments. See this for more detailed information.
2,215,856
2,215,865
Compiling nonessential object files with GCC
Consider the following example g++ a.o b.o c.o -o prog If it is the case that c.o does not contribute any executable code to prog, nor are there any dependencies on c.o in any of the other files, will GCC yet include the contents of c.o in prog? Said another way, aside from compilation time, what (if any) negative con...
There aren't any negative consequences except that your executable might be unnecessarily large. The linker can probably dead strip unused code for you, and that will shrink things back down. You can use some kind of object viewing tool (otool, objdump, nm, etc.) on the output executable to see if your program has ex...
2,215,930
2,215,970
Where to get simple opensource adpcm C\C++ encoder lib?
Where to get simple opensource pcm to adpcm C\C++ encoder lib?
The sox package can deal with several varieties of ADPCM both as a source and destination format.
2,215,961
2,216,040
Is Communicating Sequential Processes ever used in large multi threaded C++ programs?
I'm currently writing a large multi threaded C++ program (> 50K LOC). As such I've been motivated to read up alot on various techniques for handling multi-threaded code. One theory I've found to be quite cool is: http://en.wikipedia.org/wiki/Communicating_sequential_processes And it's invented by a slightly famous guy,...
CSP, as a process calculus, is fundamentally a theoretical thing that enables us to formalize and study some aspects of a parallel program. If you instead want a theory that enables you to build distributed programs, then you should take a look to parallel structured programming. Parallel structural programming is the ...
2,216,017
2,216,178
dynamical two dimension array according to input
I need to get an input N from the user and generate a N*N matrix. How can I declare the matrix? Generally, the size of the array and matrix should be fixed at the declaration, right? What about vector<vector<int>> ? I never use this before so I need suggestion from veteran.
Boost implements matrices (supporting mathematical operations) in its uBLAS library, and provides usage syntax like the following. #include <boost/numeric/ublas/matrix.hpp> int main(int argc, char* argv[]) { unsigned int N = atoi(argv[1]); boost::matrix<int> myMatrix(N, N); for (unsigned i = 0; i < myMatr...
2,216,029
2,216,092
Common pattern for library initialization and shutdown?
Is there a pattern that I may use for calling the required initialization and cleanup routines of an underlying (C) library? In my case, I would like to create the wrapper class so that it can be composed into other objects. The problem is that, when I destroy the wrapper class, the cleanup routines of the underlying l...
Not everything has to be a class. The Singleton pattern would let you turn this into a class, but it's really not buying you anything over global functions: bool my_library_init(); void my_library_shutdown(); The first call returns true if the library was successfully initialized, the second just quietly does whateve...
2,216,041
2,216,114
Prevent unnecessary copies of C++ functor objects
I have a class which accumulates information about a set of objects, and can act as either a functor or an output iterator. This allows me to do things like: std::vector<Foo> v; Foo const x = std::for_each(v.begin(), v.end(), Joiner<Foo>()); and Foo const x = std::copy(v.begin(), v.end(), Joiner<Foo>()); Now, in the...
You have stumbled upon an often complained about behavior with <algorithm>. There are no restrictions on what they can do with the functor, so the answer to your question is no: there is no way to encourage the compiler to elide the copies. It's not (always) the compiler, it's the library implementation. They just like...
2,216,143
2,216,149
Comparing chars in a character array with strcmp
I have read an xml file into a char [] and am trying to compare each element in that array with certain chars, such as "<" and ">". The char array "test" is just an array of one element and contains the character to be compared (i had to do it like this or the strcmp method would give me an error about converting char...
you need to 0 terminate your test string. char test[2]; for (int i=0; i<amountRead; ++i) { test[0] = str[i]; test[1] = '\0'; //you could do this before the loop instead. ... But if you always intend to compare one character at a time, then the temp buffer isn't necessary at all. You could do this inst...
2,216,160
2,216,168
Splitting the string at Enter key
I'm getting the text from editbox and I'd want to get each name separated by enter key like the character string below with NULL characters. char *names = "Name1\0Name2\0Name3\0Name4\0Name5"; while(*names) { names += strlen(names)+1; } how would you do the same for enter key (i.e separated by ...
Use strstr: while (*names) { char *next = strstr(names, "\r\n"); if (next != NULL) { // If you want to use the key, the length is size_t len = next - names; // do something with a string here. The string is not 0 terminated // so you need to use only 'len' bytes. How you d...
2,216,234
2,216,255
Queue message processing with Multithreading
I have to design multithreaded module for a problem. And problem is, I have queue, there is a one thread which is putting messages in the message queue, and there are two thread say A and B, thread A process the even message (0,2,4..) and thread B processes the odd message(1,3,5..). I came up with two solution, first o...
Using only one queue and synchronizing A and B in order to ensure a proper fetching sequence is a complete nonsense. Just use two queues, one for A and one for B, and ensure that they are filled correctly (which seems an easier and cleanier problem by far, even from a design PoV.
2,216,280
2,216,289
C++ auto conversions
For two unrelated classes "class A" and "class B" and a function B convert(const A&); Is there a way to tell C++ to automatically, for any function that takes "class B" as argument, to auto convert a "class A". Thanks!
What you would normally do in this case is give B a constructor that takes an A: class B { public: B(const A&); }; And do the conversion there. The compiler will say "How can I make A a B? Oh, I see B can be constructed from an A". Another method is to use a conversion operator: class A { public: operator B(vo...
2,216,388
2,217,406
How to measure memory used in a block or program with C++
What is the best way to measure the memory used by a C++ program or a block in a C++ program. The measurement code should thereby be part of the code and it should not be measured from outside. I know of the difficulty of that task, so it does not have to be 100% accurate but at least give me a good impression of the m...
Measuring at the block level will be difficult (at best) unless you're willing to explicitly add instrumentation directly to the code under test. I wouldn't start with overloads of new and delete at the class level to try to do this. Instead, I'd use overloads of ::operator new and ::operator delete. That's basically t...
2,216,654
2,216,705
Pattern matching style in C++?
I love Haskell style pattern matching. I have my C++ code as follows: ObjectPtr ptr; if(ptr.isType<Foo>()) { // isType returns a bool Ptr<Foo> p = ptr.convertAs<Foo>(); // convertAs returns a Ptr<Foo> ...... } if(ptr.isType<Bar>()) { Ptr<Bar> p = ptr.convertAs<Bar>(); ...... } Now, are there any macros I can d...
I'm assuming that your Ptr template has the concept of a NULL pointer. ObjectPtr ptr; if(Ptr<Foo> p = ptr.convertAs<Foo>()) { // convertAs returns a NULL pointer if the conversion can't be done. ...... } if(Ptr<Bar> p = ptr.convertAs<Bar>()) { ...... } Though, as others have noted, switching on type is usually a s...
2,216,741
2,216,755
Need help with understanding STL vector (simple code in body of message)
Here is the code: #include <vector> #include <iostream> class A { public: A() { std::cout << __FUNCTION__ << "\n"; } ~A() { std::cout << __FUNCTION__ << "\n"; } A& operator=(const A&) { std::cout << __FUNCTION__ << "\n"; return *this;} }; int main(int argc, char* argv[]) { std::vector<A> as; A a;...
To understand what happens, you are missing one method in A : A(const A&) { std::cout << __FUNCTION__ << "(const A&)\n"; } Then you see the output: A() A(const A&) A(const A&) A(const A&) ~A ~A ~A ~A What happen is that, for each push_back the vector allocate a new contiguous array, copy the old content, and destroy ...
2,216,889
2,216,906
If a functions return an int, can an int be assigned to it?
If a function returns an int, can it be assigned by an int value? I don't see it makes too much sense to assign a value to a function. int f() {} f() = 1; I noticed that, if the function returns a reference to an int, it is ok. Is it restricted only to int? how about other types? or any other rules? int& f() {} f()...
The first function returns an integer by-value, which is an r-value. You can't assign to an r-value in general. The second f() returns a reference to an integer, which is a l-value - so you can assign to it. int a = 4, b = 5; int& f() {return a;} ... f() = 6; // a is 6 now Note: you don't assign a value to the funct...
2,217,035
2,217,197
Simple cross-platform free audio library for raw PCM?
I'm writing a cross-platform Qt-based program that from time to time needs to play back audio supplied externally (outside my control) as raw PCM. The exact format is 16 bit little-endian PCM at various common sample rates. My first obvious idea was to use Qt's own Phonon for audio playback, but there are two problems ...
Qt 4.6 has the new QtMultimedia module. https://doc.qt.io/archives/4.6/qtmultimedia.html The QAudioOutput class would seem to do what you want - it just plays raw PCM data.
2,217,148
2,217,169
Printf - access violation reading location - C++
0xC0000005: Access violation reading location 0xcccccccc. printf is throwing this exception. I don't know why this is happening... There are values in those string variables. Am I using printf wrong? Help! (Please see the switch case) string header; string body; string key; if (!contactList.isEmpty()) { cout <<...
printf's "%s" expects a char* as an argument, not a std::string. So printf will interpret your string objects as pointers and try to access the memory location given by the object's first sizeof(char*) bytes, which leads to an access violation because those bytes aren't really a pointer. Either use the strings' c_str m...
2,217,204
2,217,264
180 to -180 motion in opengl c++?
i'm using a glutTimerFunc(...) to achieve motion of robot arm, my problem is left side 0 degree to 90 is easily done, when i try 0 to -90 degree, the arm is not stoping? i tried various methods, but all falied, can you suggest better options? here's my timer function, void myTimerFunc(int var) { switch(var) { case 1: i...
Looks to me like you're confused about how to treat angles. Are you using a [0, 360] scale for a full circle or [-180, +180]? I see a check against 270 in your code, but your prose mentions -90. Yes, they're "the same", but if it's not working perhaps some confusion has crept into your code. If you're going with [-1...
2,217,206
2,217,237
Smallest sum of pairs
Given 2N-points in a 2D-plane, you have to group them into N pairs such that the overall sum of distances between the points of all of the pairs is the minimum possible value.The desired output is only the sum. In other words, if a1,a2,..an are the distances between points of first, second...and nth pair respectively,...
You seem to be looking for Minimum weight perfect matching. There are algorithms to exploit the fact that these are points in a plane. This paper: Mincost Perfect Matching in the Plane has an algorithm and also mentions some previous work on it. As requested, here is a brief description of a "simple" algorithm for min...
2,217,436
2,220,142
Emacs Semantic/ECB namespace-struct C++ confusion
I'm trying to setup ECB to work with C++ sources. seemingly, semantic or ECB has problem determining whenever a function declarant with explicit namespace, namespace:: function , is really in the namespace. instead it parses it as struct member function. Moreover, typedef is parsed as function prototypes. What should I...
It's better to take CEDET from CVS. as i remember were some fixes for such cases
2,217,459
2,217,477
Extension wrapper malloc allocator for C++ STL
Apparently there is a “malloc_allocator” provided with gcc for use with STL. It simply wraps malloc and free. There is also a hook for an out-of-memory handler. Where can I find more about it? Where can I find its header file? I’m using gcc 4.x.
Is this something you want? You will need to include and pass in an object as the STL object's allocator template parameter.
2,217,568
2,217,611
question on stl fill function in C++
Let's say I have an array like this: string x[2][55]; If I want to fill it with "-1", is this the correct way: fill(&x[0][0],&x[2][55],"-1"); That crashed when I tried to run it. If I change x[2][55] to x[1][54] it works but it doesn't init the last element of the array. Here's an example to prove my point: strin...
Because when you have a multi-dimensional array, the address beyond the first element is a little confusing to calculate. The simple answer is you do this: &x[1][55] Let's consider what a 2d array x[N][M] is laid out in memory [0][0] [0][1] ... [0][M-1] [1][0] [1][1] ... [1][M-1] [N-1][0] .. [N-1][M-1] So, the very ...
2,217,628
2,218,034
Multiple definition of inline functions when linking static libs
I have a C++ program that I compile with mingw (gcc for Windows). Using the TDM release of mingw which includes gcc 4.4.1. The executable links to two static library (.a) files: On of them is a third-party library written in C; the other is a C++ library, written by me, that uses the C library provides my own C++ AP...
First you have to understand the C99 inline model - perhaps there is something wrong with your headers. There are two kind of definitions for inline functions with external (non-static) linkage External definition This definition of a function can only appear once in the whole program, in a designated TU. It provides ...
2,217,776
2,217,868
Calling a C++ object's method from an Objective-C child object
I have some Objective-C++ code that I'm trying to get events out of an Objective-C object to call a method within a C++ object. I'm very new to Objective-C, so I may be doing this all wrong. Example: @interface KnobClass { } -(void)Event; @end class DoorClass { public: KnobClass * knob; void start() { kno...
I'm learning Objective-C too. This works in gcc 4.3.3: #import <Foundation/Foundation.h> class AlarmClass { public: void Alert() { printf("Alert!\n"); } }; @interface KnobClass: NSObject { AlarmClass *alarm; } -(void)Event; -(id)initWithAlarm:(AlarmClass*) alarm; @end @implementation Knob...
2,217,825
2,217,902
How can I resolve linker issues when I compile this C++ program that requires GLUT?
I'm trying to compile this C++ program which utilizes the GLUT32 libraries. Right now I'm getting the following errors: Error 1 error LNK2001: unresolved external symbol _gluPerspective@32 Camera.obj soundCube Error 2 error LNK2001: unresolved external symbol _gluLookAt@72 Camera.obj soundCube Error...
The unresolved symbols are from the GL and GLU libraries. You need to add the link libraries for them as well.
2,217,878
2,217,889
C++ std::set update is tedious: I can't change an element in place
I find the update operation on std::set tedious since there's no such an API on cppreference. So what I currently do is something like this: //find element in set by iterator Element copy = *iterator; ... // update member value on copy, varies Set.erase(iterator); Set.insert(copy); Basically the iterator return by Set...
set returns const_iterators (the standard says set<T>::iterator is const, and that set<T>::const_iterator and set<T>::iterator may in fact be the same type - see 23.2.4/6 in n3000.pdf) because it is an ordered container. If it returned a regular iterator, you'd be allowed to change the items value out from under the co...
2,217,918
2,217,927
Dynamic memory use in class member
I'm getting some odd behavior in one of my class members and it is truly throwing me for a loop but I'm certainly not seeing the issue (long week!) void MyFakeStringClass::readStream( iostream& nInputStream ) { // Hold the string size UINT32 size = 0; // Read the size from the stream nInputStream.read(...
You need to create the string using: value = string( buffer, size ); If you do not specify the size, it will assume buffer is a null-terminated string. Since there is no null terminator, it reads past the end of the data, and gives you previous contents of the memory.
2,218,033
2,219,480
Cygwin gcc compiled fails in IDE complaining about 'exit' undeclared
When I compile a program using just gcc code.c There are no messages, and an output file is generated successfully. The outputted file works. However, when I try to the same cygwin installation's gcc compiler in an IDE (I've tried Netbeans and Dev-C++), I get the following errors main.cpp:27: error: `exit' undeclared ...
C++ is stricter then C. Where C allows you to call a function without a prototype, C++ does not allow this. To solve the problem, you want to add: #include <stdlib.h> Also, when compiling at the command line. Make sure to use the -Wall flag so you'll get important warnings: gcc -Wall code.c
2,218,100
2,233,748
Error avalanche in Boost.Spirit.Qi usage
I'm not being able to figure out what's wrong with my code. Boost's templates are making me go crazy! I can't make heads or tails out of all this, so I just had to ask. What's wrong with this? #include <iostream> #include <boost/lambda/lambda.hpp> #include <boost/spirit/include/qi.hpp> void parsePathTest(const std::st...
Several remarks: a) don't use the Spirit V2 beta version distributed with Boost V1.39 and V1.40. Use at least Spirit V2.1 (as released with Boost V1.41) instead, as it contains a lot of bug fixes and performance enhancements (both, compile time and runtime performance). If you can't switch Boost versions, read here for...
2,218,140
2,218,157
What requires me to declare "using namespace std;"?
This question may be a duplicate, but I can't find a good answer. Short and simple, what requires me to declare using namespace std; in C++ programs?
Since the C++ standard has been accepted, practically all of the standard library is inside the std namespace. So if you don't want to qualify all standard library calls with std::, you need to add the using directive. However, using namespace std; is considered a bad practice because you are practically importing the...
2,218,159
2,218,179
How to set c console window title
How to set the console window title in C? printf("%c]0;%s%c", '\033', "My Console Title", '\007'); This works only under linux, not in windows. Does anybody know a "cross-platform" solution? (of course not system ( title=blah ))
windows.h defines SetConsoleTitle(). You could use that everywhere, and declare your own function for linux platforms that does the same thing.
2,218,254
2,218,275
Variable initialization in C++
My understanding is that an int variable will be initialized to 0 automatically; however, it is not. The code below prints a random value. int main () { int a[10]; int i; cout << i << endl; for(int i = 0; i < 10; i++) cout << a[i] << " "; return 0; } What rules, if any, apply to initia...
It will be automatically initialized if it's a class/struct instance in which the default constructor initializes all primitive types; like MyClass instance; you use array initializer syntax, e.g. int a[10] = {} (all zeroed) or int a[10] = {1,2}; (all zeroed except the first two items: a[0] == 1 and a[1] == 2) same ap...
2,218,303
2,218,317
c++ operator[] overloading problem (works fine but not for pointers, why?)
Problem with operator[] in c++, i have some class: 197 class Permutation{ 198 private: 199 unsigned int* array; 200 unsigned int size; 201 202 void fill(){ 203 for(unsigned int i=0;i<size;i++) 204 array[i]=i;...
First, your code: Permutation* x=new Permutation(3); x->get(0)=10; // this works fine And then you do this: x[0]=1; And what you are doing is treating the pointer x as an array, and initializing it, which is longhand for: x[0] = Permuation(1); // implicit conversion using Permulation(const unsigned long&) What you ...
2,218,339
2,284,642
Cg shaders not being applied after switch to glVertexPointer
My renderer used to render geometry with the old fixed function stuff using glBegin/glEnd. After switching it to use vertex arrays via glVertexPointer et. al., my Cg shaders stopped showing up. If i just do a regular texture binding, it works fine, so the array data is solid. Also if I use the old glBegin/glEnd system,...
vertex data submission (Begin/End, regular VertexPointer+DrawArrays, VBO+DrawArrays) is supposed to be completely orthogonal to shaders (as long as you provide the data). So you're not really missing anything (especially if it works with VBO). Your problem is likely somewhere that you don't mention.
2,218,435
2,218,475
Why typedef can not be used with static?
Why typedef can not be used with static? For example, the code below is an error typedef static int INT2; What other rules should be follow to use the typedef? What other keywords can not be used with typedef? Thanks so much!
typedef doesn't declare an instance of a variable, it declares a type (type alias actually), static is a qualifier you apply to an instance, not a type, so you can use static when you use the type, but not when you define the type. Like this.. typedef int int32; static int32 foo;
2,218,494
2,218,507
Problem with named constructor with istream as argument
I'm trying to create a named constructor for my class Matrix, with an input as a stream from which I can read the values for the initialization. #include <istream> // ... class Matrix { public: Matrix(int); // some methods static Matrix *newFromStream(istream&); private: int n; std::valarray< Cell...
istream is in the namespace std: static Matrix *newFromStream(std::istream&); The error indicates it's lost once it gets to istream. Change it in both header and source, of course. A couple notes: In your header, use <iosfwd> instead of <istream>, and in your source file use <istream>. This is more "correct" and may s...
2,218,545
2,218,571
Fast Cross Platform Inter Process Communication in C++
I'm looking for a way to get two programs to efficiently transmit a large amount of data to each other, which needs to work on Linux and Windows, in C++. The context here is a P2P network program that acts as a node on the network and runs continuously, and other applications (which could be games hence the need for a ...
boost::asio is a cross platform library handling asynchronous io over sockets. You can combine this with using for instance Google Protocol Buffers for your actual messages. Boost also provides you with boost::interprocess for interprocess communication on the same machine, but asio lets you do your communication async...
2,218,753
2,218,756
declaring generic istream in c++
I need to write a program that reads in either from ifstream or cin, depending on parameters passed into the program at runtime. I was planning on doing the following: istream in; if(argv[1] == "cin") { in = cin; } else { ifStream inFile; inFile.open(argv[1].c_str()); in = inFile; } How...
Try with an istream* instead. Note, however, that you have to change your code slightly. Using pointers you have to preserve the memory area of the object that you're pointing. In other words, the "inFile" variable cannot be declared there, as it won't exist out of the else. The code could be, then: istream* in; ifSt...
2,218,798
2,218,813
What is a good method to have a common interface to code without incurring the cost of dynamic lookup?
I am writing some code for handling data. There are a number of groups of processing functions that can be chosen by the user that are then applied to the dataset. I would like to implement all these groups in separate places, but since they all take the same parameters and all do similar things I would like for them t...
A virtual function call is a function call via a pointer. The overhead is generally about the same as an explicit function call via a pointer. In other words, your idea is likely to gain very little (quite possibly nothing at all). My immediate reaction would be to start with virtual functions, and only worry about som...
2,218,889
2,218,927
C++ functor to output iterator adapter
Given a functor appropriate for use with std::for_each and friends: template <typename T> struct Foo { void operator()(T const& t) { ... } }; std::for_each(v.begin(), v.end(), Foo<Bar>()); Is there some standard way to convert this into an output iterator appropriate for use with std::copy and friends? (or the o...
How about boost::function_output_iterator?
2,218,931
2,227,180
Extension of Binary search algo to find the first and last index of the key value to be searched in an array
The problem is to extend the binary search algorithm to find all occurrences of a target value in a sorted array in the most efficient way. Concretely speaking, the input of the algorithm is (1) a sorted array of integers, where some numbers may appear more than once, and (2) a target integer to be searched. The outpu...
If you are a little clever you can define two different binary search functions. One will return the index of the first appearance of the searched for value and the other will return the last appearance of the searched for value. From your knowledge of binary search, you should be able to determine the maximum and mini...
2,219,146
2,219,159
What should the iterator type be in this C++ template?
While working on some graphics code a while back, I wrote Rect and Region classes using ints as the underlying coordinate holder, and that worked fine. The Region was implemented as a simple class extension to an STL list, and just contains a list of Rects. Now I also need the same kinds of classes using doubles as the...
iterator is a dependent type (it depends on a template argument) and needs to be prefixed with typename: typename std::list< KRect<T> >::iterator i; Better style would be to provide a class-wide typedef: template <typename T> class KRegion : public std::list< KRect<T> > { typedef std::list< KRect<T> > base; ty...
2,219,179
2,219,201
C++ Serve PHP documents?
I am writing a small web server, nothing fancy, I basically just want to be able to show some files. I would like to use PHP though, and im wondering if just putting the php code inside of the html will be fine, or if I need to actually use some type of PHP library? http://www.adp-gmbh.ch/win/misc/webserver.html I just...
PHP needs to be processed by the PHP runtime. I'm assuming the case you're talking about is that you have a C++ server answering HTTP queries, and you want to write PHP code out with the HTML when you respond to clients. I'm not aware of any general-purpose PHP library. The most straightforward solution is probably t...
2,219,239
2,219,246
Difference between these two statements? - C++
I'm a programming student trying to better understand pointers, one of the things I learned is that you can set a pointer to NULL. My question is, what's the difference between these two statements? When would each of them return true/false? if (some_ptr == NULL) if (*some_ptr == NULL) Thanks!
The first does a comparison against the address of the variable to null, the second dereferences the pointer, getting the value held at it and compares it against null.
2,219,243
2,219,253
Odd duplicate symbols error
For a school project, the class was asked to write a String class to mimic the STL string class. I have all the code written, but the linker seems to be caught up on one of my operators. There are three files, String.h, String.cpp, and test2.cpp My Makefile looks like CC=gcc CXX=g++ CXXFLAGS+=-Wall -Wextra LDLIBS+=-lst...
You provided the definitions of the operators in the header file which gets included by both String.cpp and test2.cpp. You should move the definitions into one source file and only provide declarations in the header file. // in String.h: bool operator==(const String& left, const char* right); // in String.cpp: bool op...
2,219,244
2,219,339
Dealing with Floating Point exceptions
I am not sure how to deal with floating point exceptions in either C or C++. From wiki, there are following types of floating point exceptions: IEEE 754 specifies five arithmetic errors that are to be recorded in "sticky bits" (by default; note that trapping and other alternatives are optional and, if provided, non-de...
On Linux you can use the GNU extension feenableexcept (hidden right at the bottom of that page) to turn on trapping on floating point exceptions - if you do this then you'll receive the signal SIGFPE when an exception occurs which you can then catch in your debugger. Watch out though as sometimes the signal gets throw...
2,219,267
2,219,322
Can I make a binary search tree with this?
I've made BSTs before. Can I use this to make a BST without modifications? template <class Item> class binary_tree_node { public: private: Item data_field; binary_tree_node *left_ptr; binary_tree_node *right_ptr; }; I tried making a BST with this but ran into some problems. For one thing, when I crea...
Without modifications, no. But that line 'place public member functions here' is screaming out that you should be modifying it. Since you talk about permission problem, it means you are trying to use free functions. But since the pointers are private, you won't have access to them. What you should be doing is creating...
2,219,351
2,219,819
Access Violation With Pointers? - C++
I've written a simple string tokenizing program using pointers for a recent school project. However, I'm having trouble with my StringTokenizer::Next() method, which, when called, is supposed to return a pointer to the first letter of the next word in the char array. I get no compile-time errors, but I get a runtime er...
This answer is provided based on the edited question and various comments/observations in other answers... First, what are the possible states for pStart when Next() is called? pStart is NULL (default constructor or otherwise set to NULL) *pStart is '\0' (empty string at end of string) *pStart is delim (empty string a...
2,219,557
2,242,426
Bidimensional Hashmaps in Java (and in general)
which is the best way to write a bidimensional hashmap efficiently in Java? Just to give an example of what I'm talking about: I'm developing some algorithms related to collective intelligence, these algorithms works by calculating correlation between pairs of elements.. Without caching these values, since they are cal...
I partially solved the problem by concatenating hashcodes of both items using something like this: private long computeKey(Object o1, Object o2) { int h1 = o1.hashCode(); int h2 = o2.hashCode(); if (h1 < h2) { int swap = h1; h1 = h2; h2 = swap; } return ((long)h1) << 32...
2,219,562
2,219,710
getopt fails to detect missing argument for option
I have a program which takes various command line arguments. For the sake of simplification, we will say it takes 3 flags, -a, -b, and -c, and use the following code to parse my arguments: int c; while((c = getopt(argc, argv, ":a:b:c")) != EOF) { switch (c) { case 'a': ...
See the POSIX standard definition for getopt. It says that If it [getopt] detects a missing option-argument, it shall return the colon character ( ':' ) if the first character of optstring was a colon, or a question-mark character ( '?' ) otherwise. As for that detection, If the option was the last charac...
2,219,600
2,219,629
I can use SetWindowPos to place the window behind another window, but how do I place it in front of a given window?
SetWindowPosition second parameter is hWndInsertAfter which means behind. How do I place a window in front of another (above)?
How about you call SetWindowPos again, swapping the hwnd parameters (so your original window is now the hWndInsertAfter, and the initial hWndInsertAfter is now the hWnd you're moving), and passing in the SWP_NOMOVE flag? Edit: And if the exact position in the Z-order doesn't matter and you just want it in front, don't ...
2,219,669
2,219,776
How to I pass a table from Lua into C++?
How would I pass a table of unknown length from Lua into a bound C++ function? I want to be able to call the Lua function like this: call_C_Func({1,1,2,3,5,8,13,21}) And copy the table contents into an array (preferably STL vector)?
If you use LuaBind it's as simple as one registered call. As for rolling up your own, you need to take a look at lua_next function. Basically the code is as follows: lua_pushnil(state); // first key index = lua_gettop(state); while ( lua_next(state,index) ) { // traverse keys something = lua_tosomething(state,-1); //...
2,219,690
2,219,730
How can I make this work with every delimiter in C++?
I just wrote a program that tokenizes a char array using pointers. The program only needed to work with a space as the delimiter character. I just turned it in and got full credit, but after turning it in, I realized that this program worked only if the delimiter character was a space. My question is, how could I make ...
The simpliest way is to change your while (*pStart != delim) to something like while (*pStart != ' ' && *pStart != '\n' && *pStart != '\t') Or, you could make delim a string, and create a function that checks if a char is in the string: bool isDelim(char c, const char *delim) { while (*delim) { if (*delim ==...
2,219,696
2,219,702
How to know if the user is using multiple monitors
I'm trying to figure out a way to know if the user is using multiple monitors. I would like to know how to do this in native C++ (using the Win32 API) and with managed code (using the .NET Framework). Thanks in advance
I can give you C# .NET: if (Screen.AllScreens.Length > 1) { // Multiple monitors } Edit: A search on Google turned up the following. It mentions 98/ME so it might no be relevant but may point you in the right direction: There are new APIs for handling multiple monitors in Windows 98. The APIs used in the monitors ...
2,219,719
2,219,778
Are structs necessary in binary search trees
I've looked at some code for BSTs and I can see that each node is a struct. Is this necessary?
int flat_tree[ 1000 ][ 3 ]; // for each tree node, value is stored in element [id][0] // id of left_child stored in element [id][1] // id of right_child stored in element [id][2] … I'm not gonna go any further with this. Generally speaking, structs/classes are used f...
2,219,772
2,219,787
Advantage of STL resize()
The resize() function makes vector contain the required number of elements. If we require less elements than vector already contain, the last ones will be deleted. If we ask vector to grow, it will enlarge its size and fill the newly created elements with zeroes. vector<int> v(20); for(int i = 0; i < 20; i++) { ...
It sounds as though you should be using vector::reserve. vector::resize is used to initialize the newly created space with a given value (or just the default.) The second parameter to the function is the initialization value to use.
2,219,872
2,219,929
Is there any way I can access Private member variable of a class?
Is there any way I can access Private member variable of a class? Editing: Not from a member function or friend function but through an instance.
Just cast it around, shift memory and cast back. (didn't compile the code, but you should get the idea). class Bla { public: Bla() : x(15), str("bla") {} private: int x; std::string str; } int main() { Bla bla; int x = *((int*)(&bla)); std::string str = *((std::string*)((int*)(&bla) + 1)); ...
2,219,975
2,220,097
How do I create a resource dll
How do I create a resource dll ? The dll will be having a set of .png files. In a way these .png files should be exposed from the dll. My application would need to refer this dll to get a .png file.
A resource dll is the same as any other dll, it just has little or no code in it, and relatively more resources. Microsoft doesn't have a predefined resource type for PNG files, but you can define your own The most minimal possible resource dll is just a compiled .rc file passed to the linker like this. //save this ...
2,220,166
2,220,491
to program GUI app , what will be the must user and developer frendly toolkit in c++
i like to build desktop application , that will be must user friendly in view what i mean is that the look and feel will be natural in the way the user used to see windows apps . and this toolkit/framework to be as much as possible easy fast to develop from the developer side in c++ .
Could we ask some more questions, what do you mean by user friendly(system integration easy keybingings/Accessibility)? Which platforms(windows only? You seem to indicate this, if so xp-7? Would fairly easy crossplatform support be a plus))? Do you want a form builder? an ide? special libraries? open source or closed...
2,220,230
2,221,470
Is a member of an rvalue structure an rvalue or lvalue?
A function call returning a structure is an rvalue expression, but what about its members? This piece of code works well with my g++ compiler, but gcc gives a error saying "lvalue required as left operand of assignment": struct A { int v; }; struct A fun() { struct A tmp; return tmp; } int main() { fu...
A member of an rvalue expression is an rvalue. The standard states in 5.3.5 [expr.ref]: If E2 is declared to have type “reference to T”, then E1.E2 is an lvalue [...] - If E2 is a non-static data member, and the type of E1 is “cq1 vq1 X”, and the type of E2 is “cq2 vq2 T”, the expression designates the named...
2,220,777
2,220,847
Which is more efficient ? if statement
Which is more efficient if(!var_name) or if(var_name == NULL)
Both will compile to the same code. Your choice of which to use should depend on which is most readable. This version: if(var_name == NULL) should only be used when var_name is a pointer, otherwise you will confuse anyone who reads your code in the future. Some compilers might complain if you use this on a non-point...
2,220,916
2,220,956
Why isn't it legal to convert "pointer to pointer to non-const" to a "pointer to pointer to const"
It is legal to convert a pointer-to-non-const to a pointer-to-const. Then why isn't it legal to convert a pointer to pointer to non-const to a pointer to pointer to const? E.g., why is the following code illegal: char *s1 = 0; const char *s2 = s1; // OK... char *a[MAX]; // aka char ** const char **ps = a; // error!
From the standard: const char c = 'c'; char* pc; const char** pcc = &pc; // not allowed *pcc = &c; *pc = 'C'; // would allow to modify a const object
2,220,975
2,220,990
C++ static template member, one instance for each template type?
Usually static members/objects of one class are the same for each instance of the class having the static member/object. Anyways what about if the static object is part of a template class and also depends on the template argument? For example, like this: template<class T> class A{ public: static myObject<T> obj; } ...
Static members are different for each diffrent template initialization. This is because each template initialization is a different class that is generated by the compiler the first time it encounters that specific initialization of the template. The fact that static member variables are different is shown by this code...