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
3,986,909
3,987,046
typedef for enum from template base class
Followup on an answer from last night - I was hoping more comments would answer this for me but no dice. Is there a way to achieve this without inheritance that does not require the cumbersome usage in the penultimate line of code below, which writes the value to cout? struct A { enum E { X, Y, Z }; }; ...
The only way to place names enum value names directly into a class, is by inheriting from a class with those names. The code you're showing seems to use a Microsoft language extension. In C++98 an enum typename can not be used to qualified one of the value names: Comeau C/C++ 4.3.10.1 (Oct 6 2008 11:28:09) for ONLINE...
3,987,008
3,987,682
How to optimize a cycle?
I have the following bottleneck function. typedef unsigned char byte; void CompareArrays(const byte * p1Start, const byte * p1End, const byte * p2, byte * p3) { const byte b1 = 128-30; const byte b2 = 128+30; for (const byte * p1 = p1Start; p1 != p1End; ++p1, ++p2, ++p3) { *p3 = (*p1 < *p2 ) ? b...
Instead of offsetting your signed values to make them unsigned, a slightly more efficient way would be to do the following: use _mm_min_epu8 to get the unsigned min of p1, p2 compare this min for equality with p2 using _mm_cmpeq_epi8 the resulting mask will now be 0x00 for elements where p1 < p2 and 0xff for elements ...
3,987,026
3,987,760
Advantages of using boost::mpl::bool_ instead of a const bool
I am confused about the advantages of using the the bool_<true> and bool_<false> types against simply using const bools in the context of template metaprogramming. The boost::mpl library clearly prefers the first approach, and defines helper functions like and_, or_ to help manage such bool_. Conditional metafuncti...
Here is a short example, how I use these types every now and then. This example would not be possible, using const bool: void do_something(boost::mpl::bool_<true>) { ... } void do_something(boost::mpl::bool_<false>) { ... } Call one of these two functions depending on the type of argument: template<class T> voi...
3,987,048
3,988,571
c++ std::vector Orphan Range error
A program dealing with graphs(from graph theory) representation and transformation.The adjacency list and matrix are implemented like dynamic arrays of vectors(don't ask why not vector of vector) for the following function program exits with memory error and compiler pointing to the orphan vector definition. int vertex...
Problem Solved : Once again i've read outside of an array.The error was in the cont variable which i used to address the vectors in the Matrix(dynamic array), incrementing it while it got outside the array.Problem is solved by inserting a while statement.Thank you all for the answers. int vertex,edges; vector<int> *adj...
3,987,521
3,988,340
How bad is to use void pointer in std::vector declaration?
I have two different classes as below: class text { }; class element { }; And I want to store them in the class node: template <typename T> class node { T cargo; std::vector<void*> children; node(T cargo) : cargo(cargo) { }; void add_child(T node) { this->children.push_back((void*) ...
#include <vector> using namespace std; class Element {}; class Text {}; class Nothing {}; class Node { private: vector< Node* > children_; protected: Node() {} public: void add( Node* p ) { children_.push_back( p ); } virtual ~Node() {} }; template< class Cargo > class CargoNode : public Node...
3,987,640
3,987,685
Variable creation on heap or stack in C++
Circle is a class, with public method GetDiameter(). What is the difference between the following 2 sets of code? Qn1: Does Method 1 allocates memory for c on stack (hence no need free memory), while Method 2 allocates memory for c on heap (need manually free memory)? Qn2: When should we use Method 1 or Method 2? Metho...
As a general rule for good coding practice, always use method 1 when possible. Method 2 should be used only if you need to store and/or share the pointer in different places. All objects used only locally in a method or class should be put in the stack.
3,987,873
3,987,899
Avoiding column name redundancy accessing SQL databases?
I'm working on a program using a SQL database (I use SQLite). What my program does is the following: Creates the tables in the database if they don't exist (on startup) Executes SQL queries (SELECT, UPDATE, DELETE) - decided by the user from the interface What I saw doing this is that there is a lot of redundancy. I ...
This is the basic idea behind an ORM such as Ruby on Rails' ActiveRecord, hibernate, and similar technologies. Basically you set the configuration for a table - or use a standard naming convention - and the framework will generate your CRUD (INSERT / SELECT / UPDATE / DELETE) queries for you.
3,987,897
3,987,937
C++ -- Should the subclass destructor explicitly call base class destructor?
Possible Duplicate: Do I need to explicitly call the base virtual destructor? Hello all, I would like to know whether or not a sub-class destructor should call base-class destructor explicitly. My answer is NO. For example, class A { public: A() {...} virtual ~A() {...} protected: ... private: ... }; ...
No, a destructor should never ever be called explicitly (in a subclass or otherwise, pretty much just never), the compiler will take care of that for you. The only situation where you might want to call it explicitly is where you're rolling your own memory management, and you're actually freeing the memory explicitly (...
3,988,002
3,988,061
How to open a file with it's relative path in Linux?
I have a program which opens a file by using a relative path (for instance '..'). Now the problem is, when I execute the program from another directory, the relative path is not relative to the program but relative to the working directory. Thus, if I start the program with '/path/to/program/myprog' it fails to find th...
If program is not doing it by itself, it is a bad program. Bad programs should be wrapped with a bit of Bash scripting: #!/bin/bash set -e cd $(readlink -f $(dirname $0)) exec ./myprog $* The script above determines the directory where it is located, then changes current working directory to that directory and runs a...
3,988,045
3,988,077
How much is the memory allocated for a user-defined class in C++
I understand that certain data type object have certain buffer size. E.g. a char is 1byte. So, when creating a self-defined class object, How much memory is allocated to the object a? Is the amount of memory allocated different if the object is created on stack, or heap? Is the amount of memory allocated fixed, or can...
In both cases at least sizeof(Animal) bytes will be allocated. In case of stack allocation some extra memory might be used for alignment. In case of heap memory some extra memory will likely be used for storing heap service data. You can influence the exact amount of memory by changing the class - for example for heap...
3,988,325
3,988,371
TinyXpath v_get_xpath_base, second parameter
What do I pass here as the second parameter to v_get_xpath_base in order to get it to work, no matter what I try, there always seems to be a problem. Either the class is a base class and cannot be instantiated or the class cannot be casted. I'm at a loss, someone help me please? TiXmlElement* outputnode = new ...
The API is going to return you the matching node - I imagine you need something like: const TiXmlBase* outputnode(0); bool isAttrib; proc.v_get_xpath_base(1, outputnode, isAttrib); and after the call, outputNode will point to the matched data. Seems like you have to use const TiXmlBase* as the type for outputnode. T...
3,988,470
3,988,573
Why must loop variables be signed in a parallel for?
I'm just learning OpenMP from online tutorials and resources. I want to square a matrix (multiply it with itself) using a parallel for loop. In IBM compiler documentation, I found the requirement that "the iteration variable must be a signed integer." Is this also true in the GCC implementation? Is it specified in the ...
According to OpenMP 3.0 specification: http://www.openmp.org/mp-documents/spec30.pdf, for variable may be of a signed or unsigned integer type, see 2.5.1 Loop Construct. The question is whether given OpenMP implementation matches this latest specification.
3,988,484
3,992,108
How to load a png resource into picture control on a dialog box?
I tried the following code on OnInitDialog() but nothing was shown. m_staticLogo.SetBitmap(::LoadBitmap(NULL, MAKEINTRESOURCE(IDB_LOGO))); where m_staticLogo is the static picture control and IDB_LOGO is the resource ID of the png file.
As you’ve discovered, ::LoadBitmap (and the newer ::LoadImage) only deal with .bmps. By far the easiest solution is to convert your image to a .bmp. If the image has transparency, it can be converted into a 32-bit ARGB bitmap (here is a tool called AlphaConv that can convert it). Then load the image using the CImage cl...
3,988,518
3,988,886
Unresolved External Symbol?
Possible Duplicate: What is an undefined reference/unresolved external symbol error and how do I fix it? I am terrible at reading c++ errors, but obviously Unresolved External Symbol means the function I am using isn't defined. The error I am getting is... 1>WorldState.obj : error LNK2001: unresolved external symbol...
Since you are using a template function, it's definition has to be visible when you call it. Therefore, because this is a member function, it has to be implemented in the header where you declared it.
3,988,564
3,995,324
How can I add a package to Qt
I downloaded a package called QtIOCompressor, I need to use the functionality like zipping a directory gzipping a directory etc etc in a application I am coding. But I dont know how to add this package into Qt or how to configure this package by which i can use it with my application which i may code in future! InfO: h...
step: read the INSTALL.TXT that comes with the package and follow the instructions. Basically that is just: qmake and nmake step: look at the .pro files in the example directory for usage in your program. (you just have to include src/qtiocompressor.pri
3,988,565
3,988,980
Lexically-scoped ordering behavior
I have a class with two definitions of ordering. (In the real problem, one is a total order and one is a semiorder.) But it's nice to be able to use the comparison operators rather than always having to use an explicit comparison function or functor object. So I figured I'd provide some comparison operators like thi...
I would stick with ordinary comparison functions. The rest of the code will be cleaner. No using namespace... or explicit calls to scoped operator<. Reads easier this way, IMO... int main() { bool b = compare1(4, 5); b = compare2(4, 5); }
3,988,869
3,989,019
C++ lambda operator ==
How do I compare two lambda functions in C++ (Visual Studio 2010)? std::function<void ()> lambda1 = []() {}; std::function<void ()> lambda2 = []() {}; bool eq1 = (lambda1 == lambda1); bool eq2 = (lambda1 != lambda2); I get a compilation error claiming that operator == is inaccessible. EDIT: I'm trying to compare the f...
You can't compare std::function objects because std::function is not equality comparable. The closure type of the lambda is also not equality comparable. However, if your lambda does not capture anything, the lambda itself can be converted to a function pointer, and function pointers are equality comparable (however,...
3,989,003
3,989,057
C++ How can achieve this Interface configuration?
I certainly don't know how to title this question, sorry. I'm having some problems to design the following system. I need a class which will make some work, but this work can be done in a bunch of different ways, say that this work will be made through "drivers". These drivers can have different interfaces and because ...
To me your basic idea seems to be fine. I would consider separating the creation of drivers into a factory (or at least a factory method) though.
3,989,094
3,991,317
UMFPACK and BOOST's uBLAS Sparse Matrix
I am using Boost's uBLAS in a numerical code and have a 'heavy' solver in place: http://www.crystalclearsoftware.com/cgi-bin/boost_wiki/wiki.pl?LU_Matrix_Inversion The code works excellently, however, it is painfully slow. After some research, I found UMFPACK, which is a sparse matrix solver (among other things). My ...
There is a binding for this: http://mathema.tician.de/software/boost-numeric-bindings The project seems to be two years stagnant, but it does the job well. An example use: #include <iostream> #include <boost/numeric/bindings/traits/ublas_vector.hpp> #include <boost/numeric/bindings/traits/ublas_sparse.hpp>...
3,989,127
3,989,164
What do I often see references in operator overloading definitions?
For example, in the OGRE3D engine, I often see things like class_name class_name :: operator + (class_name & object) Instead of class_name class_name :: operator + (class_name object) Well it's not that I prefer the second form, but is there a particular reason to use a reference in the input ? Does it has special ca...
It's a performance issue. Passing by reference will generally be cheaper than passing by value (it's basically equivalent to passing by pointer). On an unrelated note, you probably want the argument to operator+ to be const class_name &object.
3,989,435
3,989,864
Why do I get missing symbols for an explicit template specialization in a static library?
If I compile the following code: // // g++ static.cpp -o static.o // ar rcs libstatic.a static.o // #include <iostream> template < typename T > struct TemplatedClass { void Test( T value ) { std::cout << "Foobar was: " << value << std::endl; } }; template struct TemplatedClass < long >; I get a static libr...
You have member function definitions within class (template) definitions. This causes the member functions (templates) to be inline. That doesn't matter so much for the member function of the template class, since its linkage requirements are determined more by the nature of its instantiation(s). But in the second ex...
3,989,483
3,989,541
Download from a URL with C++
I'm playing around with C++ for the first time in years. Making an app using Qt, with the Qt IDE. I want to make an app to integrate with the Flickr API. I've got to the point where i need to make a call to a URL. Flickr API: http://flickr.com/services/rest/?method=flickr.people.getInfo&api_key=987654321&auth_token...
Use QNetworkAccessManager. The page has an example.
3,989,641
3,989,664
Why return const Rational rather than Rational
I saw the following implementation of the operator* as follows: class Rational { public: Rational(int numerator=0, int denominator=1); ... private: int n, d; // numerator and denominator friend const Rational operator*(const Rational& lhs, const Rational& rhs) { return Rati...
So that you can't do something like Rational a, b, c; (a * b) = c;. No.
3,989,678
3,989,794
C++ template friend operator overloading
What is wrong with my code? template<int E, int F> class Float { friend Float<E, F> operator+ (const Float<E, F> &lhs, const Float<E, F> &rhs); }; G++ just keeps warning: float.h:7: warning: friend declaration ‘Float<E, F> operator+(const Float<E, F>&, const Float<E, F>&)’ declares a non-template function float.h:7: ...
It's just a warning about a tricky aspect of the language. When you declare a friend function, it is not a member of the class the declaration is in. You can define it there for convenience, but it actually belongs to the namespace. Declaring a friend function which is not a template, inside a class template, still dec...
3,989,785
3,989,966
Finding memory overruns
I have a legacy C++ code which is ported to Android. When calling free on strings, a random crash is occurring. Crash is observed in random places. Is there a tool which can be used to check the memory overruns?
You could try my non-intrusive heap debugger.
3,990,004
3,990,089
Detecting when a "new" item has been deleted
Consider this program: int main() { struct test { test() { cout << "Hello\n"; } ~test() { cout << "Goodbye\n"; } void Speak() { cout << "I say!\n"; } }; test* MyTest = new test; delete MyTest; MyTest->Speak(); system("pause"); } I was expecting a crash, but inste...
You might use reference counting in this situation. Any code that dereferences the pointer to the allocated object will increment the counter. When it's done, it decrements. At that time, iff the count hits zero, deletion occurs. As long as all users of the object follow the rules, nobody access the deallocated obj...
3,990,087
3,990,249
QMap::contains() not returning expected value
I have a class that contains a QMap object: QMap<QString, Connection*> users; Now, in the following function Foo(), the if clause always returns false but when I iterate through the map, the compared QString, i.e., str1 is present in the keys. void Foo(QString& str1, QString& str2) { if(users.contains(str1)) ...
With unicode, two strings may be rendered the same but actually be different. Assuming that's the case you'll want to normalize the strings first: str = str.normalize(QString::NormalizationForm_D); if (users.contains(str)) // do something useful Of course, you'll need to normalize the string before you put it in ...
3,990,119
3,990,196
About C++ template and operators
After some trial and a lot of error, I have come to find out that it is not very useful to template operators. As an Example: class TemplateClass { //Generalized template template<TType> TType& operator[](const std::string& key) { return TType; } //Specialized template for int template<> int& operat...
This isn't specifically an issue of templates. It's a grammar issue. What you're doing is odd in that you're only changing the return type. Had you changed the operator parameters, you wouldn't have to explicitly provide the type for the template. Since you do need to provide type, you need to explicitly call the opera...
3,990,256
3,990,264
C++ version of isspace (Convert code to C to C++)
I am converting code from C to C++. I am currently using the C function, isspace, what is the C++ equivalent when using an ifstream? Specifically while (!isspace(lineBuffer[l])) id is the first the number (2515, 1676, 279) and name is the set of letters after the first "space" (ABC, XYZ, FOO). Example NewList.Txt 2515 ...
std::isspace() from #include <locale>. (Or, more fully qualified, template <typename T> bool std::isspace(T c, const std::locale& loc). Exact declaration may vary between compilers.)
3,990,593
3,990,618
Why NULL is converted to string*?
I saw the following code: class NullClass { public: template<class T> operator T*() const { return 0; } }; const NullClass NULL; void f(int x); void f(string *p); f(NULL); // converts NULL to string*, then calls f(string*) Q1> I have problems to understand the following statement template<class T> operator T*()...
what is the meaning of operator T*()? It is a user-defined conversion operator. It allows an object of type NullClass to be converted to any pointer type. Such conversion operators can often lead to subtle, unexpected, and pernicious problems, so they are best avoided in most cases (they are, of course, occasionally...
3,990,655
3,990,895
Enum with 64 bit underlying integer
I'm using gcc, which implements enums as 32 bit integers on the architecture I have (don't know in general). If I try to assign an enum value too large, I get warning: integer overflow in expression Is there a way to make gcc use 64 bit integers as the underlying integer type? A gcc specific way is fine, although if ...
The following works for me with -std=c++0x, but not with -std=c++98 though enum EnumFoo { FooSomething = 0x123456789ULL }; I tested this with $ g++ --version g++ (Ubuntu 4.4.3-4ubuntu5) 4.4.3
3,990,739
3,990,776
Undefined reference to enum
I'm getting this error message from my compiler: undefined reference to `Pawn::Pawn(Piece::Color)' This occurs when I do this: // board[][] contains pointers to Piece objects board[0][0] = new Pawn(Piece::BLACK); Here's part of the Pawn class: // Includes... #include "piece.h" // Includes... class Pawn : public Piec...
The error doesn't really have anything to do with the enum. You need to define the Pawn(Color) constructor, e.g., Pawn::Pawn(Color) { ... }
3,991,057
3,991,111
Passing array with unknown size to function
Let's say I have a function called MyFunction(int myArray[][]) that does some array manipulations. If I write the parameter list like that, the compiler will complain that it needs to know the size of the array at compile time. Is there a way to rewrite the parameter list so that I can pass an array with any size to t...
In C++ language, multidimensional array declarations must always include all sizes except possibly the first one. So, what you are trying to do is not possible. You cannot declare a parameter of built-in multidimensional array type without explicitly specifying the sizes. If you need to pass a run-time sized multidimen...
3,991,110
3,991,206
How do you create a mock object without an interface class in AMOP?
I'm just getting into Test Driven Development with mock objects. I can do it the long way with UnitTest++, but now I want to try to minimize typing, and I'm trying to use AMOP mock framework to do the mocking. AMOP states: The main differences between AMOP and other mock object library is that, users DO NOT need to...
For what I've seen in the documentation, it actually doesn't need the mock object to implement any interface. The mocking object is constructed based on the original object's interface, but not by inheritance, but as a parameter of the class: TMockObject<IInterface> mock; No inheritance here, and TMockObject doesn't g...
3,991,197
3,991,634
SQLite Crash on Inserting Items
I have three queries that I'm running through SQLite. These are what I'm running; the first is the table declaration and then the next 3 are the actual queries. Declaration: "CREATE TABLE IF NOT EXISTS items (busid INTEGER PRIMARY KEY, ipaddr TEXT, time TEXT DEFAULT (NOW()));" Queries: (Works) "INSERT INTO items...
i downloaded your source, compiled and ran with each line uncommented in turn, all works ok sqlite version 3.6.23.1 redhat 5 32 bit so i guess the answer is - upgrade to latest version of sqlite
3,991,379
4,727,503
Visual Studio Debugger - Visualising Intel Quadruple precision (_Quad)
I'm using Intel C++ Compiler from within Visual Studio 2008. I was experimenting with the Intel quadruple precision type (_Quad). Everything seems to be working fine, except for the debugging. Visual Studio visualiser is unable to peek into _Quad values. What's worse, the visualiser is unable to provide the type inform...
_Quad is a keyword for Intel C++ compiler, which means it's type info is proprietary and not understandable by Microsoft tools. To display it in VisualStudio Debugger/IDE, you'll need VisualStudio extensions that can interpret this type for the debugger/IDE. You might want just contact Intel and see if they have any ...
3,991,420
3,995,672
How to free a through istream blocked thread
i have created two classes. One for input reading (through an istream object) and parsing and the other one for processing the output of the parser. There is one instance of each of those. I have the parser running in a loop calling istream::get() and then creating commands for the second object based upon the input. T...
You will have to depend on something other than the standard iostream classes, because they don't provide select()-style behaviour. Also, killing the thread is impossible with POSIX (and utterly broken in Windows). You can issue a cancellation request via pthread_cancel(), but in your case, it may be stuck in an un-can...
3,991,478
3,991,555
Building a 32-bit float out of its 4 composite bytes
I'm trying to build a 32-bit float out of its 4 composite bytes. Is there a better (or more portable) way to do this than with the following method? #include <iostream> typedef unsigned char uchar; float bytesToFloat(uchar b0, uchar b1, uchar b2, uchar b3) { float output; *((uchar*)(&output) + 3) = b0; *...
You could use a memcpy (Result) float f; uchar b[] = {b3, b2, b1, b0}; memcpy(&f, &b, sizeof(f)); return f; or a union* (Result) union { float f; uchar b[4]; } u; u.b[3] = b0; u.b[2] = b1; u.b[1] = b2; u.b[0] = b3; return u.f; But this is no more portable than your code, since there is no guarantee that the plat...
3,991,756
3,992,145
Custom avi/MP4 file writer
I am writing some video files under Windows from a camera. I need the data unaltered - not MP4's 'uncompressed' ie. no YUV, no color interpolation - just the raw camera sensor bytestream. At the moment I am writing this direct to disk and re-reading it later to recode into a usable video. But with no header I have to k...
Well, after figuring out what 'reasonable' AVI headers would be for your stream (e.g. if you use a custom codec fourcc, no application would probably be able to do useful things with it -- so why bother with AVI?) you could just write a prebuild RIFF-AVI header at the beginning of your file. It's not too hard to figure...
3,992,171
3,992,188
How do I programmatically get the free disk space for a directory in Linux
Is there a function that returns how much space is free on a drive partition given a directory path?
check man statvfs(2) I believe you can calculate 'free space' as f_bsize * f_bfree. NAME statvfs, fstatvfs - get file system statistics SYNOPSIS #include <sys/statvfs.h> int statvfs(const char *path, struct statvfs *buf); int fstatvfs(int fd, struct statvfs *buf); DESCRIPTION The ...
3,992,237
3,992,292
correct idiom for character string (not std::string) constants in c++
A while ago I asked about std::string constants correct idiom for std::string constants?. What I took away from that was not to use std::string constants but to use char string constants. So what the best idiom for that #define FOO "foo" const char * const FOO = "foo"; const char FOO[] = "foo"; Desirable features g...
Your desired features are contradictory. Length at compile time Defined in header file Single copy across compilation units To get (1) and (2), you need to declare the variable as static or put it in an unnamed namespace. However, this will cause a definition in each compilation unit, which goes against (3). To get (...
3,992,246
3,992,304
how to automate template typename specification with CLASSNAME<typename>(argument);
I'm creating a stat editor for some objects within a game world. Rather than have multiple edit menus for each object type, I just have one menu, and pass in a list/vector of stat-edit-objects which contain a pointer to the stat being edited, and the functions to do the work. struct StatEditObjPureBase { std::vecto...
Yes, you can use a factory function: // Note: Callee takes ownership of returned pointer // (Alternatively, you should consider using a smart pointer like shared_ptr) template <typename T> StatEditObj_INT<T>* MakeNew_StatEditObj_INT(T* p, iWindow& rIW, Editor& rE) { return new StatEditObj_INT<T>(p, rIW, rE); } Th...
3,992,425
3,993,390
C++ integration with Java in one project. Is it possible and how to do it?
So... I will have a project which will be tested on Win 7 and some Linux server. It will be a web service that will use HSQLDB, Hibernate, Spring, Blaze DS and Flash (Flex RIA) as front end. I need to implement into it some image filtering\editing functionality which will be implemented in cross-platform C++ code (It ...
It sounds like you'll benefit from the Java Native Interface. If you've got existing C and C++ code that you'd like to use from Java you may want to seriously consider something like GlueGen. It will save you a lot of time generating the code to access your C code. You can have a look at the official Java JNI Examples ...
3,992,547
3,992,565
Pointer not initializing with a struct as a parameter. Access violation writing location 0x00000010.
The struct looks like this: template <class Node_entry> Node<Node_entry>::Node(Node_entry item, Node *add_on) { entry = item; next = add_on; } And the *new_rear pointer does not get initialized, but &item is filled with user input. Error_code Extended_queue::append(const Queue_entry &item) { Node<Qu...
I assume you meant to say if (new_rear == 0), not if (new_rear = 0)? Your compiler should have given you a warning. EDIT: In case you are wondering why it crashes - well, you're assigning 0 to the pointers, which also makes the conditions evaluate to zero, so you end up in the else block with "rear" just freshly assign...
3,992,548
3,992,592
Bottleneck from comparing strings
This is a follow up question to Char* vs String Speed in C++. I have declared the following variables: std::vector<std::string> siteNames_; std::vector<unsigned int> ids_; std::vector<std::string> names_; I call this function tens of thousands of times and is a major bottleneck. Is there a more efficient way to compa...
Use a map or unordered map instead. Then you can do this: std::map<string, int>names_; // ... unsigned int converter::initilizeSiteId(unsigned int siteNumber){ unsigned int siteId = 0; std::map<string, int>::iterator i = names_.find(siteNames_[siteNumber]); if (i != names_.end()){ siteId = i->secon...
3,992,747
3,992,787
How to get the fully qualified path name in C++
Is there a function that returns the fully qualified path name for any inputted file? I'm thinking of something like: LPCSTR path = "foo.bar" LPCSTR fullPath = FullyQualifiedPath(path); //fullPath now equals C:\path\to\foo.bar Thanks
In Win32, call the GetFullPathName function.
3,992,874
3,992,970
std::map sort by data?
Is there a way to sort std::map by the data rather than the key? Right now my code duplicates the entire map in to an array just to do this.
As far as I can remember, std::map will give you the iterator that will go through the items sorted by the key. Only way to go through the sorted items by the value, and still use the map, is to rewrite whole collection to another map, with key and value reversed.
3,992,926
3,992,978
using "new this.GetType()" in a base class to instantiate a derived class
I have a base class A and classes B and C are derived from it. A is an abstract class, and all three classes have a constructor that takes 2 arguments. Is it possible to make a method in the base class A like this: A* clone() const { return new this.GetType(value1, value2); } and if the current object whose clone(...
This looks like C++.NET (a.k.a. "managed C++") rather than plain (standard) C++. I'm not an expert on this, but my guess (assuming .NET) would be that you'd have to use reflection to instantiate an object of a System.Type. The usual steps are: Create or get a suitable Type object, e.g. by calling GetType. Find a suita...
3,993,344
3,994,509
QT4 How to use static fields?
I am trying to use static fields in QT class MyLabel:public QLabel{ Q_OBJECT public: static QPixmap pix1; static QPixmap *pix2; static int WasInited; ... }; int MyLabel::WasInited = 0; MyLabel::MyLabel(){ . . . if (WasInited==0) pix1.load("pic.png"); // Error if (WasInited==0) pix2->load("pic.p...
static fields are like methods in a class. First you need to declare them, then you need to define their initial value. With QPixmaps it's a little bit different. As static members are initialized before main entry point. QPixmap requires QApplication to work, so you won't be able to make it static as variable, you may...
3,993,345
4,053,483
Queue appending more then one entry
I keep getting the first entry appended 4 times instead of one time.. when I append my first entry to the Queue it appends it 4 times..I thought this might be the problem..but it looks like it isn't. I can't find where the problem is.. I also created a print function for the nodes, and it showes that there are 4 of the...
It looks like the copy constructor had bad logic. After I fixed th constructor, the driver only returned the first term as front and rear entry. So I had to fix up the overloaded = operator as well. New Code(for copy constructor): Extended_queue::Extended_queue(const Extended_queue &original){ Node<Queue_entry> *te...
3,993,492
3,993,579
cannot access protected variable in derived class c++
I have a Binary Search Tree as a derived class from a Binary Tree, right now I am trying to access the root for my recursive functions (which is in the base class). But for some reason I keep getting the error: binSTree.h:31: error: ‘root’ was not declared in this scope Here are my class declarations: base class: tem...
I don't know why this is, but when sub-classing from template classes, in order to access members, you need to prefix them with the base class name. len = search( binTree<T>::root, x,len); My compiler, Visual C++, doesn't require this, but the standard does for some reason. Alternatively, you can put the line: using ...
3,993,510
3,993,521
In assignment operator function, is array being memcpy implicitly
OK. We know the following code cannot be compiled. char source[1024]; char dest[1024]; // Fail. Use memcpy(dest, source, sizeof(source)); instead. dest = source; But, the following code can be compiled and behave correctly. class A { char data[1024]; }; A source; B dest; dest = source; I was wondering, in operato...
compiler generated copy-ctor / assignment-op is bitwise-copy if no copy-ctor / assignment-op found for the child elements. Edit: Here is the modified test case showing the concept. #include <cstdio> #include <memory> class someElement { public: someElement() : theData(0) {} // Intentionally copy-edit someE...
3,993,697
3,993,712
C++: what are the most common vulnerabilities and how to avoid them?
As I code, I try to be security-conscious all the time. The problem is that I need to know what to look for and what to prevent. Is there a list somewhere of the most common (C++) software vulnerabilities and how to avoid them? What about C++ software for specific uses, e.g. a linux console software or a web applicatio...
Many resources are available, some in question are: SEI CERT C++ Coding Standard SEI CERT C Coding Standard The more language-agnostic Writing Secure Code book from Microsoft Press (funny, I know) David Wheeler's Secure Programming in Linux/Unix
3,993,717
3,993,755
why QTextEedit can't gain focus even when i clicked it, in symbian device
i place a QTextEdit widget into a QWidget class(the QTextEdit's parent widget),but when the parent widget show,i clicked the QTextEdit,but it can't gain focus.how this situation comes?
I don't know anything about symbian development so this is only a guess. Check the focus policy for the text edit. You probably want Qt::ClickFocus or Qt::StrongFocus.
3,993,749
3,993,881
structure member access - command line
this may be a simple problem, but i am not able to figure it out. I have structure like this. struct emp { int empid; string fname; } emp e[10]; I have some data in e[10]. e[0].empid = 1 , e[0].fname = "tanenbaum" e[1].empid = 2 , e[1].fname = "knuth" ..... Now if i have given input command line like this: e...
EDIT: Using pointer to member operator you can achieve what you wanted. You need to create small database using std::map. Below is the working program. #include <iostream> #include <string> #include <map> using namespace std; struct emp { int empid; int salary; }; int main(int argc, char *argv[]) { //member m...
3,993,811
3,993,888
std::vector iterator incompatibles
I have an error (vector iterator incompatibles) during execution in my C++ program that I do not understand. [ (Windows / Visual C++ 2008 Express) ] Here is a simplified version of my problem : #include <vector> class A { int mySuperInt; public: A(int val) : mySuperInt(val) {} }; class B { std::vector<A*> ...
Your getA() function returns a vector by value. You're initializing your loop iterator to the beginning of that vector, but since the returned vector is temporary, it is destroyed at the end of that line. // at the end of this line the vector returned by getA is gone, so it_A is invalid. std::vector<A*>::const_iterator...
3,993,966
3,994,572
extern storage class specifier
Section 7.1 of the C++ Standard mentions about 'extern' as a storage class specifier. N3126 - "The extern specifier can be applied only to the names of variables and functions. The extern specifier cannot be used in the declaration of class members or function parameters. For the linkage of a name declared ...
extern is a storage class specifier. This is just a fact of the language grammar. extern has a number of effects on the semantics of a program depending on where it is used. It doesn't have the single same effect everywhere. It influences the storage duration and linkage of objects and it also helps determine whether s...
3,994,244
3,994,282
Difference between stateless and stateful compression?
In the chapter Filters (scroll down ~50%) in an article about the Remote Call Framework are mentioned 2 ways of compression: ZLib stateless compression ZLib stateful compression What is the difference between those? Is it ZLib-related or are these common compression methods? While searching I could only find stateful...
From Transport Layer Security Protocol Compression Methods: Compression methods used with TLS can be either stateful (the compressor maintains it's state through all compressed records) or stateless (the compressor compresses each record independently), but there seems to be little known benefit i...
3,994,394
3,994,444
Using C++ code in VIsual C++, no errors but some part of the code is just ignored
I'm an absolute beginner to programming and i'm just doing some exercises exercises for the beginning. First of all, i'm using Visual C++ 2010 to compile C-Code. I just create a new project and choose an empty console application. After that, I create a ressource file named test.c and change in the file properties the...
It's not ignored. When you type your second number, then hit enter, it puts your number plus a newline character in the input stream. scanf removes the number, but leaves the newline character alone. When you call cin.get(), since there's a character in the stream, it doesn't wait for your input.
3,994,500
3,994,566
C4503 warnings? How do i solve/get rid of them?
It's my first time trying out C++ STL. I'm trying to build a multidimensional associative array using map. For example: typedef struct DA { string read_mode; string data_type; void *pValue; void *pVarMemLoc; }DA; int main() { map<string, map<string, map<string, map<string, map<string, DA*>>...
If you intend to keep this monster of a data structure, there is little you can do about the warning other than disable it: #pragma warning(disable:4503)
3,994,585
4,093,474
C++ iptables libipq create multiple queues at same time
How can I create two different ip_queues, running at the same time? One of it can listen for incoming packets on one port and another can listen for outgoing packets on the same port.
It cannot be done :(
3,994,589
3,994,607
Any way to reuse an identifier within a scope?
Normally using the same identifier like name of a variable for something like another variable within the same scope generates error by compiler, Is there any technique to actually indicate to compiler that in this scope up to this specific point this name has its own purpose and is used to refer to this variable but a...
If you mean variables, no, there's not. When you create a variable, it's tied to a specific type and a specific location. Having said that, there's nothing stopping you from re-using the same variable for two different things: float f = 3.141592653589; // do something with f while it's PI f = 2.718281828459; // now do ...
3,994,676
3,994,852
MFC Treeview : How to apply different images to different nodes in Treeview?
I want to apply different images to different nodes in my MFC Treeview ? Currently i have have applied one image to my treeview root node now i want to apply different image to subnodes and how to expand all nodes in treeview , once i expand one node other get collapsed.. Currently i am doing like this : CImageLis...
You can use BOOL SetItemImage(HTREEITEM hItem, int nImage, int nSelectedImage); it within CTreeCtrl class. UPD: Import your bitmaps in your resource pain and load them: CBitmap m_Bitmap1, m_Bitmap2, m_Bitmap3, m_Bitmap4; m_Bitmap1.LoadBitmap(IDB_BITMAP1); m_Bitmap2.LoadBitmap(IDB_BITMAP9); m_Bitmap3.LoadBitmap(IDB_BITM...
3,994,747
3,996,789
Get attribute using XPath with TinyXPath & TinyXML
I'm trying to write a function that will get me the attribute of a set of XML nodes in a document using XPath with the TinyXPath library, but I cannot seem to figure it out. I find the documentation on TinyXPath is not very enlightening either. Can someone assist me? std::string XMLDocument::GetXPathAttribute(const s...
If you just use @myattribute, it will look for that attribute attached to the context node (in this case, the document element). If you are trying to evaluate whether the attribute is anywhere within the document, then you have to change your axis in your XPATH. If you are trying to evaluate whether the attribute is...
3,994,801
3,995,765
What are the security implications of using boost/format?
I am starting to use boost/format. When coding with boost/format, what should I pay attention to with regard to security? Can I do the following without being concerned about security? std::cout << boost::format("Hello %2%! Do you want to %1%?") % user_supplied_str1 % user_supplied_str2 << std::endl; What are si...
Your example is safe. In fact, it was safe with printf. Like printf, Boost.Format only parses its format string once, so there's no chance to insert extra format specifiers. Passing an incomplete format object to boost::format throws an exception. I guess what you're afraid of are format string exploits. Those are, I t...
3,994,890
3,994,954
Finding max_element of a vector where a member is used to decide if its the maximum
Consider a class A having a member x and a std::vector< A >. Now its a common task to search for the maximal x among all elements inside the vector. Clearly I can only use std::max_element if there is an iterator on the x's. But I must write one by my own, or I just make a simple for loop. maxSoFar = -std::numeric_limi...
If you can use boost then you can write a lambda expression for the binary predicate expected by max_element: struct A { A(int n): x(n) { } int x; }; using namespace std; using namespace boost::lambda; int main() { vector<A> as; as.push_back(A(7)); as.push_back(A(5)); as.push_back(A(3)...
3,994,950
3,994,979
Why can we delete arrays, but not know the length in C/C++?
How is is that it is possible for us to delete dynamically allocated arrays, but we can't find out how many elements they have? Can't we just divide the size of the memory location by the size of each object?
In C++, both... the size (bytes) requested by a new, new[] or malloc call, and the number of array elements requested in a new[] dynamic allocation ...are implementation details that the Standard doesn't require be made available programatically, even though the memory allocation library must remember the former and ...
3,995,060
3,995,250
GCC 4.2 Template strange error
i have the following code compiled with GCC 4.2 / XCode. template <typename T> class irrProcessBufferAllocator { public: T* allocate(size_t cnt) { return allocProcessBufferOfType<T>(cnt); } void deallocate(T* ptr) { if (ptr) { releaseProcessBuffer(ptr); ...
Just to make sure, you are not missing necessary includes: <cstddef> for std::size_t and <new> for placement new? Otherwise those functions would appear to be correct. If that is the entire allocator, it has other flaws, such as missing required typedefs, address() and max_size() methods, as well as a rebind template. ...
3,995,358
3,995,462
How to document overridden/implemented functions without Doxygens @copydoc?
How can I document an overridden method or an implemented virtual method of a sub class? Should I use @copydoc? class A { /** * A detailed description........ */ virtual int foo(int i); } class B : public A { /** {I won't write the same description again.} */ int foo(int i); }
If the method is overridden it probably has different behavior than the subclass implementation. In that case you should just rewrite the documentation for that method. If you want the same documentation regardless, you can use the INHERIT_DOCS option.
3,995,516
3,995,633
Calculating a Random for C++
This is probably a super easy question, but I just wanted to make 10000% sure before I did it. Basically Im doing a formula for a program, it takes some certain values and does things when them.....etc.. Anyways Lets say I have some values called: N Links_Retrieved True_Links True_Retrieved. I also have a % "scalar" i...
rand() is a very simple Random Number Generator. The Boost libraries include Boost.Random. In addition to random number generators, Boost.Random provides a set of classes to generate specific distirbutions. It sounds like you would want a distribution that's random between 1% and 10%, i.e. 0.01 and 0.1. That's done wit...
3,995,594
3,995,620
Constructing associative containers
I was convinced (until I just tried it a moment ago) that it was possible to instantiate an associative container with array style notation. For example, std::set< int > _set = { 2, 3, 5 }; This isn't the case but I am wondering if there is any other way of bulk initialising a container in the constructor like this?
You can use Boost.Assign. std::set< int > _set = boost::assign::list_of(2)(3)(5);
3,995,631
3,996,130
C++ call back system. Pointers to member functions
Im trying to create a call back by passing a pointer to member functions but am running into all types of issues. How can i go about implementing such a thing template<class T> class A{ void (T::*callBackFunction)(int); public: void addCallBack(void (T::*callBackFunction)(int)){ void (T::*cal...
You could do something like this. The virtual base class BaseCB allows B to be totally unaware of the type of C but still invoke the callback. class BaseCB{ public: virtual void operator()(int x)=0; }; template<class ClassT> class CCallback : public BaseCB { public: typedef void(ClassT::* FuncT)(int); FuncT _fn;...
3,995,823
3,995,833
Instantiate object of a class before main() executes
Is it possible to instantiate an object of a class even before main() executes? If yes, how do I do so?
Global objects are created before main() gets called. struct ABC { ABC () { std::cout << "In the constructor\n"; } }; ABC s; // calls the constructor int main() { std::cout << "I am in main now\n"; }
3,995,827
4,013,323
SDL_SetVideoMode problems
I'm using SDL_Image to display a JPEG on screen and having some issues with the resolution it's being displayed at. I understand that if I pass 0 to width, height and bits when calling SDL_SetVideoMode that SDL takes the current modes values, however these seem to be wrong in my case. I'm running this on an embedded li...
This was fixed by adding the custom resolution to /etc/fb.modes like so: mode "1280x720-59" # D: 172.00 MHz, H: 82.700 kHz, V: 66.00 Hz geometry 1280 720 1280 720 16 timings 13000 300 70 26 3 80 5 endmode Still no fix for the SDL_SetVideoMode hanging as referenced in my above comment...
3,995,942
4,006,595
Is FC++ used by any open source projects?
The FC++ library provides an interesting approach to supporting functional programming concepts in C++. A short example from the FAQ: take (5, map (odd, enumFrom(1))) FC++ seems to take a lot of inspiration from Haskell, to the extent of reusing many function names from the Haskell prelude. I've seen a recent article ...
I'm the primary original developer of FC++, but I haven't worked on it in more than six years. I have not kept up with C++/boost much in that time, so I don't know how FC++ compares now. The new C++ standard (and implementations like VC++) has a bit of stuff like lambda and type inference help that makes some of what...
3,996,049
3,996,071
cpp file #include causing errors, @class not
In an iPad app im using a thirdParty cpp file that acts as a controller for some UI functionality; its wired up with IB and a @class definition is all i need. However now I'm trying to set a delegate on the cpp file and therefore have to include it in the implementation of my viewController. including the cpp header in...
Change the suffix of your files from .m (Objective-C) to .mm (Objective-C++).
3,996,416
3,996,435
Using a pointer to a function as a template parameter
(C++) I've got a number of Entry classes, and got BaseProcessor interface which incapsulates Entry processing logic. (see code below) The Entry doesn't provide operator<(). The BaseProcessor provides a pointer to less(Entry, Entry) function which is specific for particular BaseProcessor implementation. I can use the fu...
Have you tried this? typedef std::set<Entry, LessFunc> EntrySetImpl; EntrySetImpl entries(lessfunc); Note that you need to specify the type of your comparison function or object as a template parameter to set, and then give it an instance of the comparison function or object when you actually create a set. I'll edit ...
3,996,474
3,996,520
find int inside struct with find_if for std::list with structs
How can I use find_if with a std::list if the list contains structs? My first pseudo code attempt at this looks like this: typename std::list<Event>::iterator found = find_if(cal.begin(), cal.last(), predicate); The problem here is that the predicate is not directly visible in the list but inside event.object.re...
You can use a functor class (which is like a function, but allows you to have state, such as configuration): class Predicate { public: Predicate(int x) : x(x) {} bool operator() (const Cal &cal) const { return cal.getter() == x; } private: const int x; }; std::find_if(cal.begin(), cal.end(), Predicate(x));...
3,996,506
3,997,632
Why would I start a debug build without debugging?
Is there any benefit in starting a debug build without debugging (as opposed to a release build without debugging)? And what do I miss when I debug a release build (as opposed to debugging a debug build)?
To add to Adrians answer and as a general point when talking about debug vs. release builds: Here are some factors that influence your builds: You link against either the debug or the release runtime libs (/MD vs. /MDd) NDEBUG (release mode) or _DEBUG (debug mode) is #defined _SECURE_SCL (or some equivalent) is define...
3,996,713
3,996,764
C++ matrix size depending input doesn't compile
there is a topic about this subject which is working with arrays but I can't make it work with matrices. (Topic: C++ array size dependent on function parameter causes compile errors) In summary: long rows, columns; cin >> rows >> columns; char *a = new char [rows]; compiles great in visual studio, but: ch...
The array-new operator only allocates 1-dimensional arrays. There are different solutions, depending on what sort of array structure you want. For dimensions only known at runtime, you can either create an array of arrays: char **a = new char*[rows]; for (int i = 0; i < rows; ++i) { a[i] = new char[columns]; } or ...
3,996,855
3,996,964
Reference to uninitialized object iniside constructor
It is possible to pass uninitialized object to a parent class like in the following example class C { public: C(int i): m_i(i) {}; int m_i; } class T { public: T(C & c): m_c(c) { }; C & m_c; }; class ST : public T { public...
You can, but you get undefined behavior. In Boost's utilities, you'll find the base-from-member idiom created by R. Samuel Klatchko. Basically, you make a private base in the place of the private member. This base gets initialized first, and you can use it for other bases: // ... class C_base { public: C_base(int ...
3,997,056
3,997,358
class containing a generic type of a child
Is there any possible way that a generic type can be used to contain a child of a base class. From the assignment given to me, I am to create something similar to the following in structure. template <class T> class Fruit { private: int count; int location_id; T type; public: virtual void displayInf...
This is perfectly fine, in principle. Read up about Curiously Recurring Template Pattern (CRTP) for more info on usage of derived class as the instantiating type in a class template that is its base, esp the example about static polymorphism which should look 'curiously' familiar. template <class Derived> struct Base...
3,997,099
3,997,165
Why this error? "no appropriate default constructor available"
Someone has given me the following C++ code snippet to try out - and now I have lost contact with them (its a long story). Anyway, it won't compile - I get an error error C2512: 'mstream' : no appropriate default constructor available Can anyone explain why, and what is needed to fix it. class mstream : private ostr...
ostream has no default constructor; the implicitly created default constructor for mstream is invalid because of it. You need to provide the ostream with a stream buffer: class mstream : private ostream { public: mstream() : ostream(/* whatever you want */) {} /* Maybe this is more appropriate: ms...
3,997,121
3,997,150
C++ - boost get question
Does someone know if the boost::get for the boost::variant is a performance-consuming operation or not. Right now I am refactoring some old code in a performance-critical part, where "varianting" was implementing by containers for each possible types and corresponding enum. Obviously, this is fast, but ugly and right n...
You could still write a simple test-application to compare the two, it doesn't have to be the production environment. A colleague of mine had a similar problem to this one recently. In his scenario there where objects of different types, but he always knew beforehand which type he expected. Also his data-structure was ...
3,997,274
3,997,331
how do I make a makefile depend on the build options
A long time ago, I remember using some Solaris make, and they had an ingenious option that would automatically detect when the compiler options had changed, and rebuild all rules appropriately. For example, suppose I switch from: g++ -O3 to g++ -g Then all files should be recompiled. I'm using gnu make, and haven't ...
A simple way to achieve this with gmake is to write the gcc options into a file. Then, in the Makefile, read these options to a variable, use this variable in the gcc command line, plus add the dependency for all object files to this option file (can be done in the pattern rule).
3,997,404
3,997,731
Initialization of member: bug in GCC or my thinking?
I've got an enum type defined in the private section of my class. I have a member of this type defined as well. When I try to initialize this member in the constructor body, I get memory corruption problems at run-time. When I initialize it through an initialization list in the same constructor instead, I do not get me...
For posterity: It appears as though the make script isn't pickup up the changes to these files for some reason. Manually deleting the objects rather than letting our "clean" target in the makefile caused a full rebuild (which took some time), and the problem disappeared.
3,997,700
3,997,733
Can we create static array with a size that is an execute-time constant?
We all know the basic rules for static array: int size = 20; char myArray[size]; is not legal. And. const int size = 20; char myArray[size]; is OK. But, what about this. int f(const int size) { char myArr[size]; } void main() { f(2); f(1024); } MSVC says it is an error, gcc seems to compile and execute it...
No. C++ has no variable-length arrays. C99 does, and gcc allows it via extension. Use a std::vector. Assuming you have profiled your application and found this to be a bottleneck, write a custom allocator that allocates from the stack and use that. If not, there's not a problem. Stack allocation is very fast, but thi...
3,998,215
3,998,296
removeItemAtPath on a file already open
I have a file open on the iPhone that I am sending the data of across the network (Opened using "_open"). However I have the ability to delete files from the iphone's interface. This is done using NSFileManager's removeItemAtPath. The odd thing is that removeItemAtPath is succeeding even though the file is currently ...
According to the documentation at http://developer.apple.com/library/ios/documentation/cocoa/reference/foundation/Classes/NSFileManager_Class/Reference/Reference.html#//apple_ref/occ/instm/NSObject/fileManager:shouldRemoveItemAtPath: shouldRemoveItemAtPath returns YES if the operation should proceed, not necessarily th...
3,998,228
3,998,451
How can I store the Output of System function to a string
While I try the following: system( "ifconfig -a | grep inet | " "sed 's/\\([ ]*[^ ]*\\)\\([ ]*[^ ]*\\).*$/\\1 \\2/' " " > address.txt" ) ; I am getting the output in a file. How can I assign the out put to a variable.
EDIT: the best way to do this as recommended in @Paul R's comment, is to use _popen and read in the command output from stdin. There is sample code at that MSDN page. ORIGINAL EFFORT: One option would be to create a temp file using tmpnam_s, write your output there instead of hard-coding the filename, and then read it...
3,998,291
3,998,660
Difference between "MyClass& func1(void)" and "MyClass* func2(void)"
Possible Duplicate: What is the proper way to return an object from a C++ function ? Hi there, i would like to know whats the difference between the following two functions with respect to the return types? MyClass& func1(void) MyClass* func2(void) I always thought this would be the same? Heinrich
The first one is only capable of returning a reference to a single object and may not be null. Or rather, it should not be null. The second one may be returning the pointer to a single object, or an array of objects. In cases where you wish to return a single object that cannot be null, #1 tends to be the preferred for...
3,998,368
3,998,396
Calling a non-void function without using its return value. What actually happens?
So, I found a similar question here, but the answers are more about style and whether or not you are able to do it. My question is, what actually happens when you call a non-void function that returns an object, but you never assign or use said returned object? So, less about whether or not you can, because I absolutel...
I believe that for both C# and Java, the result ends up on the stack, and the compiler then forces a pop instruction to ignore it. Eric Lippert's blog post on "The void is invariant" has some more information on this. For example, consider the following C# code: using System; public class Test { static int Foo() ...
3,998,400
3,998,606
Is it worth writing part of code in C instead of C++ as micro-optimization?
I am wondering if it is still worth with modern compilers and their optimizations to write some critical code in C instead of C++ to make it faster. I know C++ might lead to bad performance in case classes are copied while they could be passed by reference or when classes are created automatically by the compiler, typi...
I'm going to agree with a lot of the comments. C syntax is supported, intentionally (with divergence only in C99), in C++. Therefore all C++ compilers have to support it. In fact I think it's hard to find any dedicated C compilers anymore. For example, in GCC you'll actually end up using the same optimization/compilati...
3,998,411
3,998,570
Distributing DLLs Inside an EXE (C++)
How can I include my programs dependency DLLs inside the EXE file (so I only have to distribute that one file)? I am using C++ so I can't use ILMerge like I usually do for C#, but is there an easier way to automatically do this in Visual Studio? I know this is possible (thats why installers work), I just need some help...
There exist two options, both of which are far from ideal: write a temporary file somewhere load the DLL to memory "by hand", i.e. create a memory block, put DLL image to memory, then process relocations and external references. The downside of the first approach is described above by Nate. Second approach is possi...
3,998,682
3,998,709
Allocate Virtual memory before running out of RAM
is it possible, in a C/C++ program, to allocate virtual memory (Swap Space) for an specific array, so that the program keeps using RAM for the rest of variables, and maybe getting some benefit at some type of problems??
For the first part: in pretty much every modern OS, there is a way to map files to a memory location. You could do so and use the file as the "swap space" you describe. The POSIX standards define mmap (which is usable through Linux and Mac OS) and Windows has MapViewOfFile. For the second part: it heavily depends on th...
3,998,978
3,999,018
Using a const key for unordered_map
I've been switching my code over from std::map to std::unordered_map where appropriate. With std::map, I typically write the following just to make sure the key cannot be modified: std::map<const std::string, int> Frankly, I never checked if this const was of any value. This has always compiled and worked with g++. ...
The associative containers only expose the (key,value) pair as std::pair<const key_type, mapped_type>, so the additional const on the key type is superfluous.
3,999,120
3,999,144
Data structure for a random world
So, I was thinking about making a simple random world generator. This generator would create a starting "cell" that would have between one and four random exits (in the cardinal directions, something like a maze). After deciding those exits, I would generate a new random "cell" at each of those exits, and repeat whenev...
A map< pair<int,int>, cell> would probably work well; the pair would represent the x,y coordinates. If there's not a cell in the map at those coordinates, create a new cell. If you wanted to make it truly infinite, you could replace the ints with an arbitrary length integer class that you would have to provide (such as...
3,999,157
3,999,194
System Error 0x5: CreateFileMapping()
I wish to implement IPC using Named Shared Memory. To do this, one of the steps is getting a handle to a Mapping Memory Object, using CreateFileMapping(). I do it exactly as MSDN website reccommends: http://msdn.microsoft.com/en-us/library/aa366551(v=VS.85).aspx: hFileMappingHandle = CreateFileMapping ( I...
Looks like you don't have enough privileges. From MSDN: Creating a file mapping object in the global namespace from a session other than session zero requires the SeCreateGlobalPrivilege privilege. For more information, see Kernel Object Namespaces. ... The creation of a file-mapping object in the global...
3,999,226
3,999,376
c++ templates without "typename" or "class"
i'm used to write templates like this: template<typename T> void someFunction(SomeClass<T> argument); however - now I encountered templates in another thread written like this: template<U> void someFunction(SomeClass<U> argument); as far as i know one can use "typename" and "class" interchangably (except for some det...
That code is wrong (typo). There must be a typename or class in this situation. The one with class compiles. The one without fails with error: ‘U’ has not been declared. However, it does not mean that all template parameters must start with a typename/class. This is because besides types, a template parameter can a...
3,999,317
3,999,340
"Virtual" and Header Files
I have Foo.hpp and Foo.cpp, i'd like to define a virtual function virtual void setValue(int val){ } Would the following implementation be correct: Foo.hpp #ifndef _FOO #define _FOO class Foo{ public: Foo(); virtual void setValue(int val); }; #endif Foo.cpp Foo::setValue(){ } I realise it would be easier ...
Your example won't compile, because the function signatures are different between your cpp and hpp, but you have the right idea. If your function is void, there is no need to return, either.
3,999,397
3,999,530
boost::shared_array and aligned memory allocation
In Visual C++, I'm trying to dynamically allocate some memory which is 16-byte aligned so I can use SSE2 functions that require memory alignment. Right now this is how I allocate the memory: boost::shared_array aData(new unsigned char[GetSomeSizeToAllocate()]); I know I can use _aligned_malloc to allocate aligned me...
boost::shared_array has a constructor that takes a deleter as a second argument to be used instead of default delete[]. This means you might be able to pass the address of a suitable deallocation function just like that. boost::shared_array<X> array(allocate_x(100), &deallocate_x); References: Boost.SharedArray