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,287,621
2,287,706
How to calculate length of an UCS-2 string and its size in C++?
I have a string in UCS-2 encoding. I need to copy this string to another UCS-2 string. Before copying I need to calculate the length of a UCS-2 string for memeory allocation. How to calculate length of an UCS-2 string?
UCS2 does not carry information about string length itself. Your original string representation either is 0-terminated, in which case you can just check for a 0 code unit (i.e. a 16-bit 0 value), or it is not 0-terminated, in which case you need some out-of-band information about the length of the string (such as a sep...
2,287,757
2,289,638
Saving a simple image buffer to png in C++
I'd like to do this in a platform independant way, and I know libpng is a possibility, but I find it hard to figure out how. Does anyone know how to do this in a simple way?
There is a C++ wrapper for libpng called Png++. Check it here or just google it. They have a real C++ interface with templates and such that uses libpng under the hood. I've found the code I have written quite expressive and high-level. Example of "generator" which is the heart of the algorithm: class PngGenerator : pu...
2,287,804
2,288,344
pClass1 = (Class1*)pBase->next without (Class1*) cast
class Base { Base* next; } class Class1 : Base { } Base* pBase = new Base(); Class1* pTest = new Class1(); pBase->next = pTest; Class1* pClass1; pClass1 = (Class1*)pBase->next; I want to be able to write pClass1 = pBase->next; and get no compilation error C2440 (cannot convert). Or in other words I w...
template<class T> class Base { T* next; } class Class1 : Base<Class1> { } Class1* pTest1 = new Class1(); Class1* pTest2 = new Class1(); pTest1->next = pTest2; Class1* pClass1; pClass1 = pTest1->next;
2,287,879
2,287,923
Why can't convert TCHAR* to char*
error C2664: 'strcpy' : cannot convert parameter 1 from 'TCHAR *' to 'char *' code: LPCTSTR name, DWORD value strcpy (&this->valueName[0], name); error C2664: 'strlen' : cannot convert parameter 1 from 'LPCTSTR' to 'const char *' LPCTSTR name; strlen (name) The code above to a class which works fine in anoth...
You need to use a function such as wcstombs when _UNICODE is defined. Either that or just use _tcslen (Look under Generic-Text Routine Mappings) on the TCHAR string and the compiler will transfer it to either strlen or wcslen depending if you are using unicode or not.
2,287,922
2,288,252
What library implements asynchronous processing of messages?
Help find a library that implements: 1) Publisher-Subscribers. Publisher sends (SendMessage - not WinAPI function) the message, not knowing how many subscribers will receive it, maybe 0. 2) Asynchronously. If there is a free flow, the subscriber (s) must start in parallel with the code after the SendMessage. 3) Smart p...
Have a look at Boost.Asio
2,287,962
2,288,897
C++ - How to read Unicode characters( Hindi Script for e.g. ) using C++ or is there a better Way through some other programming language?
I have a hindi script file like this: 3. भारत का इतिहास काफी समृद्ध एवं विस्तृत है। I have to write a program which adds a position to each and every word in each sentence. Thus the numbering for every line for a particular word position should start off with 1 in parentheses. The output should be something like this...
I would seriously suggest that you'd use Python for an applicatin like this. It will lift the burden of decoding the strigns (not to mention allocating memory for them and the like). You will be free to concentrate on your problem, instead of problems of the language. For example, if the sentence above is contained in ...
2,288,171
2,288,322
How to get 2 random (different) elements from a c++ vector
I would like to get 2 random different elements from an std::vector. How can I do this so that: It is fast (it is done thousands of times in my algorithm) It is elegant The elements selection is really uniformly distributed
For elegance and simplicty: void Choose (const int size, int &first, int &second) { // pick a random element first = rand () * size / MAX_RAND; // pick a random element from what's left (there is one fewer to choose from)... second = rand () * (size - 1) / MAX_RAND; // ...and adjust second choice to take into...
2,288,238
2,288,384
Converting method signatures
typedef void (__thiscall* LPVOIDPROC) (void); class ClassA { LPVOIDPROC m_pProc; void SetProc(LPVOIDPROC pProc) { m_pProc = pProc; } void OnSomeEvent() { m_pProc(); } } class ClassB { ClassA* pCA; void Proc() { /* ... */ } void Init() { // Assume pCA != NULL pCA->Set((LPVOIDPROC)&ClassB::Pro...
Workaround: typedef void (* CLASSPROC) (void *); template<class T, void (T::*proc)()> void class_proc(void * ptr) { (static_cast<T*>(ptr)->*proc)(); } class ClassA { CLASSPROC m_pProc; void * m_pInstance; public: void SetProc(void *pInstance, CLASSPROC pProc) { m_pInstance = pInstance; ...
2,288,291
2,289,265
Is it a good practice to free memory via a pointer-to-const
There are many questions discussing the details of C and C++ dealing with pointer-to-const deletion, namely that free() does not accept them and that delete and delete[] do and that constness doesn't prevent object destruction. What I am interested on is whether you think it is a good practice to do so, not what the la...
Well, here's some relevant stuff possibly too long to fit into a comment: Some time ago the practice to free memory via a pointer-to-const was plain forbidden, see this dr. Dobb's article, the "Language Law" ( :)) part. There has twice been a relevant discussion on http://groups.google.ru/group/comp.lang.c++.moderated...
2,288,293
2,288,355
Windows & C++: extern & __declspec(dllimport)
What is the difference/relationship between "extern" and "__declspec(dllimport")? I found that sometimes it is necessary to use both of them, sometimes one is enough. Am I right that: "extern" is for statically linked libraries, "__declspec(dllimport)" is for DLL (dynamically linked libraries), both do actually the sa...
extern means that the entity has external linkage, i.e. is visible outside its translation unit (C or CPP file). The implication of this is that a corresponding symbol will be placed in the object file, and it will hence also be visible if this object file is made part of a static library. However, extern does not by i...
2,288,456
2,356,594
Using desktop as canvas on linux
i was wondering if somebody could help me out. I have a plan of making clone of geek tools for linux. But i have no idea if you can somehow use linux desktop as canvas for drawing text etc. I tried to google it up but i found nothing. What i need to do is basically be able to draw text on certain parts of desktop so i...
You already accepted a partial answer, but I hope you will still read this. It is true that the desktop background by convention is the root window. However, there are two important mechanics going on on a typical modern desktop: root pixmap setting (wallpaper), which is not drawn on the background of the root window ...
2,288,692
2,288,727
What happens if I use "throw;" without an exception to throw?
Here's the setup. I have a C++ program which calls several functions, all of which potentially throw the same exception set, and I want the same behaviour for the exceptions in each function (e.g. print error message & reset all the data to the default for exceptionA; simply print for exceptionB; shut-down cleanly for ...
If handle() is called outside the context of an exception, you will throw without an exception being handled. In this case, the standard (see section 15.5.1) specifies that If no exception is presently being handled, executing a throw-expression with no operand calls terminate(). so your application will terminate. T...
2,288,698
2,289,021
Communicating between a ruby script and a running c++ program
I have a c++ program which performs one function. It loads a large data-file into an array, receives an array of integers and performs a lookup in that array, returning a single integer. I am currently calling the program with each integer as an argument, like so: $ ./myprogram 1 2 3 4 5 6 7 I also have a ruby script,...
A possible approach is to modify your C++ program so that it takes its input from the standard input stream (std::cin) instead of from the command line parameters, and returns its result through the standard ouput (std::cout) instead of as main's return value. Your Ruby script would then use popen to launch the C++ pro...
2,288,730
2,288,742
What's the scope of a type declaration within a class?
If a new type is declared whithin a class, like: class foo { public : struct s1 { int a ; }; private : struct s2 { int b ; }; }; then in what scope can the following statements be used: s1 ss1; s2 ss2; Thanks in advance.
The type s1 can be used anywhere, but if used outside of foo's member functions, it must be qualified: foo::s1 ss1; The type s2 can only be used in member functions of foo.
2,288,834
2,288,894
CComVariant vs. _variant_t, CComBSTR vs. _bstr_t
I am using ATL (VS2008, so ATL9 IIRC) to create COM objects and have been using the CComVariant class (defined in atlcomcli.h) to manage VARIANT types. However, there is also another VARIANT wrapper called _variant_t. Is there any difference between CComVariant and _variant_t and which one should I be using? Similarl...
_variant_t and _bstr_t are provided by the compiler as COM support classes and get used when you use constructs like #import . You can use them if you like. CComVariant and CComBSTR are provided by the ATL libraries. Whether you use the COM Support classes or the ATL classes is up to you. If you often need to do opera...
2,288,931
2,288,962
How could I simulate _set_abort_behavior in VC++7 and earlier?
In Visual C++ when terminate() is called the default behavior is to call abort() which by default shows a message box and then - after OK button on the message box is pressed - terminates the application. The "shows message box" part is not very good for programs that must work without human interaction since the progr...
Call the operating system's process terminate function. TerminateProcess() on Windows.
2,288,970
2,289,025
C++: How to build Strings / char*
I'm new to C++. I want to make a char*, but I don't know how. In Java is it just this: int player = 0; int cpu = 0; String s = "You: " + player + " CPU: " + cpu; How can I do this? I need a char*. I'm focusing on pasting the integer after the string.
You almost certainly don't want to deal with char * if you can help it - you need the C++ std::string class: #include <string> .. string name = "fred"; or the related stringstream class: #include <sstream> #include <string> #include <iostream> using namespace std; int main() { int player = 0; int cpu = 0; ost...
2,289,048
2,289,113
ReadWrite lock using Boost.Threads (how to convert this simple class)
I am porting some code from windows to Linux (Ubuntu 9.10). I have a simple class (please see below), which uses windows functions to implement simple mutex locking. I want to use Boost.Threads to reimplement this, but that library is new to me. Can someone point out the changes I need to make to the class below, in or...
I'm not going to re-write all your code for you. However you should look into boost's shared_mutex class. Also, this question from StackOverflow shows how to use a boost::shared_mutex
2,289,128
2,298,805
CallBack function from c# to c++
I have a C# exe and some vc++ dll's . I am creating a callBackFunction in C# whichh takes structure as its Parameters. My c++ dll will fill this structure and return it back.But 95% of the time My Exe crashes. My dll is multi threaded and my C# has backgroundWorker in it. I have put try catch block to check if any exce...
this must work: (c#) namespace Test { public class CallbackClass { public void Callback(string s) { MessageBox.Show(s); } } } (c++/cli) ... Test::CallbackClass::Callback(gcnew System::String("woof!"); ...
2,289,168
2,289,192
Is this code valid, or is it the compiler?
int cpu = 0; int player = 0; char * getPoints() { using namespace std; string str = "You: "; str += player; str += " CPU: "; str += cpu; char c [100]; strcpy(c, str.c_str()); return c; } This code doesn't compile. Is the code wrong or is there something wrong with my compiler? I'm usin...
The errors seem to be from problems with the compiler. Are you sure you have the project set up correctly? The warning about returning a local variable is serious. You allocate the c array on the stack in your function. When the function returns, the array will be gone from the stack and the pointer you returned ends u...
2,289,193
2,289,277
How to test if template parameter is a pair associative container?
Let's imagine I want to make a templated function that returns the first element of any stl container. The general way would be : template<typename Container> Container::value_type first(Container c){ return *(c.begin()); } This works for vectors, lists, deques, sets and so on. However, for pair associative contai...
You can do quite easily: namespace result_of // pillaged from Boost ;) { template <class Value> struct extract { typedef Value type; }; template <class First, class Second> struct extract < std::pair<First,Second> > { typedef Second type; }; } template <class Value> Value extract(Value v) { return v; } templ...
2,289,305
2,289,345
Are there Visual C++ runtime implementations for other platforms?
Does Visual C++ runtime imply Windows platform? I mean if I write a program that only directly uses functions specific to VC++ runtime and doesn't directly call Windows API functions can it be recompiled and run on any OS except Windows? I don't mean on Windows system emulator, I mean a ready implementation of VC++ run...
The Visual C++ runtime contains the standard C++ library and platform specific auxiliary functions. The Windows API is part of the Windows SDK, and is not included in the Visual C++ runtime. When you compile a C++ program on a different platform you will use that platform's C++ library implementation. I mean if I writ...
2,289,389
5,729,795
Can I have platform specific sections in my vsprops (Property Sheet) file?
I'm creating a vsprops file to contain include and lib paths that are common to all projects in my solution. However, I have platform specific paths for the lib paths which can be Win32/x64. Is it possible to put these settings in one vsprops file? Or do I have to create a different vsprops file for each platform and t...
No, there doesn't seem to be a way, I ended up creating two different vs props files.
2,289,481
2,291,475
What is the mistake in my code?
The sample code mentioned below is not compiling. Why? #include "QprogressBar.h" #include <QtGui> #include <QApplication> #include<qprogressbar.h> #include <qobject.h> lass myTimer: public QTimer { public: myTimer(QWidget *parent=0):QTimer(parent) {} public slots: void recivetime(); }; void myTimer::recivetime(...
To sum-up the previous comments and answers: the compiler tells you at least what it does not understand if not straight-up what's wrong with your code => if you don't understand what the compiler says post the error message with your question so that it helps those who speak "compilese" "connect" will connect a objec...
2,289,548
2,289,586
Array indexing starting at a number not 0
Is it possible to start an array at an index not zero...I.E. you have an array a[35], of 35 elements, now I want to index at say starting 100, so the numbers would be a[100], a[101], ... a[134], is that possible? I'm attempting to generate a "memory map" for a board and I'll have one array called SRAM[10000] and anothe...
Is it possible to start an array at an index not zero...I.E. you have an array a[35], of 35 elements, now I want to index at say starting 100, so the numbers would be a[100], a[101], ... a[134], is that possible? No, you cannot do this in C. Arrays always start at zero. In C++, you could write your own class, say Offse...
2,289,569
2,289,926
C++: How to add a library in Netbeans (DarkGDK + DirectX SDK)
I'm trying to learn how to make games with DarkGDK. But I have to write in Visual Studio. I don't like Visual Studio. Its suggestions (Ctrl-Space for Completion) are bad (in my opinion) and the compiler is broken (See my previous questions). So I want to migrate to Netbeans, with MSys and MinGW. But I'm not able to use...
Personally I found the include directories in Tools -> Options don't work. You need to right click on your project and go to properties -> C++ Compiler and add your include directories. Then from properties -> Linker to add your library directories and libraries.
2,289,593
2,289,740
How to select the version of the VC 2008 DLLs the application should be linked to?
I'm using Visual Studio 2008 SP1 for C++. When compiling, Visual Studio needs to choose against which version of the CRT and MFC DLLs the application should be linked, version 9.0.21022.8 (= RTM), 9.0.30729.17 (= SP1) or 9.0.30729.4148 (= SP1 with security update). I'd like to know how you can choose which of both vers...
_BIND_TO_CURRENT_VCLIBS_VERSION sets the current version in the manifest - or the RTM version if not. And setting it in the manifest is the correct way to do this. What you are seeing however is the effects of an assembly policy file :- When the VCRedist package containing the 2008 SP1 runtime is installed, it installs...
2,289,637
2,358,297
Directdraw: Rotate video stream
Problem Windows Mobile / Directdraw: Rotate video stream The video preview is working, all I need now is a way to rotate the image. I think the only way to handle this is to write a custom filter based on CTransformFilter that will rotate the camera image for you. If you can help me to solve this problem, e.g. by helpi...
Well if you look at the EZRGB24 sample you get the basics of a simple video transform filter. There are 2 things you need to do to the sample to get it to do what you want. 1) You need to copy x,y to y,x. 2) You need to tell the media sample that the sample is now Height x Width instead of Width x Height. Bear in min...
2,289,785
2,289,900
Strange Serial MisComunication
Ok, so I have 3 devices. an AVR Butterfly microcontroller, set up with USART A Bifferboard, running Debian, using a custom made program for serial. A Desktop machine running Br@y's. So I'm trying to make the Bifferboard send serial to the AVR, But the AVR never receives the signal, (we've checked the wires). But if i...
(We've checked the wires) This still sounds like a cabling problem. If Br@y's can communicate with both, then it doesn't seem to be a configuration issue. You should throw a logic analyzer or oscilloscope on the receive pin (and probably probe other pins) of the AVR and see what's happening electrically when yo try...
2,289,992
2,290,456
How to hide menu? lpszMenuName
I managed to make the menu with this piece of code and using Visual Studio 2008: WNDCLASS wc; ... wc.lpszMenuName = MAKEINTRESOURCE(IDR_MENU1); ... if(!RegisterClass(&wc)) ... But how i can hide the menu by just pressing a button of my choice? There is ShowWindow() function, but it doesnt work on menus... so what ...
I think you can do something like this: // save the menu HMENU hMenuOld = GetMenu(hWnd); // hide the menu SetMenu(hWnd, NULL); // show the menu SetMenu(hWnd, hMenuOld);
2,290,007
2,294,359
Beginner extending C with Python (specifically Numpy)
I am working on a real time audio processing dynamically linked library where I have a 2 dimensional C array of floating point data which represents the audio buffer. One dimension is time (samples) and the other is channel. I would like to pass this to a python script as a numpy array for the DSP processing and then I...
You may be able to avoid dealing with the NumPy C API entirely. Python can call C code using the ctypes module, and you can access pointers into the numpy data using the array's ctypes attribute. Here's a minimal example showing the process for a 1d sum-of-squares function. ctsquare.c #include <stdlib.h> float mysums...
2,290,154
2,290,227
Multiple DLLs writing to the same text file?
I want to add logging support to a COM object (DLL) of mine, and there are usually at least two instances of this object loaded. I want both of the DLLs to be able to write lines to the same text file but am worried that this is going to give me problems. Is this possible to achieve? Am I right in thinking that a si...
#include <iostream> #include <fstream> #include <windosws.h> struct Mutex { Mutex () { h = ::CreateMutex(0, false, "{any-GUID-1247965802375274724957}"); } ~Mutex () { ::CloseHandle(h); } HANDLE h; }; Mutex mutex; // GLOBAL mutex void dll_write_func() { ::WaitForSingleObj...
2,290,299
2,290,356
Calling a member function from a member function templated argument
Given the following code which I can't get to compile. template < typename OT, typename KT, KT (OT::* KM)() const > class X { public: KT mfn( const OT & obj ) { return obj.*(KM)(); // Error here. } }; class O { public: int func() const ...
The correct syntax is return (obj.*KM)();
2,290,306
2,319,494
boost::thread_group - is it ok to call create_thread after join_all?
I have the following situation: I create a boost::thread_group instance, then create threads for parallel-processing on some data, then join_all on the threads. Initially I created the threads for every X elements of data, like so: // begin = someVector.begin(); // end = someVector.end(); // batchDispatcher = boost::fu...
I believe this is not possible. The solution you want might actually be to implement a producer-consumer or a master-worker (main 'master' thread divides the work in several fixed size tasks, creates pool of 'workers' threads and sends one task to each worker until all tasks are done). These solutions will demand some...
2,290,587
2,290,838
GCC style weak linking in Visual Studio?
GCC has the ability to make a symbol link weakly via __attribute__((weak)). I want to use the a weak symbol in a static library that users can override in their application. A GCC style weak symbol would let me do that, but I don't know if it can be done with visual studio. Does Visual Studio offer a similar feature?...
MSVC++ has __declspec(selectany) which covers part of the functionality of weak symbols: it allows you to define multiple identical symbols with external linkage, directing the compiler to choose any one of several available. However, I don't think MSVC++ has anything that would cover the other part of weak symbol func...
2,290,733
2,290,749
Initialize parent's protected members with initialization list (C++)
Is it possible to use the initialization list of a child class' constructor to initialize data members declared as protected in the parent class? I can't get it to work. I can work around it, but it would be nice if I didn't have to. Some sample code: class Parent { protected: std::string something; }; class Chi...
It is not possible in the way you describe. You'll have to add a constructor (could be protected) to the base class to forward it along. Something like: class Parent { protected: Parent( const std::string& something ) : something( something ) {} std::string something; } class Child : public Parent { priva...
2,290,861
2,290,984
How to render non trivial particles in OpenGL
I have a particle system where the positions and various properties are stored in a vertex buffer object. The values are continuously updated by a CUDA kernel. Presently I am just rendering them using GL_POINTS as flat circles. What I am interested in is rendering these particles are more involved things like 3d ani...
You probably want to use: EXT_draw_instanced. I've never actually used Instancing, but most modern GPUS (GF6 and up I think) allow you to feed the GPU a model and a list of points and have it draw the model at every point. I'll google some more info and see what I come up with.... Well this is the official spec, and i...
2,291,110
2,291,321
How do I improve breaking substitution ciphers programmatically?
I have written (am writting) a program to analyze encrypted text and attempt to analyze and break it using frequency analysis. The encrypted text takes the form of each letter being substituted for some other letter ie. a->m, b->z, c->t etc etc. all spaces and non alpha chars are removed and upper case letters made low...
I'm not sure how constrained this problem is, i.e. how many of the decisions you made are yours to change, but here are some comments: 1) Frequency mapping is not enough to solve a puzzle like this, many frequencies are very close to each other and if you aren't using the same text for frequency source and plaintext, y...
2,291,114
2,291,235
Runtime array bounds checking in C++ built with g++
Is there any way to do array bounds checking in C++ compiled using g++? Valgrind's Memcheck can't detect overflows on arrays allocated on the stack. The GCC extension enabled by -fbounds-checking is only implemented for the C front end. Ideally, the source code shouldn't be modified in any way. Using std::vector, std...
There is a Valgrind tool called SGCheck (formerly known as Ptrcheck) that does check stack array bounds overrun. valgrind --tool=exp-sgcheck <program> <arguments> The tool is still labeled experimental and it comes with several limitations. One of them is: Platforms: the stack/global checks won't work properly on Pow...
2,291,369
2,309,123
Set up Eclipse C++ compiler without auto-install or altering System Path on Windows
I am trying to install a C++ compiler on Eclipse without altering the Path variables as I can't, the machine has limited rights. Eclipse obviously runs fine, it's the build that doesn't, it complains about. The first thing I noticed was a warning that said "Unresolved inclusion" for the libary file stdio.h I added the...
It looks like you're trying to build a simple hello world program using Eclipse/CDT and a development environment and using mingw as the compiler tool chain. I was able to get this working just now without modifying my system path environment variable. This is what I did: I already had Eclipse 3.5 (Galileo) installed...
2,291,533
2,291,668
Bitstream to Float Type Coercion
I'm having trouble getting the following code to work correctly. Using an online IEEE-754 converter, I wrote out (by hand) to the testData.txt file that is read with the bit string that should signify the floating point number 75.5; the actual cout.write does show that the bit string is as I expect as well. However, ...
You are translating the ASCII into bits using the constructor of bitset. That causes your decoded bits to be in the bitset object rather than the union. To get raw bits out of a bitset, use the to_ulong method: #include<climits> #include<iostream> #include<fstream> #include<bitset> int main( int, char** ) { std::...
2,291,551
2,291,568
Question about Inheritance / Method overriding C++
class Class1 { public: void print() { cout << "test" << endl; } void printl() { print(); } }; class Class2 : public Class1 { public: void print() { cout << "test2" << endl; } }; Why does print() not get overridden in Class2, is there any way a function can ...
No. This is the entire reason for virtual functions. Without a virtual method here, when printl() calls print(), it's calling Class1.print(), which prints "test". If you flag the method as virtual, then it will handle it as you were expecting.
2,291,702
2,291,870
Can C++'s value_type be extended from iterator_traits to all types?
I would like to create a construct similar to std::iterator_traits::value_type that can work seamlessly for all types using the same syntax. Imagine we have the following: template <typename T> struct value_type { typedef T type; }; #define VALUE_TYPE(T) typename value_type<T >::type This will work for POD types. ...
You can use SFINAE to detect the presence of the value_type typedef. No need to specialize for individual types (which might not be possible, since you'd be relying entirely on internal implementation details). #include <vector> template <class T> struct has_value_type { typedef char true_type; typedef char fa...
2,291,779
2,292,876
Is Linux Standard Base (LSB) AppChecker reliable?
According to the LSB scanner, my binary is supposedly incompatible with a specific version of Linux because it uses GBLICXX_3.4.9 symbols. But when I tried to run the binary myself on that version, everything seems to work fine... Can a binary even start on a Linux distro if that distro is missing the runtime librarie...
I don't know if I've understood well the question but as far as I know even though you have compiled your program with a modern glibc does not necessarily mean that you won't be able to execute into an older version. The next Linux command: objdump -T "your exe or lib file" | grep GLIB will show you which version of th...
2,291,802
2,291,845
Is there a C++ iterator that can iterate over a file line by line?
I would like to get an istream_iterator-style iterator that returns each line of the file as a string rather than each word. Is this possible?
EDIT: This same trick was already posted by someone else in a previous thread. It is easy to have std::istream_iterator do what you want: namespace detail { class Line : std::string { friend std::istream & operator>>(std::istream & is, Line & line) { return std::getline(is, lin...
2,291,995
2,292,070
use c++ template class from objective c file
I would like to use a C++ class in an objective c application. How to achieve this? Thanks for your helps :)
You can do this using "Objective-C++". You should read Apple's documentation, but the short version is that you may mix C++ and Objective-C in files with the extension ".mm". It's not magic (C++ classes and Objective-C classes are still separate things), but you can now use them in the same code.
2,292,202
2,292,262
While loop with try catch fails at bad cin input
I can't seem to figure out why this falls into a loop after getting non-int input. I've tried cin.flush(), which doesn't seem to exist, cin.clear(), which seems like it should work, even cin.sync() after reading someone else post about it working, but didn't seem to make much sense. Also tried cin.bad(). Thank you very...
You should think carefully what you want to do if user gives invalid input in this case. Usually in these cases the best solution is to read one line from the input and throw it away. Try putting cin.clear() and std::cin.ignore(std::numeric_limits<streamsize>::max(),'\n'); in your catch clause. cin.clear() clears the f...
2,292,245
2,292,500
obtain output of command to parse in in c / MacOSX
I'm working on a Command Line app to help me on launchd tasks to know if a task is running by returning a BOOL, the problem comes when i need to do a command line and obtain the output for further parsing. i'm coding it in C/C++ so i can't use NSTask for it, any ideas on how to achieve the goal? The Command sudo launch...
You'll want to create a pipe from which you can read the output of the program. This will involve using pipe, fork, exec*, and maybe even dup. There's a good tutorial on the linux documentation project.
2,292,294
2,293,741
how do I clean up my lua state stack?
I am using the lua C-API to read in configuration data that is stored in a lua file. I've got a nice little table in the file and I've written a query C-function that parses out a specific field in the table. (yay it works!) It works by calling a few of these kinds of functions over and over: ... lua_getglobal (...);...
As long as your stack doesn't grow without bound, you'll be fine. When you return integer N from the C API into Lua, two things happen: The Lua engine takes the top N values from the stack and considers them as the results of the call. The Lua engine deallocates (and reuses) everything else on the stack. David Seile...
2,292,296
3,283,132
Can somebody recommend a good U3D library?
I need to put some 3D images into PDF files, and PDF uses Universal 3D (U3D) formats. I don't like the U3D Sourceforge project (basically what Intel released after the ECMA standardization effort). Does anybody know of good U3D libraries I could use? I'm using C++ on Microsoft Windows, FWIW.
VCGLib is a mesh processing library that has a U3D exporter and a variety of importers (see http://vcg.sourceforge.net/index.php/Tutorial#File_Formats). MeshLab is a tool built on top of it.
2,292,304
2,292,331
Are there any actively maintained tools that can transform C++ code to xml?
Are there any tools that can transform C++ code to xml, or some other format that would be easier to parse? It would be great if it would also have the option of turning xml back to C++ . I already know of doxygen's xml format ... maybe it's just me, but I don't find it particularly helpful.
Something like gcc xml?
2,292,466
2,292,479
Dynamic memory and inherited structs in C++
Say I have some structs like this: struct A{ int someInt; } struct B : public A{ int someInt; int someOtherInt; } And a class: class C{ A *someAs; void myFunc(A *someMoreAs){ delete [] someMoreAs; } } would this cause a problem: B *b=new B[10]; C c; c.myFunc(b); Because it's deleting b, thinking that it's o...
No memory will leak in this particular case because both A and B are POD (plain old data) and thus their contents do not require any destruction. Still, it is a good practice to always have a virtual destructor in a (base) class that is supposed to be inherited from. If you add a virtual destructor to A, any deletion v...
2,292,468
2,293,375
Class names that start with C
The MFC has all class names that start with C. For example, CFile and CGdiObject. Has anyone seen it used elsewhere? Is there an official naming convention guide from Microsoft that recommends this style? Did the idea originate with MFC or was it some other project?
Something a bit similar is used in Symbian C++, where the convention is that: T classes are "values", for example TChar, TInt32, TDes R classes are handles to kernel (or other) resources, for example RFile, RSocket M classes are mixins, which includes interfaces (construed as mixins with no function implementations). T...
2,292,647
2,292,678
memory allocation and inherited classes in C++
Say I have these structs: struct Base{ ... } struct Derived:public Base{ //everything Base contains and some more } I have a function in which I want to duplicate an array of these and then alter it. void doStuff(Base *data, unsigned int numItems){ Base *newdata = new Base[numItems]; memcpy(newdata, data, numItem...
You could do this easily with a template: template< class T >void doStuff(T *data, unsigned int numItems) { T *newdata = new T[numItems]; memcpy( newdata, data, sizeof( T ) * numItems ); ... delete [] newdata; } Edit as per the comments: If you wanted to do this for a mixed collection things will get m...
2,292,701
2,292,738
What Visual C++ setting/option/flag is the counterpart of -ansi -pedantic in g++
I have a C++ codebase, and I am porting from Visual Studio to g++, which should I set in Visual Studio so that build errors in gcc are reduced? With g++ this is achieved by -ansi -pedantic.
I believe you are looking for /Za.
2,292,898
2,292,905
Help rearranging /solving an Equation
I have the following C formula bucket = (hash - _min) * ((_capacity-1) / range()); What I need to to rearrange the equation to return the _capacity instead of bucket (I have all other variables apart from _capacity). e.g. 96 = (926234929-805306368) * (( x -1) /1249540730) 836 = (1852139639-805306368) * ((x -1) /124954...
capacity = (range() * bucket) / (hash - _min) + 1; bucket = (hash - _min) * ((_capacity - 1) / range()); // start bucket = ((hash - _min) * (_capacity - 1)) / range(); // rearrange range() * bucket = (hash - _min) * (_capacity - 1); // multiply by range (range() * bucket) / (hash - _min) = _capacity - 1; // divide by...
2,292,995
2,293,006
c++ allocation on the stack acting curiously
Curious things with g++ (maybe also with other compilers?): struct Object { Object() { std::cout << "hey "; } ~Object() { std::cout << "hoy!" << std::endl; } }; int main(int argc, char* argv[]) { { Object myObjectOnTheStack(); } std::cout << "===========" << std:...
The first type of construction is not actually constructing the object. In order to create an object on the stack using the default constructor, you must omit the ()'s Object myObjectOnTheStack; Your current style of definition instead declares a function named myObjectOnTheStack which returns an Object.
2,293,231
2,293,411
sizeof(...) = 0 or conditional variable declaration in c++ templates
Suppose I have something like this: struct EmptyClass{}; template<typename T1, typename T2 = EmptyClass, typename T3 = EmptyClass, typename T4 = EmptyClass, ..., typename T20> class PoorMansTuple { T1 t1; T2 t2; ... T20 t20; }; Now, I may waste up to 19bytes per PoorMansTuple. Question is: 1)...
Partial specialization may be what you are looking for the first part of the question. This program #include <string> #include <iostream> struct EmptyClass {}; template<typename T1, typename T2> class Tuple { T1 t1; T2 t2; }; template<typename T1> class Tuple <T1, EmptyClass> { T1 t1; }; int main (void) {...
2,293,270
2,293,286
Is there any keyword to redefine "all" methods of templated base class in a templated derived class?
I know this looks like a silly question, but using object oriented stuff with templates in C++ is really troublesome. For example, Foo is the base class: template <typename T> class Foo { public: virtual void Method1() { } virtual void Method1(int a) { } virtual void Method2() { } virtual void Method2...
No, there is no functionality like that but it usually isn't needed. What you intend to do with using is already provided by the basic inheritance mechanism. You need to use using if overloads in the deriving class hide methods from the base class or if you want to change the access mode, but not in general: class A ...
2,293,338
2,293,366
Possible to pass name as argument to c++ template?
Is it possible to write a class: template<typename T, ... name> struct Magic { T name; }; such that: Magic<int, foo> gives: Magic<int, foo> { int foo; } and Magic<float, bar> gives: Magic<float, bar> { float bar; } Basically, I want to be able to specify not only the Type, but also the name of the member var...
That is not possible, you have to resort to either macro-based solutions or use a predefined set of types that provide named members. A possible macro-based approach: #define MAGIC(name_) \ template<typename T> struct Magic1 { \ T name_; \ }; MAGIC(foo); or: #define MAGIC(type_, name_) \ struct Ma...
2,293,404
2,293,437
Simple modular guide in C/++?
I think modular is the correct term; to give a basic example if I was to create an encryption application which you could type in like notepad, and then save encrypted, however under the save menu there are options to save for the encryption methods that you have plugins for like AES, Blowfish etc, and also allow new m...
Assuming Win32api, you do something like this: Have a plugins directory for your application. On load of your application, list all files in that directory Any with the extension DLL, you load with the LoadLibrary call. You get some information from the dll that tells you what the plugin's name is You create menus/ui ...
2,293,481
2,293,490
Understanding c++ code; what do *datatype and classname::method mean?
I am new to C++ and I am trying to understand some code. What does it mean to have a * in front of the datatype ? and why is the class Name in front of the method name CAStar::LinkChild void CAStar::LinkChild(_asNode *node, _asNode *temp) { }
A * in front of the data type says that the variable is a pointer to the data type, in this case, a pointer to a node. Instead of passing a copy of the entire "node" into the method, a memory address, or pointer, is passed in instead. For details, see Pointers in this C++ Tutorial. The class name in front of the met...
2,293,670
2,301,029
C++ Swapping an array of integers passed through an int& parameter
I need to swap a couple of integers in the format int i[2] using a void swap(int& x) function. As you see the function takes an argument of type int&. Here is non-working version of the function: int i[2] = {3, 7}; void swap (int& x) { int temp; temp = x[1]; x[1] = x[0]; x[0] = temp; } int main() { ...
All right, thanks to @gf's suggestions, I found a solution :) Many thanks! Please tell me if you see anything not very C++ish in there. // Swap integers #include<iostream> using namespace std; int i = 3; int j = 7; void swap (int& x, int& y) { int temp = x; x = y; y = temp; } int main() { cout << i...
2,293,796
2,293,926
PODs, non-PODs, rvalue and lvalues
Could anyone explain the details in terms of rvalues, lvalues, PODs, and non-PODs the reason why the first expression marked below is not ok while the second expression marked below is ok? In my understanding both int() and A() should be rvalues, no? struct A {}; int main() { int i; A a; int() = i; //Not OK (...
Rvalues are what you get from expressions (a useful simplification taken from the C standard, but not worded in C++ standardese). Lvalues are "locator values". Lvalues can be used as rvalues. References are always lvalues, even if const. The major difference of which you have to be aware can be condensed to one item...
2,293,923
2,293,951
IDirect3DTexture9::SetData?
In XNA, you can do texture = new Texture2D( GraphicsDevice, width, height ) ; I'm guessing somewhere deep down in the MSFT bowels, this is equivalent to C++ code: D3DXCreateTexture( GraphicsDevice, width, height, 1, 0, D3DFMT_A8R8G8B8, D3DPOOL_MANAGED, &texture ) ; In XNA there's this nifty function that lets you set...
I found it.. IDirect3DTexture9::LockRect()
2,293,961
2,293,999
c++ methods in a base class
When having a base class with pure virtual methods this makes it so that the class can not be instantiated. If I have regular methods and attributes in this base class does the derived classes still inherit those as normal? For e.g. a getter and setter for an attribute.
Yes, all methods are inherited.
2,293,970
2,293,978
error: expected unqualified-id before ‘for’
The following code returns this: error: expected unqualified-id before ‘for’ I can't find what is causing the error. Thanks for the help! #include<iostream> using namespace std; const int num_months = 12; struct month { string name; int n_days; }; month *months = new month [num_months]; string m[] = {"Jan"...
Your for loop is outside a function body.
2,293,979
2,311,558
Encoded character buffer storage problem in MySQL varchar using C
I have a encoded character buffer array of size 512 in C, and a database field of varchar in MySQL. Is it possible to store the encoded character buffer into varchar? I have tried this, but the problem which I face is that it only stores the limited area of the buffer into the database and ignore. What is the actual pr...
It is not clear what you mean by encoded. If you mean that you have an arbitrary string of byte values, then varchar is a bad fit because it will attempt to trim trailing spaces. A better choice in such cases is to use varbinary fields. If the string you are inserting contains control characters, you might be best co...
2,294,003
2,294,015
How do I declare the size of a string array if it's a member function
I have a problem with setting the size of my array. In my code I have: class Test { public: ....//Functions private: string name[]; }; Test() { //heres where i want to declare the size of the array } Is this possible?
No. But you could use a vector of strings instead: private: std::vector<std::string> name; Then in your constructor: Test() : name(sizeOfTheArray) { } The vector will be sized for the number of strings you specify. This means all memory for the strings will be allocated at once. You can change the size of th...
2,294,032
2,294,086
algorithm to find edges using vertices (2D and 3D) in a mesh
I have a a mesh, with certain types of elements (e.g. triangular, tetra). For each element I know all its vertices i.e. a triangular 2D element will have 3 vertices v1, v2 and v3 whose x,y,z coords are known. Question 1 I am looking for an algorithm that will return all the edges... in this case: edge(v1, v2), edge(v1...
You can use the half-edge data structure. Basically your mesh also has a list of edges, and there is one edge structure per pair of verts in each direction. That means if you have verts A and B then there are two edge structures stored somewhere, one for A->B and one for B->A. Each edge has 3 pointers, one called prev...
2,294,300
2,294,321
What does 'Font(..)' mean when Font is a class?
I need help in understanding the following C++ code (in a .h file): bool setFontDescription(const FontDescription& v) { if (inherited->font.fontDescription() != v) { inherited.access()->font = Font(v, inherited->font.letterSpacing(), inherited->font.wordSpacing()); return true; ...
Create a Font object on stack, as a temporary. The object's scope is the line where it's created.
2,294,306
2,294,400
Byte array to UTF8 CString
I'm using Visual Studio 2008 (C++). How do I create a CString (in a non-Unicode app) from a byte array that has a string encoded in UTF8 in it? Thanks, kreb EDIT: Clarification: I guess what I'm asking is.. CStringA doesn't seem to be able to interpret a UTF8 string as UTF8, but rather as ASCII or the current codepag...
CStringW filename= CA2W(null_terminated_byte_buffer, CP_UTF8) should do the trick.
2,294,443
2,294,931
Base Conversion Problem
I'm trying to convert an integer to a string right now, and I'm having a problem. I've gotten the code written and working for the most part, but it has a small flaw when carrying to the next place. It's hard to describe, so I'll give you an example. Using base 26 with a character set consisting of the lowercase alphab...
If I understand correctly what you want (the numbering used by excel for columns, A, B, .. Z, AA, AB, ...) this is a based notation able to represent numbers starting from 1. The 26 digits have values 1, 2, ... 26 and the base is 26. So A has value 1, Z value 26, AA value 27... Computing this representation is very s...
2,294,646
2,294,776
Strange vector initialization issue
I recently debugged a strange C++ problem, in which a newly declared vector somehow had a size of 477218589. Here's the context: struct Triangle { Point3 a,b,c; Triangle(Point3 x, Point3 y, Point3 z) : a(x), b(y), c(z) {} Vector3 flat_normal() { return (a-c)^(b-c); } }; vector<Triangle> triangles; Calling...
This #include <vector> #include <iostream> struct Point3 {}; struct Triangle { Point3 a,b,c; Triangle(Point3 x, Point3 y, Point3 z) : a(x), b(y), c(z) {} }; int main() { std::vector<Triangle> triangles; std::cout << triangles.size() << '\n'; return 0; } prints 0 for me. If it also does for you...
2,294,665
2,294,678
Linker error LNK2019 while trying to compile prog with template declarations
Here the code #include <iostream> #include <conio.h> using namespace std; template <typename T> class grid { public: grid(); ~grid(); void createCells(); private: T **cells; }; int main(int argc, char **argv) { grid<int> intGrid; _g...
You need to define the constructor and destructor (you just declared them): template <typename T> class grid { public: grid() {} // here ~grid() {} // and here void createCells(); private: T **cells; };
2,294,809
2,294,851
Going from Java imports to C++ includes
I've been struggling with understanding how C++ classes include other classes. I'm guessing this is easier to understand without any preconceived notions. Assume my two classes are Library and Book. I have a .h and .cpp file for each. My "main.cpp" runs a simple console app to use them. Here is a simple example: ...
In C++ source files are conceptually completely separate from class definitions. #include and header files work at a basic text level. #include "myfile" simply includes the contents of the file myfile at the point at which the include directive is placed. Only after this process has happened is the resulting block of t...
2,294,908
2,294,965
operator bool() converted to std::string and conflict with operator std::string()
How can operator bool() cause an error when declaring operator std::string in a class and also serving as an implicit conversion to string by itself? #include <iostream> #include <string> using namespace std; class Test { public: operator std::string() { cout << "op string" << endl; return "whatever";} operato...
The problem you are facing (besides operator std::string() returning a bool) is that implicit conversions trigger when you want and when you don't. When the compiler sees s = t it identifies the following potential std::operator= matches: // using std::string for compactness instead of the full template std::string::op...
2,295,011
2,295,029
Preventing implicit cast of numerical types in constructor in C++
I have a constructor of the form: MyClass(int a, int b, int c); and it gets called with code like this: MyClass my_object(4.0, 3.14, 0.002); I would like to prevent this automatic conversion from double to int, or at least get warnings at compile time. It seems that the "explicit" keyword does not work in these case, r...
What's your compiler? Under gcc, you can use -Wconversion to warn you about these types of conversions.
2,295,296
2,295,373
Debugging memory leaks with libMallocDebug
I want to use the MallocDebug app to find some memory leaks in my app. I'm running Mac OS X 10.6.2. Whenever I try and following the instructions listed in this guide, I get the following error: dyld: could not load inserted library: /usr/lib/libMallocDebug.A.dylib Trace/BPT trap I have verified that the .dylib file ...
libMallocDebug is not available for 64-bit executables. % lipo -info /usr/lib/libMallocDebug.A.dylib Architectures in the fat file: /usr/lib/libMallocDebug.A.dylib are: i386 ppc7400 It does appear to work with 32-bit executables in 10.6, though, for example: % lipo -thin i386 /bin/ls -out foo % DYLD_INSERT_LIBRAR...
2,295,297
2,295,346
Why does this C++ code fail?
I have the following code #include <iostream> #include <vector> using namespace std; int distance(vector<int>& set1, vector<int>& set2) { int distance = 0; unsigned int i1 = 0; unsigned int i2 = 0; while(i1 < set1.size() && i2 < set2.size()) { if(set1[i1] == set2[i2]) { ++i1; ++i2...
Youd distance function is clashing with the one in std. That's why it's usually not recommended to write using namespace std; in your code. Try removing that or renaming your function to something like my_distance.
2,295,440
2,295,502
C++ Exception Handler problem
I written an exception handler routine that helps us catch problems with our software. I use SetUnhandledExceptionFilter(); to catch any uncaught exceptions, and it works very well. However my handler pop's up a dialog asking the user to detail what they were doing at the time of the crash. This is where the problem c...
Perhaps you could launch a separate data collection process using CreateProcess() when you detect an unhandled exception. This separate process would prompt the user to enter information about what they were just doing, while your main application can continue to crash and terminate. Alternatively, if you don't want to...
2,295,582
2,295,591
Template class won't build properly
Header class linkNode { public: linkNode(void *p) { before = 0; after = 0; me = p; } linkNode *before; void *me; linkNode *after; }; template <class T> class list { public: list(void) { first = last = NULL; siz...
C++ does not really support the separate compilation of templates - you need to put all your template code in the header file(s).
2,295,639
3,423,041
Why is event handling in native Visual C++ deprecated?
http://msdn.microsoft.com/en-us/library/ee2k0a7d.aspx Event handling is also supported for native C++ classes (C++ classes that do not implement COM objects), however, that support is deprecated and will be removed in a future release. Anyone knows why? Couldn't find any explanation for this statement.
It's totally non-standard kludge that probably has very little actual users. And I mean non-stndard kludge even in WinNT and Microsoft-private world. COM has much richer repertoire for event-like mechanisms and also allow fully multi-threaded code these days This one is lethal - that functionality is doing implicit lo...
2,295,969
2,296,104
Visual Studio 2010 and boost::bind
I have this simple piece of code that uses boost::bind: #include <boost/bind.hpp> #include <utility> #include <vector> #include <iterator> #include <algorithm> int main() { std::vector<int> a; std::vector<std::pair<bool,int> > b; a.push_back(1); a.push_back(2); a.push_back(3); std::transform(...
Update: The problem is that make_pair seems to be overloaded in the STL that ships with VS2010 (it wasn't in previous versions of VS or in GCC). The workaround is to make explicit which of the overloads you want, with a cast: #include <boost/bind.hpp> #include <utility> #include <vector> #include <iterator> #include <a...
2,295,994
2,296,020
performance: sorting 'm' vectors with N/m elems Vs sorting single vector with N elements
Operation A I have N vectors, each containing certain number of unique 3D points. For Example : std::vector<double*> vec1; and like that I am performing sort operation on each of the vector like: std::sort(vec1.begin(), vec1.end(), sortCriteria()); std::sort(vec2.begin(), vec2.end(), sortCriteria()); std::sort(vec3....
Sorting is an O(n log n) operation. Sorting N vectors with m/N elements will become strictly faster than sorting a single vector of m elements as you increase m. Which one is faster for any fixed m can only be determined by profiling.
2,296,101
2,296,177
File version information
How can I add version information to a file? The files will typically be executables, .so and .a files. Note: I'm using C++, dpkg-build and Ubuntu 8.10 if any of those have support for this.
For shared objects pass -Wl,soname,<soname> to gcc, or -soname <soname> to ld. Executables and static libraries do not have version information per se, but you can add it to the filename if you like.
2,296,106
2,296,121
Non static members as default parameters in C++
I'm refactoring a large amount of code where I have to add an extra parameter to a number of functions, which will always have a value of a member of that object. Something like class MyClass { public: CMyObject A,B; void MyFunc(CMyObject &Object); // used to be void MyFunc(); }; Now, I'd actually like it t...
How about : class MyClass { public: CMyObject A,B; void MyFunc() { MyFunc(A); } void MyFunc(CMyObject &Object); }; ?
2,296,129
2,296,145
Array of classes. Stack or heap?
class temp; temp *t; void foo() { temp foo2; t[1] = foo2; } int main() { t = new temp[100]; foo(); //t[1] is still in memory? } If i want an array of classes like this, am i going to have to use pointer to pointer? (and use 'new' on each element in the array) E.G: temp **t; if i want to make an array...
The code: t = new temp[100]; constructs an array 100 objects of type temp. A safer way to do the same thing is: std::vector <temp> t(100); which absolves you of ever having to call delete[] on the array.
2,296,577
2,296,588
When object is constructed statically inside a function, would it be allocated on the heap or on the stack?
if i have the following code: for (...) { A a; } would a be allocated on the heap or on the stack?
On the stack. Memory is only allocated on the heap when doing new (or malloc and its friends if you are doing things C-style, which you shouldn't in C++).
2,296,634
2,296,663
DRYing c++ structure
I have a simple c++ struct that is extensively used in a program. Now I wish to persist the structure in a sqlite database as individual fields (iow not as a blob). What good ways are there to map the attributes of the struct to database columns?
Since C++ isn't not a very "dynamic" language, it is running short of the kinds of ORM's you might commonly find available in other languages that make this task light work. Personally speaking, I've always ended up having to write very thin wrapper classes for each table manually. Basically, you need a structure that...
2,296,918
2,297,106
Calling WNetAddConnection2 with empty local name
I have a small program that simply checks if a specified file is located on a specified network drive that is not mapped on the computer. To check this I temporarily map to the network location, check if the file exists and than unmap the drive. I now figured out that I can call WNetAddConnection2 with an empty local n...
Ok, figured it out. I can call WNetCancelConnection2(nr.lpRemoteName, 0, TRUE); to unmap the drive properly.
2,297,059
2,307,798
Release management system for Linux
What we need in our firm is a sort of release management tool for Linux/C++. Our products consist of multiple libraries and config files. Here I will list the basic features we want such system to have: Ability to track dependencies, easily increase major versions of libraries whose dependencies got their major versio...
In the project I'm currently working on we use cmake and other Kitware tools to handle most of this issues for native code (C++). Answering point by point: The cmake scripts handle the dependencies for our different projects. We have a dependency graph but I don't know if is a home-made script or it is a functionality...
2,297,064
2,297,160
Typedeffing a function (NOT a function pointer)
typedef void int_void(int); int_void is a function taking an integer and returning nothing. My question is: can it be used "alone", without a pointer? That is, is it possible to use it as simply int_void and not int_void*? typedef void int_void(int); int_void test; This code compiles. But can test be somehow used or ...
What happens is that you get a shorter declaration for functions. You can call test, but you will need an actual test() function. You cannot assign anything to test because it is a label, essentially a constant value. You can also use int_void to define a function pointer as Neil shows. Example typedef void int_void(i...
2,297,164
2,308,670
STL deque accessing by index is O(1)?
I've read that accessing elements by position index can be done in constant time in a STL deque. As far as I know, elements in a deque may be stored in several non-contiguous locations, eliminating safe access through pointer arithmetic. For example: abc->defghi->jkl->mnop The elements of the deque above consists of a ...
I found this deque implementation from Wikipedia: Storing contents in multiple smaller arrays, allocating additional arrays at the beginning or end as needed. Indexing is implemented by keeping a dynamic array containing pointers to each of the smaller arrays. I guess it answers my question.
2,297,363
2,297,493
What alternatives to the Windows registry exist to store software configuration settings
I have a C++ MFC app that stores all of its system wide configuration settings to the registry. Previously, we used .INI files, and changed over to using the registry some years back using SetRegistryKey("MyCompanyName"); We now get regular support calls from users having difficulty migrating from PC and Windows ver...
I suggest moving over to an XML file in the same location as the executable. One benefit is that XML is portable across non-Windows machines (and even between Windows versions). Edit: The idea behind an XML configuration file in the same location as the executable is that the configuration file is for program configur...
2,297,390
2,297,415
How can the order of inherited includes be controlled in vsprops Property Sheets?
I'm using some vsprops sheets that inherit from each other. My base property sheet defines some include paths. In a second vsprops file that inherits from it, I want to add some more include paths. However, I want to be able to choose whether the additional include paths come before or after the base include paths. I'm...
Ok, found it now: $(Inherit) is what I want, as in this example: c:\test2;$(Inherit);c:\mystuff See: http://msdn.microsoft.com/en-us/library/hx1tt59t(VS.80).aspx
2,297,402
2,297,498
Element is removed from QList but static counter of existing objects doesn't decrease
I have question about removing element from QList. "myclass.h": class node2D : public QObject { Q_OBJECT public: node2D(){++s_NCount;}; ~node2D(){--s_NCount;}; int checkCount(){return s_NCount;}; private: static int s_NCount; }; "myclass.cpp": int node2D::s_NCount = 0; "main.cpp": void main() {...
but shouldn't node2D objects be automatically deleted while Nlist->clear()? Not at all. What if i want to use these objects somewhere else, which is the case mostly for me. Managing the objects pointed by the pointers you add to the list is your concern, not QList's. Managing the copies of these pointers is on the ot...
2,297,567
2,297,584
where should "include" be put in C++
I'm reading some c++ code and Notice that there are "#include" both in the header files and .cpp files . I guess if I move all the "#include" in the file, let's say foo.cpp, to its' header file foo.hh and let foo.cpp only include foo.hh the code should work anyway taking no account of issues like drawbacks , efficienc...
As a rule, put your includes in the .cpp files when you can, and only in the .h files when that is not possible. You can use forward declarations to remove the need to include headers from other headers in many cases: this can help reduce compilation time which can become a big issue as your project grows. This is a...
2,297,962
2,298,001
extend boost.asio file i/o for linux
According to this question about the topic there is no asynchronous file io in asio anything but Windows... So fine, does anyone know of any already written extensions to asio that do asynchronous file io on Linux? Or does anyone know of any examples on how to extend asio to support asynchronous io to {insert-whatever-...
My guess is that if this was easy to do, they would have done it.
2,298,099
2,298,120
Why isn't C++ strtok() working for me?
The program is supposed to receive an input through cin, tokenize it, and then output each one to show me that it worked properly. It did not. The program compiles with no errors, and takes an input, but fails to output anything. What am I doing wrong? int main(int argc, char* argv[]) { string input_line; while(st...
Looks like you forget to copy the contents of input_line to pch: strcpy(pch, input_line.c_str()); But I'm not sure why you're doing string tokenization anyway. Doing cin >> input_line will not read a line, but a token.. so you get tokens anyway?