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
7,766,281
7,766,312
How to access variale defined in different class in c++
I am using xerces library to parse xml in C++ storing xml elements into string array, I want to access this string array from my class code of Handler class - #include "MySAX2Handler.hpp" #include <xercesc/sax2/Attributes.hpp> #include <iostream> #include <string> using namespace std; const int MAXITEMS = 100; string...
resultArray is a global variable with external linkage, so you can already access it from anywhere in your program. You just have to declare it: // someotherfile.cpp extern std::string resultArray[100]; void foo() { std::cout << resultArray[12] << std::endl; }
7,766,523
7,766,996
How do I populate a listbox in MFC with data from an XML file?
I was just wondering if it was possible to populate a listbox with data from an a xml file? If anyone could help me out here I would be extremeley grateful. Thanks.
Use the AddString member function to add an item to the CListBox. For parsing the XML there are a lot of different parsers to use. TinyXML, RapidXml, for instance.
7,766,771
7,766,848
Conversion constructor with responsibility transfer
This is a follow up of this question. I need to implement a conversion operation to pass responsibility for a member object from one object to another. The conversion operation takes place in a class hierarchy. There is a Base class and two deriving classes, say Child1 and Child2. In the Base class, there is a dynamica...
I think you need to look at reference-counted objects. Essentially, the object itself tracks it's usage itself, and instead of storing a raw pointer to the object, you use a reference-counted pointer. Scott Meyers talks about this here: http://www.aristeia.com/BookErrata/M29Source.html As you're on an embedded system,...
7,766,799
7,766,850
Is it possible to compile c++ without any lib?
Is it possible to compile c++ without any lib? Because when i was trying to compile my program with Mingw and cygwin after the .exe file was made i couldn't run it and it said there is a missing library. For cygwin it was "cygwin1.dll".
Binaries that are build with Cygwin always has dependency on cygwin1.dll. Hovewer, if you want to avoid this, use linker option -mno-cygwin. This way you'll make sure that there will be no dependency on cygwin runtime library that you need to ship with your app. MinGW has some local dependencies too. In particular, lib...
7,766,942
7,767,275
Visual Studio 2010: When creating new project vs2010 wants to open html file of wizard
As title says when I'm creating new project in vs2010 it wants to open wizard html in browser. The file it wants to open: file:///C:/Program Files/Microsoft Visual Studio 10.0/VC/VCWizards/AppWiz/Generic/Application/html/1033/default.htm So in the end I can't create project. Any ideas what can be wrong? I'm using ...
Uninstalling old Internet Explorer 8 and installing Internet Explorer 9 solved this problem.
7,766,979
7,767,006
invalid handle exception when debugging
I have following message while I am in debug mode in Visual studio 2010 Unhandled exception at 0x76c5f9e2 in test.exe: 0xC0000008: An invalid handle was specified.When I run this in regular mode I don't get this error. The debugger stops in close.c at this line CloseHandle( (HANDLE)_get_osfhandle(fh) ) ) Does anyone h...
Don't handle this exception, but avoid the situation were you pass an invalid handle! Edit: In debug mode, the code gives you a hint that something is wrong. So you should fix that error instead of handle the exception afterwords!
7,767,036
7,767,109
How do I get the number of displays in windows?
I want to count the number of active displays. For Mac I can use the following: CGDisplayCount nDisplays; CGGetActiveDisplayList(0,0, &nDisplays); log.printf("Displays connected: %d",(int)nDisplays); How can I achieve the same in Windows? I've found EnumDisplayMonitors but I can't work out how to use it.
As you have discovered, EnumDisplayMonitors() will do the job but it is a little tricky to call. The documentation states: The EnumDisplayMonitors function enumerates display monitors (including invisible pseudo-monitors associated with the mirroring drivers) that intersect a region formed by the intersection of a spe...
7,767,202
7,767,481
Template specialization with variadic templates
template <size_t size, typename ...Params> void doStuff(Params...) { } template <> void doStuff<size_t(1), int, bool>(int, bool) { } int main(int, char**) { doStuff<1,int,bool>(1, false); return 0; } This doesn't compile, the second doStuff declaration gives me error: template-id ‘doStuff<1u, int, bool>’ fo...
The syntax is correct (afaik, and clang++ accepts it), but your compiler is probably just not up2date yet. If you use gcc, its variadic template support is quite incomplete, and even very recent svn versions don't support specialization yet (That is just how it is when you use bleeding edge technology, and sadly gcc im...
7,767,328
7,767,469
Using 'new' keyword with struct in c++
#include "PQueue.h" struct arcT; struct coordT { double x, y; }; struct nodeT { string name; coordT* coordinates; PQueue<arcT *> outgoing_arcs; }; struct arcT { nodeT* start, end; int weight; }; int main(){ nodeT* node = new nodeT; //gives error, there is no constructor } My purpose is...
PQueue<arcT *> does not have an appropriate default constructor, so a default constructor for nodeT cannot be generated by the compiler. Either make an appropriate default constructor for PQueue<arcT *> or add a user-defined default constructor for nodeT which constructs outgoing_arcs appropriately.
7,767,626
7,767,726
Two phase lookup - explanation needed
What does it mean that compiler is using two phase lookup in order to compile template class?
Templates are compiled (at least) twice: Without Instantiation the template code itself is checked for syntax. Eg: Any syntax errors such as ; etc. At the time of instantiation(when the exact type is known), the template code is checked again to ensure all calls are valid for that particular type. Eg: The template mi...
7,767,998
7,768,053
Should std::sort work with lambda function in c++0x/c++11?
I tried to use lambda function with sort, but was getting "Segmentation fault" errors. I managed to simplify the code to the following: #include <iostream> #include <algorithm> int main() { const int len = 18; int intArr[len]; for (int i=0;i<len;i++) intArr[i]=1000+i; // The following is expected to sort all b...
The comparison predicate should return a bool: true if a < b and false otherwise. Change the return statement to: return a < b; Not to be confused with C-style 3-way comparison functions. NOTE: Though C++20 does introduce a 3-way comparison operator <=>, sort would still expect a 2-way compare predicate.
7,768,080
7,768,169
How to make a class object a checking condition in C++?
Boost has something like this: void OnAccept( const boost::system::error_code & ec) { if( ec ) { ... } } error_code is a class. What operator to override to make a class object
You should use the safe bool idiom. This protects from most pitfalls that occur when you simply provide a conversion to bool. To provide some context: If a type can be implicitly converted to bool through operator bool() const, a value of that type can be used in comparison expressions where this conversion doesn't mak...
7,768,158
8,555,830
adjacency_list with VertexList different from vecS
I have two structs containing some fields: struct MyNodeData, and struct MyEdgeData. When I create a graph with VertexList as vecS, there is no problem to access the descriptor of vertices etc. For example: typedef adjacency_list<setS, vecS, undirectedS, MyNodeData, MyEdgeData> Graph; typedef Graph::vertex_descriptor ...
Currently, you just need to provide an associative property map. <...> typedef Graph::vertex_descriptor NodeID; typedef map<NodeID, size_t> IndexMap; IndexMap mapIndex; associative_property_map<IndexMap> propmapIndex(mapIndex); <...> // indexing all vertices int i=0; BGL_FORALL_VERTICES(v, g, Graph) { put(propmapI...
7,768,166
7,770,801
Is there a full range-based standard library implementation available?
After reading "Iterators must go" by Andrei Alexandrescu, I tried to find a replacement for the standard library that uses ranges rather than iterators. The best I could dig up is boost::range, but documentation is pretty weak so I really don't know whether it enables total replacement of iterators when using the stand...
Looking at the Boost.Range documentation the missing algorithms are (using the same classification as the Standard and the Range documentation): Non mutating all_of, any_of, none_of [C++11] find_if_not [C++11] is_permutation [C++11] Mutating copy_if [C++11] move [C++11] move_backward [C++11] iter_swap generate_n sh...
7,768,178
7,768,492
Overload operator-> for STL iterator
I'm writing my own implementation of the C++ STL map container. Now I'm trying to implement the iterator. It should allow you to do something like iter->first and iter->second that returns the key/value respectively and where iter is an object not a pointer. I'm wondering how I should overload this? It's a bit confusin...
The value_type of a standard map is std::pair<const KeyType, MappedType>. To achieve normal pointer semantics, operator* returns a reference, whereas operator-> returns a pointer. //minimal example #include <utility> #include <cstdio> struct It { std::pair<const int, int> pair; std::pair<const int, int>* operator-...
7,768,224
7,768,385
References in initializer list
I have a camera class with two reference variables. I want to pass in two references through the constructor and assign the reference variables to these, so that if I change these in this class, the other ones I defined before (and passed in) will change too. However, I get the error: a reference of type "D3DXMATRIX &"...
It seems to me you are trying to initialize reference to Derived with a reference to Base, as in: class D3DMATRIX {}; class D3DXMATRIX : public D3DMATRIX {}; class Camera { private: D3DXMATRIX& m_; public: Camera(D3DMATRIX& m) : m_(m) {} }; MSVC9.0 says: test.cpp(9) : error C2440: 'initializing' : cannot con...
7,768,460
7,768,518
how to assign value to char * array[] in C++
I want to assign string to char array here is code - char *resultArray[100]; int cnt = 0; void MySAX2Handler::startElement(const XMLCh* const uri, const XMLCh* const localname, const XMLCh* const qname, const Attributes& attrs) { char* message = XMLString::transcode(localname); r...
attrName and attrValue are both pointers and char is a type of integer, so the assignment operator will simply copy the value of the pointer (the address), not the content. Either loop through the strings or use some version of strcpy(), or indeed one of the C++ string libraries.
7,768,565
7,768,874
repackaging exceptions, or keep them intact?
I'm writing some class which has 2 (main) subsystems. A part depends on boost::filesystem while another part depends on tinyxml. (Basically, it reads an xml, and depending on the data of the xml it uses boost::filesystem's functions for more access to other files). Now both of these are "likely" to throw exceptions. I ...
It's impossible to answer this question without an understanding of your code and your coding guidelines, specifically as they relate to exceptions. But if your coding guidelines permit exceptions, then I suggest a general rule-of-thumb: Allow exceptions to propagate until they reach a context in which they can be hand...
7,768,648
7,768,768
How can I get my callback function to work?
I'm getting monitor information using EnumDisplayMonitors: BOOL CALLBACK MonitorEnumProc(HMONITOR hMonitor, HDC hdcMonitor, LPRECT lprcMonitor, LPARAM dwData){ Class::callback(hMonitor,hdcMonitor,lprcMonitor,dwData); return true; } bool Class::callback(HMONITOR hMonitor, HDC hdcMonitor, LPRECT lprcMonitor, LPARAM ...
The last parameter of EnumDisplayMonitors() is an extra pointer reserved for use by the caller. It is passed uninterpreted to the callback function. Pass a pointer to the class instance. BOOL CALLBACK MonitorEnumProc(HMONITOR hMonitor, HDC hdcMonitor, LPRECT lprcMonitor, LPARAM dwData){ reinterpret_cast<Class*>(dwD...
7,768,850
7,769,084
Where can I find reliable information on C++11, std new features and Tr1?
I am trying to make the most of the new standart. However, I am having dificult in find solid information about C++11 like good explanations on the new keywords and syntax. Another problem has been to find information about s*ome new features on the std*. With exception of the wikipedia and the C++ Annotations, I canno...
The latest working draft of C++11 standard (which is N3291 at this time) is available for download here. Edit: It seems that N3291 is not available for public download, you can download the previous version (N3242) instead.
7,768,863
7,771,374
How to correctly set CURRENCY value in C++
In a C++ DLL which is used from a legacy VB6 program, I use the CURRENCY data type to return some large values. The code I'm using to fill it is this: CURRENCY INT64toCURRENCY(INT64 int64) { CURRENCY ret; ret.int64 = int64 * 10000; return ret; } An integer overflow might arise here, but this is the least ...
VarCyFromI8 is the best solution. http://msdn.microsoft.com/en-us/library/ms644370(v=vs.85).aspx The CURRENCY type is a bit tricky with regards to signed values; just use what is already there rather than mess with it on your own. Note that the 64 bit variants are not technically supported until XP. Of course you cou...
7,768,865
7,768,910
copy contents of vector into file
i have following code for copying content of vector into file #include<iterator> #include<algorithm> #include<fstream> #include<iostream> #include<vector> using namespace std; void dump(vector<int>& v){ ofstream out1("C\\Users\\datuashvili\\Desktop\\vector.txt"); if(!out1){ exit(1); } copy(v....
I suspect the problem is this: ofstream out1("C\\Users\\datuashvili\\Desktop\\vector.txt"); should be; ofstream out1("C:\\Users\\datuashvili\\Desktop\\vector.txt"); ^^^^^ You could have found this out on your own by running under a debugger, observing the exit status of your program, or by adding print...
7,769,128
7,954,711
template friend of template class fails in Sun Studio C++
I have a problem with giving a template class a template friend in Sun Studio. The code compiles fine with GNU G++ (4.4.1 and 4.4.3), but fails with Sun Studio C++ (5.9 SunOS_sparc Patch 124863-01 2007/07/25). Here is a minimal example: // Forward declarations template<class T> class M; template<class T> void f(M<T>, M...
Successfully compiled your code using "CC: Sun C++ 5.8 Patch 121017-13 2008/01/02" adding template declaration to a friend: template<class T> class M { ... template <class A> friend void ::f(M<A>, M<A>); ... }; Following is not an answer to original question but those who is looking why a friend templa...
7,769,223
7,769,944
boost::scoped_lock not working with local static variable?
I made the following sample program to play with boost threading: #pragma once #include "boost\thread\mutex.hpp" #include <iostream> class ThreadWorker { public: ThreadWorker() {} virtual ~ThreadWorker() {} static void FirstCount(int threadId) { boost::mutex::scoped_lock(mutex_); stati...
You have two errors: First of all, as already noticed, mutex_ should be static also: private: static boost::mutex mutex_; and of course declare it somewhere (in a .cpp file preferably!): boost::mutex ThreadWorker::mutex_{}; Now, why does the compiler not complain? Well, because you actually do not construct a sco...
7,769,321
7,769,380
Why pointer is not null after function call?
I'm not often using C++ an do I'm currently having a problem with pointers using Microsoft C++. I have defined a half edge data structure. Code sample shows a part of the structure. struct edge { HalfEdge *he1; // pointer to right halfedge HalfEdge *he2; // pointer to left halfedge Edge *n...
The problem is here: HalfEdge h; ... ed->he2 = &h; h goes out of scope when you exit the enclosing block. As a result ed->he2, while keeping its value, becomes a dangling pointer. One way to fix it is by allocating the HalfEdge instance on the heap (using new). edit: It looks like createEdges() has the same b...
7,769,399
7,769,457
C++ STL-based sending of binary serialized data for network transmission using sockets without the use of libraries
I need to send a number of complex objects over the network to a peer. I have written the code to serialize them using ostream and the operator<< for each class member in the objects that need to be serialized. The code I have written works successfully for serialization and network sending (htonl(), htons() etc. corre...
I believe one problem is the use of std::string as your container. Especially the line goodies = buf;. The std::string assignment operator from a char* assumes that the input ends at the first NUL. Since binary data can contain arbritrary NUL characters, it will likely terminate earlier than you expect. For an appli...
7,769,426
7,769,483
C++ - Error when using class template
In file main.cpp... #include "pqueue.h" struct nodeT; struct coordT { double x, y; }; struct arcT { nodeT *start, *end; double weight; }; int arcComp(arcT *arg0, arcT *arg1){ if(arg0->weight == arg1->weight) return 0; else if(arg0->weight > arg1->weight) return 1; return -1; ...
The syntax is simply invalid, you cannot initialise members in-place; use a constructor. struct nodeT { coordT* coordinates; PQueue<arcT *> outgoing_arcs; nodeT() : ougoing_arcs(arcComp) { } }; Apart from that you cannot (usually) define templates in cpp files, you must put the complete definition inside ...
7,769,600
7,769,619
Strange "undefined reference" to template members
First of all, I know that one has to implement the definition in the header files, and that's what I generally did according to this thread I have several files // Image.h namespace library { namespace data { template<class Pixel, class SubPixel, int Layer> class Image { pub...
You have not provided a definition for Image(int width, int height, Pixel emptyFill);, only for Image(int width, int height);
7,769,715
7,769,742
C++ and printf - strange character output
I'm a complete newb to C++, but not to Java, C#, JavaScript, VB. I'm working with a default C++ console app from Visual Studio 2010. In trying to do a printf I get some strange characters. Not the same each time which tells me they may be looking at different memory location each time I run it. Code: #include "stdaf...
The problem is that printf/scanf are not typesafe. You're supplying a std::string object where printf expects a const char*. One way to fix this is to write printf("Hello %s", p.first_name.c_str()); However, since you're coding in C++, it's a good idea to use I/O streams in preference to printf/scanf: std::cout << p.f...
7,769,991
7,770,062
how to not include boost header file in my own header file
I am writing a class In the class, I use boost::graph::adjacent_list as a private member. but I don't want my header file include boost header file, because any other file include my header file will need to include boost header file. Is there a way can avoid include boost header file in my own header file. I have tri...
You can't do this directly, but you can probably solve the underlying problem of not propagating an implementation detail (boost) by pimpling your class. This essentially means that you forward declare a pointer to your implementation details, which are then fully implemented just in a source file.
7,769,998
7,770,019
How to return local array in C++?
char *recvmsg(){ char buffer[1024]; return buffer; } int main(){ char *reply = recvmsg(); ..... } I get a warning: warning C4172: returning address of local variable or temporary
You need to dynamically allocate your char array: char *recvmsg(){ char* buffer = new char[1024]; return buffer; } for C++ and char *recvmsg(){ char* buffer = malloc(1024); return buffer; } for C. What happens is, without dynamic allocation, your variable will reside on the function's stack and will there...
7,770,225
7,770,255
(How) Does the compiler compile a monolithic program as a threaded one?
I wrote a monolithic designed program which is quite rough on the processors needs. And as I have a dual-core I figured that one CPU should therefore be always at 100%. But both my CPUs are on 100% all the time. Now I am guessing that my compiler somehow turned my monolithic application in a threaded one. What are the ...
It doesn't, at least not without using something like Cilk. You must be inadvertently using multiple threads (or processes) without realizing it. Perhaps you're using a third-party library that creates an extra thread or two in your process? [EDIT] As per the comments, use a program like top(1) to verify that is in f...
7,770,502
7,770,709
how can I add error checking for empty string case
There is error checking for a missing file or incorrectly typed file name...but for no file_name i.e. the string file_name is empty I get the error terminate called after throwing an instance of 'std::logic_error' and then windows throw an error at me as well. My guess would be to add a check for the empty string... ...
If you don't provide an argument at all, then argv will only contain one string, and argv[1] will be invalid. You'll have to check that before you even try to access it: int main(int argc, char* argv[]) { if (argc != 2) { std::cerr << "Usage: " << argv[0] << " filename\n"; return EXIT_FAILURE; }...
7,770,520
7,770,611
Can Windows API functions be over-written and called after it?
I want to modify the native functions available in Windows API, such as CreateWindowEx or ShowWindow in a way that when an application is compiled with those functions included, it will instead call my functions, perform the tasks there, and then call the original native function. In other words, I want to in a way pro...
As I've written in the comment, the parent of many hooking libraries was probably the microsoft Detours Now that it isn't free anymore there are various alternatives. Here there is a comparison of some of them (link removed. I'm not sure it was safe. Try googling for "Microsoft Detours is a library utilized in the part...
7,770,543
7,770,852
Drawing Steiner's Roman Surface in OpenGL
I'm trying to draw Steiner's Roman Surface in OpenGL, and I'm having some trouble getting the right normals so that the surface lights up correctly. I used the parametric equation from Wikipedia : http://en.wikipedia.org/wiki/Roman_surface. For the normals, I did a partial differentiation with respect to theta, then ph...
In the case you're dealing with nonorientable surfaces (like Steiner's Romans, or the famous Möbius strip) you have to possiblilities: Enable double sided lighting glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, GL_TRUE); or you enable face culling and render the surface with two passes (front facing and back facing) – you'll ...
7,770,867
7,771,064
why are my primitives see through?
i am rendering a 3d surface in opengl by drawing a bunch of triangles. some of my primitives are see through. i don't simply mean that there is a blending of the color behind them, i mean that i can see completely through them. i have no idea why i am able to see through these primitives and would not like that to be t...
glEnable(GL_BLEND | GL_DEPTH_TEST); is wrong as glEnable only takes a single capability to enable, not a bitmask. You might have more errors, but you want to change the above to: glEnable(GL_BLEND); glEnable(GL_DEPTH_TEST);
7,770,916
7,770,931
How can I read a line of text from a file without skipping a blank line?
I have some input file that looks like this: asdfasfasfas.... asdfasdfasd.... asdfasdf.... asdfsadf... I want to be able to read line by line the whole line, without skipping the blank lines in between. How can I do this? Each line has no white space in it, but if I simply read in and process as: std::string line; ...
You can use getline to read line by line, rather than operator>> that will skip the spaces.
7,770,960
7,771,004
Implementing C library function in C++
What are the disadvantages of implementing C library in C++? The library is going to be used to build Windows application for regular PC using Visual Studio 2008 or newer. It is not clear why the specs state that it should be C library. I am guessing that what they want is plain C-API, not pure C lib. But my boss disag...
I've seen people do that for, say, exposing STL collections to C programs. If you are sure that the library will only be used in environments with sane C/C++ compilers (say, VS and gcc only) I think this is a pretty safe thing to do from the technical perspective. N ow, it sounds like you have some sort of outside re...
7,771,285
7,771,341
example of a hash - superfulous code
I found this snippet here as an example of the simplest kind of hash. It kind of makes since..basically use the modulus operator to reduce a data set from DATA_SIZE(implied) to TABLE_SIZE(defined). However, if a collision occurs, i.e. the array element is already taken, it moves to hash = (hash + 1) % TABLE_SIZE But ...
That modulus is there in case of overflow. suppose hash == TABLE_SIZE - 1. Then hash + 1 == TABLE_SIZE, whereas hash+1 % TABLE_SIZE == 0.
7,771,301
7,771,322
Beginner C++: object creation at runtime without knowing how many objects to create
Say I have a class I defined called 'MyClass'. My 'main' method takes as arguments a list of filenames. Each filename is a config file for MyClass, but the program user can have as many objects of MyClass as they want. If they type in, say, 2 filenames as arguments to my main method, I would like to have 2 objects. If ...
You could use a std::vector of MyClass instances - then you could make as many or as few as you wanted. Take a look at this tutorial, for example (one of many out there on the web), to get you started.
7,771,413
7,773,028
How to properly install virtual printer using WinAPI on Win x64?
I am trying to install virtual printer from C++ console program using WinAPI calls. It works fine on Windows XP, but on Windows 7 x64 there are some processes which lock files in system folders, required for install. I think they appear only on x64 Windows systems, but I haven't tested it with Windows XP x64. These are...
No, there's no way to prevent files from being locked. Even if you stop the spooler, splwow64 and everything else you can think of, there's still the possibility some other program will have one of your DLLs open. This is especially true since you're using UNIDRV because it's used by many other printer drivers. The M...
7,771,551
7,771,764
How to take a vector of points and grab only 'y' of those points
Unfortunately my math abilities and objective-c/c/c++ isn't developed enough to understand how to do this. I have a vector set up like this: [2,2,3,3,4,4,5,5,6,6] <-- i think thats how vectors are set up correct? This is sort of what i think it should be set up: vector<CGPoint>::iterator i; vector<CGPoint>* dp = x...
Ok, my interpretation of your question is that you have a vector that contains CGPoint objects and you want to extract only the y coordinate from all of the points. In that case you want something like (using C++11 lambdas): std::vector<CGFloat> ycoord; std::transform( dp->begin(), dp->end(), std::back_inserter( ycoord...
7,771,623
8,872,200
Segfault when creating smartpointer on CairoContext
I got some problems when creating a Cairo::RefPtr on a Cairo-Context. I really can't imagine why this segfaults, except the pointer ist pointing on something completely wrong. This is my code. int main(int argc, char * argv[]) { Gtk::Main kit(argc, argv); Gtk::Window window; Gtk::DrawingArea draware...
Gtk::Widget::get_window() returns a null Glib::RefPtr, since the widget has not been realized just yet. Based on the GtkDrawingArea documentation, you need to hook onto the "draw" signal to handle drawing, where your Cairo context is already created and handed to you. Going back to the Gtkmm reference, you would use Gt...
7,771,842
7,771,959
Serialize C++ functor
Can you save the function body of a C++ lambda/functor? For example, say you have light0->lightFunction = []( real tEl, real pAz ) -> Vector { return Vector( // red is up lobe std::max<real>( 0., 5*cos(tEl)-4 ), // green lower lobe std::max<real>( 0., -4*sin(tEl-PI)*cos(pAz-2.5)-3), 0. ) ; } ; ...
This lambda doesn't have state (not a closure), so it's an ordinary function. Saving it therefore is the same problem as saving any function. It's not possible in general, but as long as you're loading it back into the exact same process, it may be possible in practice, just by reinterpret_cast-ing the function pointe...
7,771,947
7,772,087
How to measure elapsed time in C# and C++
I have a simple C# and C++ code that computes a sum of dot products. The C# code is: using System; namespace DotPerfTestCS { class Program { struct Point3D { public double X, Y, Z; public Point3D(double x, double y, double z) { X = x; ...
Your diffclock code is wrong. If you change your C++ code to use the std::clock and std::difftime it appears to show the actual runtime: #include <iostream> #include <vector> #include <ctime> using namespace std; typedef struct point3d { double x, y, z; point3d(double x, double y, double z) { thi...
7,771,964
7,771,994
What stream do files use?
When reading data through cin, the stdin stream is used. How about files? Do they use a particular stream object?
There is a complete hierarchy of stream classes, you can see the doccumentation here. Most notable amongst them are ifstream and ofstream for reading and writing to files respectively.
7,772,069
7,772,183
how to tell which project a .cpp file is in
I took over a C++ code which is in a solution. That one solution contains many projects. I edit a .cpp file, but can't file which project it belongs to, so I don't know which project to build. Building the whole solution takes a long time. How do I find out which project a .cpp file belongs to?
Well I think this is kind of the point of .vcxproj files. The projects <-> files relationship is many-to-many. That is, a project contains many files, but also, a file can belong to many projects (in the same solution). So I'm not sure if you can do this in an easier way, but you can right click the tab of the file y...
7,772,085
7,772,236
Pointers to functions and derived classes
I'm having a problem with g++ and how templates interact with pointers to functions. Consider the following declaration of a template. template <class T,class B> class TestTemplate { private: T* context; public: TestTemplate(T* usingClass); B* testfcnOK(B* arg); B* testfcnBAD(B* (T::*fcn)(void));...
I'm no expert in the C++ Standard, but from what I can tell, covariant return types only apply when overriding a function. You cannot use covariant return types with a function pointer. I would propose something like: template <class T,class B> class TestTemplate { private: T* context; public: TestTemplat...
7,772,105
7,772,123
C++ - Basic Error with Arrays of Base Classes
I am a bit stuck right now. I have a base class called BaseBond. ZeroCouponBond and CouponBond inherit from that class. I am looking to create an array that contains both types of bonds. Here is my code: ... BaseBond port[12]; for (int i=0; i < recordCount; i++) { if (bonds[i].CouponRate == 0.0) port[i] = ...
You need to do this using pointers: Change the declaration to this: BaseBond *port[12]; In your original code, you were trying to assign a pointer to BaseBond. So it won't compile. Furthermore, when you use inheritance like this, you have to do it using pointers anyway to prevent object slicing.
7,772,161
7,783,464
Arrays split into header and source files
for some bizarre reason I always forget the exact syntax of arrays. How do I create an array in the header and initialise it in the constructor? Is it possible to initialise it in the header as well as defining it?
I have since read up on this issue a little more and it seems it is not possible: This actually hits on one of the shortcomings of the C++ language — there is no way to initialize non-static array members in C++.
7,772,284
7,772,458
Alt-Tab pedal with an Arduino
I'm creating an Alt-Tab pedal with an Arduino. The idea is that the user will just press down on a pedal that will hit a button on the Arduino, and this would be the equivalent of hitting the ALT+TAB key (thereby allowing you to stealthily switch windows). I'm also open to just minimizing the window. The problem is, I'...
SendKeys.Send("%{TAB}"); Or use SendInput() in a C program.
7,772,331
7,772,740
Pass pointer to pthread of class member declared as friend
I have a class called BaseB which can be called from A. I need to have class A pass a pointer to pthread_create of a member function in class BaseB that also happens to be declared as: friend void ThreadedTask(BaseB* b); in Class BaseB's header under public accessibility. However, in the actual cpp file it is not decl...
If I understand your situation correctly, you have something like the following: /*** baseb.hpp ***/ class BaseB { friend void ThreadedTask(BaseB* b); public: // ... }; /*** baseb.cpp ***/ #include "baseb.hpp" void ThreadedTask(BaseB* b) { // impl } // other BaseB definitions /*** a.hpp ***/ struct A { ...
7,772,756
7,778,153
Qt: Adding native OS Specific code to project
My project is a Qt application written in C++, running on Windows, OS X and Linux. There is a certain area Qt doesn't cover in its abstraction: Iterating other application windows active on the desktop, and returning their names, their 'handles' and icons. I have OS specific code to do just that. Pure Win32/C++ on win...
I suppose I would create shared libraries in this situation. Anyway, what I'm about to suggest is an idea, but should work. By using qmake capabilities, I would create a pro file with different configurations for each platforms, where each configuration (CONFIG variable) includes different sources (this is if you don't...
7,772,839
7,777,157
Drawing multiple related objects in OpenGL
I wish to draw a basic robotic arm using OpenGL using primitive shapes such as cylinders, cubes etc. At this point, I managed to draw the arm statically by applying the necessary transformations viz. translation, rotation, scaling etc. I now need to make it interactive. That is, when a user selects a certain object a...
What you're doing here is called a transformation hierachy and is in fact covered by the chapter on transformations in the OpenGL-1.1 programming guide (recent versions of OpenGL, namely v3 and later largeley stripped down the matrix manipulation stuff, so you need to implement this yourself, but the principle remains ...
7,773,049
8,093,288
Memory leak detection for mixed mode projects: managed, unmanaged and native
I have a Visual Studio 2010 solution that contains C# (managed), C++/CLI (unmanaged) and pure C++ (native) projects. I would like to perform memory leak detection across all 3 projects or at least around the native code: The C# project references the unmanaged dll (I have access commonly available .NET Memory Profilin...
In .NET even if you use managed objects there may be something that never get disposed (check some examples here: Memory Leak in C#). About the native part, you may use two different approaches: use a different memory profiler software, many listed here: Is there a good Valgrind substitute for Windows? change your sou...
7,773,276
7,773,334
C++ shared memory leak, how to clear shared memory?
I am using Qt and trying to achieve a single instance application by applying this solution in Linux(ubuntu). The problem is that if the application unexpectedly finishes(seg. fault or user kills it) the shared memory remains attached and no other process can create it again. Recall from QSharedMemory doc: Unix: QShar...
You can catch the signals that crash your program and use a handler that calls the QSharedMemory destructor.
7,773,301
7,773,367
Executing a python script line-by-line using the C++ Python API
My goal is ultimately to execute a python script that manipulates values in my C++ program, one line at a time, returning execution to my C++ program between statements in the python script. Right now, I'm been attempting to feed the python interpreter my script one line at a time. But it wants a context, and I have no...
I think it will be difficult to feed a script one line at a time. Look into sys.settrace() to set a function that is invoked at each line of execution. You can also set it in the C API using PyEval_SetTrace, in a slightly different form.
7,773,447
7,773,506
Updating DLL of a C++ project in Visual Studio
I have a project that uses a DLL that I have created. Everything works wonderfully, but I am now extending the library in the DLL to optimize some older functions. What I was wondering is if I just modify the library to where only the main function body changes and nothing else can I just rebuild the DLL and replace it...
If you're just changing the functions to optimize them, without changing the function signatures, then you can just build your library and deploy it (replacing the old library). However, if you need to change the function signatures then you can do one of (at least) two things: Modify the code that's using your libra...
7,773,500
7,777,005
Repositioning Shapes/Objects- OpenGL
I would like to reposition a circle, triangles, lines and an arc. How do I go about it? I've searched the web for solutions but nothing that address the issue specifically. Any input that will lead me in the right direction will be helpful. I'm using C++ with opengl.
I would like to reposition a circle, triangles, lines and an arc. So you already did draw the scene and now want to change the position of the objects? Well then, all you need to understand is, that OpenGL doesn't maintain a scene graph of sorts. After submitting a draw call, things get only updates on the target fra...
7,773,607
7,773,621
Segmentation fault for reading 31,622,400 characters from a file
Here is the source code: int main() { int secondsInYear = 366*24*60*60; // Equals 31,622,400 short int data[secondsInYear]; FILE * pFile; pFile = fopen ("stat", "r"); fread(data, sizeof(short int), secondsInYear, pFile); fclose(pFile); } on line fopen("stat", "r") it gives me the segmentation f...
You're creating a massive array on the stack. So you are hitting a stackoverflow. :) You should dynamically allocate that array instead. short int *data = new short int[secondsInYear]; and be sure to delete it later: delete[] data;
7,773,718
7,774,133
Template argument deduction fails on MSVC: bug?
The following fails to compile on VC++8.0 complier with an error (I haven't tried it on the latest visual studio complier yet.) error C2440: 'return' : cannot convert from 'const char *' to 'const char (&)[6]' template <typename T> inline T const& compare (T const& a, T const& b) { return a < b ? b : a; } int ...
It is most certainly a bug in the Microsoft compiler. Here is one big difference in C and C++. e0 ? e1 : e2 In C++, a condtional-expression produces lvalue, unless at least one of the expressions in the second part (after '?') is an rvalue, while in C, a conditional-expression always produces rvalue, no matter what. ...
7,773,771
7,773,941
How do I implement dragging a window using its client area?
I have a Win32 HWND and I'd like to allow the user to hold control and the left mouse button to drag the window around the screen. Given (1) that I can detect when the user holds control, the left mouse button, and moves the mouse, and (2) I have the new and the old mouse position, how do I use the Win32 API and my HWN...
Implement a message handler for WM_NCHITTEST. Call DefWindowProc() and check if the return value is HTCLIENT. Return HTCAPTION if it is, otherwise return the DefWindowProc return value. You can now click the client area and drag the window, just like you'd drag a window by clicking on the caption. LRESULT CALLBACK W...
7,773,875
7,773,993
Boost C++ libraries installation
I have just downloaded the boost libraries from the boost website and extracted them to my desktop. I was hoping to just have a quick look at them and have them installed on my machine and perhaps use them in the future when I am more accustomed to C++. When I extracted it, I was confused with all of the extracted file...
Just add the root boost directory to include paths of your compiler/IDE (so if you have Boost extracted to C:\Boost, the compiler will use that path, not C:\Boost\boost). Don't do any copying of the boost folder to your compiler's include directory, because it may make upgrading Boost harder in the future. Also if you ...
7,773,959
7,774,011
unique_ptr deleter is causing a crash in my program
At run time when I close my program I get the error: "crt detected that the application wrote to memory after end of heap buffer." I followed the program execution through a destructor to the deleter of the unique ptr and the error occured on the call to the deleter function. Another problem I want to mention is that f...
crt detected that the application wrote to memory after end of heap buffer. Yes, this message appears when you call delete, but it's saying it found an error. Not caused one. Somewhere in your code, you are writing past the end of an array, and then during the delete, the memory manager found "footprints" in an o...
7,774,073
7,797,691
undeclared identifier in C++ Visual Studio 2008
I have a C++ project in Visual Studio 2008. In the project I have several forms and several non-form classes. One non-form specifically called Import_LP.h that is a class with several methods all of which are written in the header file with nothing in the resource file. I have no problem with #include Import_LP in any...
If you have include guards, it goes like this: the preprocessor includes Import_LP.h, which says "only include me once", then includes Window.h, which tries to include Import_LP.h, but doesn't because of the include guard. So Window.h starts parsing the window class, but fails because the Import_LP.h class header hasn...
7,774,131
7,774,217
using macros to condense code
I am instantiating various objects based on an xml file. To create an object from a template I specify the datatype in the xml file. As I have quite a lot of templates and datatypes that should be supported I'd like to condense my code a little bit. I thought I could do this by using macros, but since I never really us...
The macro would be something like: #define MACRO(T) if (s == #T) { return new A<T>(blockName); } You only need a parameter (the type), because as far as I can see, A is fixed in your code. If you want to create the code for several types at once, this is not that easy. You should use something like boost preprocessor....
7,774,188
7,774,242
Explicit specialization after instantiation
I have the following code: typedef vector<int> Vec; typedef vector<Vec> VecOfVec; template<typename Vec> Vec DoSomething(const Vec &v); template<> VecOfVec DoSomething<VecOfVec>(const VecOfVec &v) { VecOfVec r; for(auto i = v.begin(); i != v.end(); i++) r.push_back(DoSomething(*i)); return r; } t...
The code requested an implicit instantiation at DoSomething(*i). The fact that you didn't define the template in that translation unit means that it could not instantiate a specialization, hence DoSomething(*i) yields an "unresolved symbol" (linker-) error in your case. To get rid of that error, you either have to defi...
7,774,241
7,775,459
Sort points by angle from given axis?
How can I sort an array of points/vectors by counter-clockwise increasing angle from a given axis vector? For example: If 0 is the axis vector I would expect the sorted array to be in the order 2, 3, 1. I'm reasonably sure it's possible to do this with cross products, a custom comparator, and std::sort().
Yes, you can do it with a custom comparator based on the cross-product. The only problem is that a naive comparator won't have the transitivity property. So an extra step is needed, to prevent angles either side of the reference from being considered close. This will be MUCH faster than anything involving trig. Ther...
7,774,287
7,779,038
DirectX Device Options
Almost all games today have a video options menu where you can choose the quality of textures, shaders, shadows, resolution etc. I'm just wondering how I could find the available options? (like if the user has a 1080x1050 screen, there shouldn't be an option for 1920x1200 resolution) If that's not how it works, do I ha...
Based on the comments, it sounds like you won't be doing any of this for a while, but if/when you do, there is no magic wand, you have to have to deal with all the options individually and it depends on the features you support. For example, with textures, the "low" option could mean that you don't load the highest mip...
7,774,467
7,774,495
How can you use vectors and int's as constructors for a class
If I had a class foo then class foo{ vector <int> vec; int someint; public: foo(number n): someint(n){} } How would I write a constructor for the vector, for class foo? Moreoever, I can use: int get_someint() const{ return someint; } To return an int, but what about vectors?
When working with complex data types, its usually best to work with references, or const-references like so: class A { public: A() {} // default construct of A, v_ is empty A(const std::vector<int>& source) : v_(source) // construct A, given a vector that is // copied into v_ ...
7,774,487
7,774,525
Avoiding code duplication with different data types?
I have some methods like this in my class: static std::string numberToString(int n); static std::string numberToString(float n); static std::string numberToString(double n); std::string encodeVector(const std::vector<int>& intVec); std::string encodeVector(const std::vector<float>& floatVec); std::string encodeVector(c...
Sure. (Caveat: have not compiled) #include <sstream> #include <vector> // All types used in the to_string() function have to // have an appropriate operator << defined. template <class T> std::string to_string(const T& v) { std::stringstream out; out << v; return out.str(); } // generic for vector of an...
7,774,568
7,774,584
C: How to check if free() has freed the memory?
Possible Duplicate: Function Free() in C doesn't work I just asked a question about free(), check the link below. If I can't use if(pointer != NULL), then what can I use, just in case it doesn't work because of a stupid mistake I made. Function free() in C isn't working for me
Whenever you free a pointer you should set it to null - then you can use your test safetly free(pointer); pointer=NULL; if(!pointer) { pointer=malloc(42); } You could even create your own free function so you dont forget to set to null. void myfree(void **ptr) { free(*ptr); *ptr=NULL; }
7,774,687
7,774,707
Interpreting a vector of structs of 3 ints as an array
OpenGL has functions such as BufferData(int array[]) where array must be of the format x-y-z x-y-z .... It is simply a sequence of integers where each consecutive 3-tuple is interpreted as a vertex. Is it safe to represent this as an std::vector, where vertex is declared as: struct vertex { int x, y, z; }; This woul...
It may work but it will not be reliable - there could be unnamed padding between the structure members so you cannot guarantee that they are aligned correctly What is wrong with just using std::vector - this memory is guaranteed by the standard to be correct aligned and sequential. For example you can use: std::vector<...
7,774,738
7,774,750
Reading writing from offset
bool CReadWrite::write(unsigned long long offset, void* pvsrc, unsigned long long nbytes) { int WriteResult; pFile = fopen("D:\\myfile.bin","wb"); if (!pFile){ puts("Can't open file"); return false; } //offset = fseek(pFile,offset, WriteResult = fwrite (pvsrc, 1, nbytes, pF...
If you're using fopen without the append setting (as you are, "wb" creates an empty file), you can assume you're at the beginning. Regardless, SEEK_SET sets the position to the given offset from the beginning. If the file doesn't have the offset that you want to seek to (as it is in your case), then the question is wha...
7,774,789
7,774,812
Is there a way a partial specialization is always preferred over the primary template?
I'm asking myself Can you write a class template and a corresponding partial specialization such that for any set of template arguments for the parameters, the partial specialization is taken by the compiler? For example template<typename T> struct A { }; template<typename T> struct A</* what to write!?*/> { }; I s...
My version of GCC is happy to accept: template<typename T> struct A; template<typename... Pack> struct A<Pack...> {};
7,774,938
7,775,007
In C++, will the vector function push_back increase the size of an empty array?
Quick question. Let's say I declare a vector of size 20. And then I want to add a few integers to it using push_back. vector<int> myVector(20); myVector.push_back(5); myVector.push_back(14); Is the capacity of my vector now 22, or is it still 20? Were 5 and 14 added to indices [19] and [20], respectively? Or are they ...
After those statements its capacity is implementation-defined. (Please note that is different from its size.) vector<int> myVector(20); This creates a vector filled with twenty 0's. Its size is twenty, exactly, and its capacity is at least twenty. Whether or not it's exactly twenty is implementation-defined; it may h...
7,775,042
7,775,104
Uninitialized static data member of static class
I ran into a weird problem today that I don't really fully understand. Hopefully someone here can help. The setup is fairly easy. I have a class that has a static member of type std::set. The class has 2 template constructors that differ in the number of arguments only. It's the same behavior for both constructors, so ...
Global objects that access each other from the constructor are going to have problems with the order of their instanciation. There are a couple of ways around this: Try //Change static std::set<u32> mRegisteredVars; //Into static std::set<u32>& getRegisteredVarsSet() { static std::set<u32>& mRegisteredVars; ...
7,775,302
7,775,332
Regarding passing strings to win32 api functions
I was wondering if there is any advantage (for shorter strings only) of using a string datatype instead of a char array, or simply the string such as: TextOut(hDC, 10, 10, "Hello", sizeof("HEllO") - 1)
In practice, this doesn't matter at all. That said, the Win32 APIs require LPSTRs or LPWSTRs, so anything which is not "one of those" will first have to be converted into the appropriate char* type, so a very tiny bit of extra work is required. I'd say the vastly bigger consideration is using a datatype which is conven...
7,775,496
7,775,502
What causes SXSTrace error "StartTrace failed ... Unknown Error"?
I'm here because of a sibe-by-side configuration error. When I try to launch a game, it pops a side-by-side configuration error. I try lots of stuff that didn't work, but then, I found this site: http://blogs.msdn.com/b/cesardelatorre/archive/2011/03/27/the-application-has-failed-to-start-because-its-side-by-side-conf...
You can use dependency walker to open your exe and find the missing dependency and SxS versioning.
7,775,533
7,775,555
OpenMP Unexpected output
I have two threads with a parallel for but this one does not break up into threads: #pragma omp parallel sections { #pragma omp section { for(int i=0;i<4;++i) printf("Loop A %d %d\n", omp_get_thread_num(),2); } #pragma omp section { for(int i=0;i<4;++i) printf("Loop B %d %d\n",...
This can happen for a number of reasons. I'll list the possible ones I know: 1: Make sure you actually have a multi-core machine. If it's a single core machine (no HT), it'll only run with one thread. 2: If this is on Visual Studio, you need to enable OpenMP support. Just including the header is not enough: Project -> ...
7,775,537
7,792,836
data_condition wait invalid argument error
data_cond.wait(lk, [this]{return !data_queue.empty();}); invalid argument after compile with g++ -std=c++0x -Wall -pthread threadpool.cc -o hello originally from book is data_cond.wait(lk, []{return !data_queue.empty();});
That looks rather like code from my book: C++ Concurrency in Action, especially with the lack of [this] capture (a typo which will be fixed in the final printing). Unfortunately, there is a bug in g++ 4.5 and 4.6, where the compiler cannot handle lambdas with [this] captures in class templates. This even applies to sim...
7,775,589
7,775,640
Overloading string() operator
I have an assignment that my teacher has told us to use this in the .h file: operator string(); and we can not deviate from it in any way. So in my .cpp file I have: Currency::operator string(){ stringstream output; output<<"$"; output<<dollars;//Why does this return garbage for money1+money2?? output<<".";...
Here is my overloaded + operator code: You are returning a local variable by reference. Never do this. You should be returning it by value: Currency Currency::operator+(const Currency &rhs)
7,775,626
7,781,865
prim_minimum_spanning_tree() Boost function
I am trying to use the Prim algorithm with prim_minimum_spanning_tree function of the boost library, using a file containing all my graph points. I successfuly created the graph I wanted with the kruskal_minimum_spanning_tree function of boost library. But with the prim_minimum_spanning_tree I only get the direct pare...
I have found the answer to my own question, might be usefull to someone else. I was linking the points twice, which work for the kruskal's algorithm, but not for the prim's one, for example in my edges I had : 0 <--> 1 1 <--> 0 where I should have only linked the points once for the prim's algorithm.
7,775,697
7,775,732
Calling a function and escaping it with a goto: memory leak?
If I call a function, and escape it with a goto, will I be leaking onto the stack? Is that like dividing by zero? Will the universe implode in a reverse-Big-Bang? This is not my program, but it has almost exactly the same structure... bool func() { blah(1337.1337); uber("iasouhfia"); if(random) goto escapeL...
According to draft C++ standard: "The scope of a label is the function in which it appears." (6.1 Labeled statement) So, you can't goto to a label outside the function, hence your question contains a syntax error.
7,775,803
7,775,811
Debugging map insertion?
I'm having an issue with inserting an entry into a Map. #include <stdio.h> #include <vector> #include <stack> #include <map> using namespace std; class Nodo { public: vector<Nodo> Relaciones; int Valor; bool Visitado; Nodo(int V) { Valor = V; Visitado = false; } }; class Graf...
You have a type mismatch. You're passing a Nodo* into the pair constructor while it expects a Nodo object. You declare: Nodo *Raiz; and then you try to call: pair<int, Nodo>(V, Raiz) which expects an int and a Nodo. But you passed it int and Nodo*. What you probably want is this: class Grafo { public: Nod...
7,775,887
7,775,899
How do I allocate memory by using new in C++?
I have following static declaration of memory: void* array[5000]; How I can allocate the same memory using operator new in C++?
void **array = new void*[5000];
7,775,994
7,776,011
Open a file using full path in C++
quick question really that has me momentarily stumped. This program searches through a a file directory and all of its sub directories. When it gets to a file that's not a directory type I want to open the file, throw it in a buffer and compare it to another file which will already be in another buffer. The problem is...
Concatenate them: open((path + "/" + dir_entry->d_name).c_str(), ...)
7,776,022
7,845,387
Qt - how to record and play sound simultaneously
I posted this question on the Qt forum, but got no answers. That's why I am posting it here. I wanted to know is there any way to record and play sound at the same time in Qt. I want to record sound from a microphone and at the same time I want to play it in the speaker/headphone. Is there any way to do this in Qt? Or...
I'm not very experienced with Qt, but I am with handling media, so forgive me if my answer isn't very specific but instead addresses your problem from a more general point of view. I looked at your code, and I think in general your idea should work. I see some problems though: the writeData method doesn't seem to be p...
7,776,085
7,776,098
Why are memcpy() and memmove() faster than pointer increments?
I am copying N bytes from pSrc to pDest. This can be done in a single loop: for (int i = 0; i < N; i++) *pDest++ = *pSrc++ Why is this slower than memcpy or memmove? What tricks do they use to speed it up?
Because memcpy uses word pointers instead of byte pointers, also the memcpy implementations are often written with SIMD instructions which makes it possible to shuffle 128 bits at a time. SIMD instructions are assembly instructions that can perform the same operation on each element in a vector up to 16 bytes long. Tha...
7,776,105
7,776,788
std::pair of std::string and custom class fails to copy on std::map::insert(std::make_pair(string, class))
This error: error C2678: binary '=' : no operator found which takes a left-hand operand of type 'const std::string' (or there is no acceptable conversion) c:\program files (x86)\microsoft visual studio 10.0\vc\include\utility 216 occurs on this function's only line: void Animation::AddAnimation(std::string name, Ani...
The reason why this is failing is because the std::map container you are using expects a const value as key value. Check the documentation of std::map here. Example: class TestClass { }; std::map< const std::string, TestClass > myMap; std::pair< const std::string, TestClass > firstElement = std::make_pair("test", Test...
7,776,264
7,779,363
C++0x: Slice template fails to compile with range-based for()
I get the following compile error in gcc 4.6.1 when trying to get a Slice template class to work with range-based for() (occuring on the for() line with auto): I know there is a slice class in boost - this is just for illustrative purposes I managed to get ranged-based for() to work fine with a plain class - just havi...
Your begin and end template parameters are set up wrong. They are passed s, which is Slice<int>, so T is deduced to Slice<int>. The return type, then, is vector<Slice<int> >::const_iterator. But Slice<int>::Begin returns vector<int>::const_iterator. As you mentioned in your comment, the solution is to change the par...
7,776,272
7,776,313
Calling C++ member function pointer from a struct
I have found information on calling C++ member function pointers and calling pointers in structs, but I need to call a member function pointer that exists inside of a structure, and I have not been able to get the syntax correct. I have the following snippet inside a method in class MyClass: void MyClass::run() { ...
Use: (this->*functionMap[0].command)(x, y); Tested and compiles ;)
7,776,448
7,776,468
SFINAE tried with bool gives compiler error: "template argument ‘T::value’ involves template parameter"
I tried to implement an SFINAE using bool (unlike popular void_ trick): template<typename T, bool = true> struct Resolve { static const bool value = false; }; template<typename T> struct Resolve<T, T::my_value> { static const bool value = true; }; The goal is to specialize, the classes which h...
Actually what you're doing is forbidden by section §14.5.4/9 which says, A partially specialized non-type argument expression shall not involve a template parameter of the partial specialization except when the argument expression is a simple identifier. The trick could be using a type for second template parameter ...
7,776,451
12,926,993
running shellcode + vs2010
I just tried the following code snippet for shellcode testing purposes:- #include<iostream> using namespace std; char sc[] = ""; #i've removed the shellcode int main() { int (*func)(); func = (int(*)())sc; (int)(*func)(); } I get a build error on compilation :- ------ Build started: Project: shellcoderu...
To execute a shellcode in your C/C++ program with VS, the simplest way is embedding an Assembly code like this example below: char* buffer="blah blah blah"; int main() { __asm{ lea eax, buffer call eax } } Hope this help!
7,776,548
7,776,553
Is there any ArrayList<String> collection in C++ like in Java?
I am using native function in my java class. I have written C++ function for XML parsing. My problem is that after parsing XML, i have to store node names into string array, but i dont want to fix its size. Like java, C++ have any collection ?
Are you looking for just this? vector<string> var; http://en.wikipedia.org/wiki/Vector_%28C%2B%2B%29 It's used pretty much the same way but with different method names.
7,776,800
7,777,198
convert vector to jobject in C++/JNI?
I am using Java native function - public native ArrayList<String> parseXML(); In C++ my native function - vector<string> resultList; JNIEXPORT jobject JNICALL Java_Sample1_parseXML (JNIEnv *env, jobject obj){ // logic return resultList; // here getting error } My problem is that how to convert resultList (...
You would have to create a wrapper for the ArrayList in C++. Something like: vector <char*> vec; jclass clazz = (*env).FindClass("java/util/ArrayList"); jobject obj = (*env).NewObject(clazz, (*env).GetMethodID(clazz, "<init>", "()V")); for (int n=0;n<vec.size();n++) { char* str = (char*) static_cast<char*>(vec[n])...
7,776,809
7,776,883
Is having a container of a type as a field a bad idea in C++?
Is it a bad idea in C++ to do something like: struct Node { string name; vector<Node> children; }; I'm asking because it looks to me like resizing children for any reason could potentially cause an exponential copying cascade. But on the other hand, vector<Node*> has its own problems, and things like vector<sh...
Is having a container of a type as a field a bad idea in C++? It's not bad as a general rule. It really comes down to the context. In this case, the indirections of a shared pointer should not be significant compared to nontrivial resize operations, and the cascading (assuming that will be a problem). If you can rese...
7,776,814
7,776,899
how do I optimize this loop further?
Well, this post is the reason for Why is memcpy() and memmove() faster than pointer increments? I have a custom image structure with 4 channels and I like to extract 3 of them (RGB) into an openCV cv::MAt strcuture with 3 channels. cv::Mat GetColorImgFromFrame(Image* pimg) { int iHeight = pimg->m_imageInfo.m_height...
Before going into "assembler like" mode by using SIMD intrinsic, you can try to tell your compiler that the source and destination pointer do not alias, using for example the __restrict__ keyword with gcc or __restrict with visual studio
7,776,852
7,776,910
Can we use ofstream object as a third argument in backtrace_symbols_fd()?
I have to call backtrace_symbols_fd() function, but the third argument of this function is file descriptor. so can i pass that third argument as ofstream object ? I'm tyring following code: ofstream myfile; myfile.open ("example.txt"); size_t size = backtrace(aray, 5000); backtrace_symbols_fd(aray, 5000, myfile); ...
As you have discovered, no it is not possible to pass an ofstream. Just use the open(2) function to get a file descriptor.
7,776,933
7,779,083
Read configuration file using only unmanaged C++
I have an unmanaged Visual C++ project. I need to use a section defined in app configuration file without using any managed assembly. Is there a library that comes with Visual Studio 2010 installation that can be used for this purpose? If no such library comes with Visual Studio 2010, I suppose I will have to use a lib...
See C++ library for storing settings in XML for libraries which can read settings in XML files. If you want something which comes with MSVC, I think the closest you get is using MSXML via a COM interface. But you will need to install the msxml redist on the target machine if it is not already installed. Maybe take a lo...