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
6,416,019
6,416,118
Inherit a class as static
I have the following structure in C++: class A { protected: int a; }; class B : public A { public: static void initThreads(); //Initialize threads (pthreads) /* Threads */ static void* send(void*); static void* receive(void*); } These functions "send" and "receive" operate on "a". But a non-static member c...
Static member functions don't work on non-static members because they don't have an object attached to them; they are missing the implied this pointer that gets passed invisibly to non-static member functions. The way around this is to explicitly pass a pointer to an object to work with. Your static function will have ...
6,416,117
6,416,361
Simple object detection using OpenCV and machine learning
I have to code an object detector (in this case, a ball) using OpenCV. The problem is, every single search on google returns me something with FACE DETECTION in it. So i need help on where to start, what to use etc.. Some info: The ball doesn't have a fixed color, it will probably be white, but it might change. I HAVE...
Well, basically you need to detect circles. Have you seen cvHoughCircles()? Are you allowed to use it? This page has good info on how detecting stuff with OpenCV. You might be more interested on section 2.5. This is a small demo I just wrote to detect coins in this picture. Hopefully you can use some part of the code ...
6,416,198
6,416,767
What is wrong with my following code
I am writing coin change algorithm. Algorithm is taken from http://ace.cs.ohiou.edu/~razvan/courses/cs404/lecture19.pdf Following is my code till now: #include <vector> #include <iostream> #include <string> int compute_change(std::vector<int> &d, int n) { int k = (int)d.size(); std::vector<std::vector<int> > C...
You seem to have mixed up the 0-based indexes of C++ arrays vs 1-based indexing used in the algorithm. That is, d[1] in the algorithm is d[0] for this code. But in a few places you also used 0 based indexes. You may want to double check all array indexes.
6,416,259
6,416,495
How to automatically include C++ headers in vim?
Often I want to use STL functions and containers and I find myself having to add manually: #include <vector> using std::vector; to the beginning of the file. Is anyone aware of a vim plugin or command line program that will do that sort of thing automatically?
It's a pretty uphill battle once you start to want some fancy IDE behavior from vim, especially once it requires code parsing. You should decide what's more important to you, using vim as an editor, or getting coding assistance. If the former is more important to you, stick with vim; otherwise, consider getting a dece...
6,416,294
6,416,324
Pointer in macro parameter list
I am currently attempting to define a function based on a compiler flag. If the TRACE flag is set, then I want to define a macro to pass information to a trace component. #define TRACERPTR(Reporter * pReporter, traceComponent eComponent, traceLevel eLevel, string sFormat, formatArgs...) \ if (pReporter != NULL) { pRepo...
To my knowledge, in C, at least, macro parameters aren't typed. It's all symbol substitution. Just use pReporter rather than Reporter * pReporter or Reporter pReporter. (The same applies to the other parameters for your macro, I suppose.)
6,416,364
6,416,400
Setting last 8 bytes of char array to __uint64
I'm implementing the SHA1 algorithm from the pseudocode on wikipedia. It says I should append to original length as 64 bits to the message, so I tried the following: // new_message is of type char[] and is 9+ bytes long *((__int64*)(new_message-8)) = (__int64) length; This makes the new_message's memory corrupt. Could...
Not definitively, without seeing the part of the code that shows what new_message is set to. It looks like you are underflowing the buffer though, which will mess up the heap header that probably precedes &new_message[0]. You are writing your __int64 8 bytes before the start of the char[], by the look of things.
6,416,385
6,416,522
Move semantics == custom swap function obsolete?
Recently, many questions pop up on how to provide your own swap function. With C++11, std::swap will use std::move and move semantics to swap the given values as fast as possible. This, of course, only works if you provide a move constructor and a move assignment operator (or one that uses pass-by-value). Now, with tha...
It is a matter of judgment. I will typically let std::swap do the job for prototyping code, but for release code write a custom swap. I can usually write a custom swap that is about twice as fast as 1 move construction + 2 move assignments + 1 resourceless destruction. However one may want to wait until std::swap ac...
6,416,533
6,416,621
Bignum Vector Usage in C++
What do I do to make a vector contain GMP bignum double values in C++. My code only works up until over a million. Here's what I have in my code now: vector<double> Primes; What should it be? I have checked and I can't find anything about this. Is the use normal.
That's not a GMP big double, that's a standard built-in C++ double. What about this? std::vector<mpf_class> Primes; But since you (seemingly) are putting primes in a vector I suspect you want integers, not floating point numbers. Then this is appropriate: std::vector<mpz_class> Primes;
6,416,604
6,418,083
Boost asio-acceptor unblocks without a new connection?
I am using the C++ boost asio library, where I listen to new connections on the socket. On getting a connection I process the request and then listen for a new connection on another socket in a loop. while (true) { tcp::socket soc(this->blitzIOService); this->blitzAcceptor.listen(); boost::system::error_cod...
What could be the reason to this behavior? This behavior is entirely dependent on the client code. If it connects, but does not send a request, the server with block when receiving data. how can I ensure that it always block at this->blitzAcceptor.accept(soc,ec) until a new request is made? You can't. But you...
6,416,862
6,416,941
How to derive from/extend a recursive class
I have a recursive class, a kind of tree, that has instances of itself as member variables. For example: template<class T> class Tree { public: /* Constructors, etc. */ protected: T m_value; Tree<T> *leftChild; Tree<T> *rightChild; }; If I want to add a method that prints all the values using an in-order tra...
Template on the node type. template<typename T, typename NodeType = void> class Tree { NodeType node; T m_data; }; template<typename T> class Tree<void> { struct Node { Tree<T, void>* left; Tree<T, void>* right; }; Node node; T m_data; }; template<typename T> struct DerivedNode {...
6,417,124
6,417,155
Question about C++ Iterator `map`
In below codes, std::map<Key,Int>::iterator p; p = randomTable[chunk].find(value); if (p != randomTable[chunk].end()) { } else { } How does the p != randomTable[chunk].end() works? Does this mean, for all elements in randomTable that is not the last (end()) element?
find(value) will return the same as end() if value is not in the map. So if value is in the map, you'll go into the "if" branch, and if not, you'll go into the "else" branch. end() isn't actually a member of the map - it points to the "element after the end". This is a slightly odd idea, but it probably helps to thin...
6,417,362
6,417,527
Huge 2D arrays in C++
I'm working on some code that does image manipulation, and it reads every 16 bits from a raw image file and stores each block into an array. The array needs 1392 columns and 1024 rows. I'm reading in data blocks from the raw file with fread: fread(&q1[0][0], sizeof(uint16_t), NUM_COLS*NUM_ROWS*sizeof(uint16_t), fp)...
First, it's better not to presume that such an array will be too big. Most likely your platform does support a global array of a couple megabytes. Really you're not talking about a very big object at all. Second, an array of pointers is most useful when the row size varies within the array of arrays. For a graphics app...
6,417,438
6,418,288
c++: convert vector<char> to double
I am using vector<char> to send and receive data via socket. In this vector I stored data of different types. Unsigned Integer and Doubles. To decode the data from vector I am using copy function. vector<char> myVector = ... smth; double value = 0.0; copy(myVector.begin(), myVector.begin() + sizeof(value), &value); It...
It works with Integer without problem. But... It most certainly will not work for integers. At least not for integers where sizeof(int) > 1! Because it will not write to just one integer, but spread the bytes in myVector over sizeof(T) integers, thus overwriting random memory. (see nightcracker's answer) Please just ...
6,417,592
6,418,077
Method to automatically detect cases of incorrect find_first_of() and family
I am working on a software project and have found numerous examples where find_first_of(), find_first_not_of(), find_last_of(), and find_last_not_of() are incorrectly used. These std::string methods take a string argument for a set of characters to search for whereas, the developer really means to use compare(), find(...
This may actually be a situation where you need to visually inspect every call to find_first_of and friends. It doesn't seem like there would normally be a lot of calls, and you can tag them in some way as you verify that they are correct. By inspecting all the calls you have confidence that the existing issues are res...
6,417,609
6,418,289
Pointer to an array, what am i missing?
I'm relatively new to OpenGL and have been using the GLTools library it provides. One of the classes, GLTriangleBatch, in part, deals with batches of vertexs. The class has a global attribute pointer pVerts declared as follows: typedef float M3DVector3f[3]; M3DVector3f *pVerts; When an initializing function is called...
This is not so much a 3D graphics or OpenGL problem, but a lack of understanding how arrays work in C and C++. An array in C is a set of contigous address space backed by system memory. The contents are addressed by a base pointer and an offset against this base pointer, through a mechanism called pointer arithmetic. S...
6,417,786
6,418,039
constness for reference class members
I have a couple of classes one of which keeps reference to the object of other: class Inner {}; class Outer { Inner & in; public: Outer(Inner & in) : in(in) {} }; What if I have to create Outer object from const reference to Inner? Am I have to write specific class, say OuterConst, for this? UPD: Any neat so...
You could store a const reference, and use const_cast to cast the const away when needed. If you add some runtime checking, it's also safe. class Inner { /* ... */ }; class Outer { Inner const & in; bool const inIsConst; Inner & inMutable() { if (inIsConst) throw std::logic_error("...
6,417,795
6,417,987
how to create a container that takes one object of each kind?
I tried to create a container for posible metadata that can be attached to my objects. I can guarantee that there will be at most one object af each kind attached to my class but there is no limit for object of different type to attach. for example I can't attach two instances of wordInfo to an object but instances of ...
Create a wrapper class for std::type_info, similar to the following: class TypeWrapper { private const std::type_info &mInfo; public TypeWrapper(const std::type_info &info) : mInfo(info) { } // Functions required by a key into a std::map. }; Use TypeWrapper as your key into your map.
6,417,817
6,417,880
Easy way to remove extension from a filename?
I am trying to grab the raw filename without the extension from the filename passed in arguments: int main ( int argc, char *argv[] ) { // Check to make sure there is a single argument if ( argc != 2 ) { cout<<"usage: "<< argv[0] <<" <filename>\n"; return 1; } // Remove the extensio...
size_t lastindex = fullname.find_last_of("."); string rawname = fullname.substr(0, lastindex); Beware of the case when there is no "." and it returns npos
6,417,890
6,438,597
the error message of a lua function called with lua_pcall geting lost
I'm using lua 5.1 and I'm using lua to load functions that can then be called from C++. int Error = luaL_loadfile(LuaState, "Test.lua"); if(!Error) { Error = lua_pcall(LuaState, 0, LUA_MULTRET, 0); } if(Error) { std::cerr << "-- " << lua_tostring(LuaState, -1) << std::endl; lua_pop(LuaState, 1); } else { ...
The problem was with some bit of my code i had completely overlooked, in it i had another LuaStackBalancer object that was created and its destructor was called when the error was thrown resulting in the loss of the error message. ^^u Thank you all for your help and please forgive my stupidity
6,417,956
6,418,021
For an intermediate programmer, how hard would it be to modify Google Chrome OS and how would one go about it?
I think Chrome OS is based on Linux and written in C/C++. I haven't looked at the source but presumably it wouldn't be too hard to change some of the images and UI etc., but if I wanted to, for example, make it log into a proprietary account instead of Google's accounts on login, how hard would it be?
How about pulling down the source first and trying to build/install it yourself? If you feel that it's way overwhelming, then nobody can say it's easy for you. It's hard to answer "how hard" because there's not an exact standard about "how intermediate" or "how fast can you learn".
6,418,006
6,418,026
Are static objects deleted when an exception is thrown, or just local objects?
#include <iostream> #include <exception> using std::cout; using std::endl; class test { public: test() { cout<<"constructor called"<<endl; } ~test() { cout<<"destructor called"<<endl; } void fun(int x) { throw x; } }; int main() { try { static...
The test destructor is called after main exits. catch(int k) { cout<<"exception handler"<<endl; } // Added this line std::cout << "Main Exiting\n"; } Now testing > g++ test.cpp > ./a.out constructor called exception handler Main Exiting destructor called Static (static storage duration obj...
6,418,503
6,418,521
What is the difference between overloading operator= and overloading the copy constructor?
What is the difference between overloading the operator = in a class and the copy constructor? In which context is each one called? I mean, if I have the following: Person *p1 = new Person("Oscar", "Mederos"); Person *p2 = p1; Which one is used? And then when the other one is used? Edit: Just to clarify a little bit: ...
In your case neither is used as you are copying a pointer. Person p1("Oscar", "Mdderos"); Person extra; The copy constructor Person P2(p1); // A copy is made using the copy constructor Person P3 = p2; // Another form of copy construction. // P3 is being-initialized and it uses copy constru...
6,418,548
6,418,629
How can one determine the return type of a function at template instantiation time?
Is there a way to find out what the return type of a function (or even better of a function pointer) is ? I've got the following code, which breaks when I use a void function pointer, but works fine for any other return type. The error I get when using a void function pointer from gcc 4.5 is: error: void value not ig...
Try a template partial specialization on void: template <class F> class Instruction<F, void> { protected: F (func); public: template <typename T> Instruction(T const& f) { func = &f; }; template <typename A> void execute(A const& a) { (func)(a); }; template <typename A> void...
6,418,582
6,418,619
Can one override my const C++ member function returning a const pointer to a internal non-const array using const_cast?
I'm learning c++ and came across this const_cast operator. Consider the following example: class Test { private: char name[100]; public: Test(const char* n) { std::strncpy(name, n, 99); name[99]=0; } const char* getName() const { return name; } } Now a user can do Test t("hi"); const_cast<char*>(t.ge...
No this is not 'fine'. Though it is possible. But C++ doesn't force good behavior on programmers. It mainly allows you to declare things in a way that show their intended use. If a programmer decides to trick around that protection he should know what he is doing. Bjarne Stroustrup: Yes. That's the new cast syntax. Cas...
6,418,742
6,418,909
How to register an image manually (image registration)
I'm converting code from Matlab to C++, and one of the functions that I don't understand is imtransform. I need to "register" an image, which basically means stretching, skewing, and rotating my image so that it overlaps correctly with another image. Matlab's imtransform does the registration for you, but as I'm progr...
Raw C++ does not have any of the concepts you refer to built into it. However, there are many image processing libraries for C++ you can use that can do various transforms. DevIL and FreeImage should be able to do layering, as well as some transforms.
6,418,757
6,418,877
Porting allegro 4 to allegro 5
what is the allegro 5 version of this function? texture_number = allegro_gl_make_texture_ex(AGL_TEXTURE_MASKED, my_bitmap, GL_RGBA); Or do I need to do something completely different in allegro 5? I'm trying to load an image to be used as an openGL texture. Here is the full code. GLuint texture_number; ALLEGRO_BITMAP ...
Allegro 5 always uses either OpenGL or D3D. Therefore, all Allegro bitmaps are already textures. To get the OpenGL texture object associated with an Allegro bitmap, call al_get_opengl_texture. Note that due to sub-bitmaps, multiple bitmaps can use the same texture. So you will need to use al_get_opengl_texture_size and...
6,418,791
6,419,772
Requesting administrator privileges at run time
Is it possible to get a C++ application running in Windows to request administrator privileges from the operating system at run time? I know it can be done at compile time, but can't seem to find anywhere whether it can be done at run time. Thanks for your help! EDIT: What if I want the current instance to have elevate...
Not quite, but you can do the opposite—you can drop privileges if you already have them. So, you can have your program start out running as an Administrator, using one of the methods listed by Kate Gregory. Then, drop your unneeded privileges; see Dropping privileges in C++ on Windows for how to do that.
6,418,920
6,418,977
long for 12 digit number?
I'm trying to use long for 12 digit number but it's saying "integer constant is too large for "long" type", and I tried it with C++ and Processing (similar to Java). What's happening and what should I use for it?
I don't know in C++, but in C, there is a header file called <stdint.h> that will portably have the integer types with the number of bits you desire. int8_t int16_t int32_t int64_t and their unsigned counterpart (uint8_t and etc). Update: the header is called <cstdint> in C++
6,418,949
6,419,061
C++ file written with unallocated memory block
I was programming and a coding mistake caused problems: ofstream myFile; myFile.open("/home/guido/ejemplo.XX",ios::out | ios::binary | ios::trunc); ... buffer = new char; delete (buffer); //write into file with accidentally freed memory block myFile.close(); ... ifstream sameFile; sameFile.open("/home/guido/ejemplo.XX...
It's not really possible to know exactly why it crashed the way it did. That's why the C++ specifications calls it "undefined behavior": it is something that is outside of the language's definition. It might have executed correctly on some compilers/standard library implementations. It may have failed here due to memor...
6,419,032
6,419,226
Getting shogun ML library to work with python
I was trying to install shogun on Windows: http://www.shogun-toolbox.org/doc/installation.html but evidently it requires python 2.5 to work. I tried with python 3 and it didn't work. But then python 2.5 no longer exists. Does anybody know how to get it working with python without using python 2.5?
You won't get very far trying with Python 3 (which is not fully compatible with Python 2.x). Furthermore, the installation instructions say: "SHOGUN requires the standard linux utils like bash, grep, test, sed, cut, ldd, uname gcc g++ cat python" sounds like you are out of luck on windows, unless you resort to Cy...
6,419,117
6,419,626
signal and unlock order
void WorkHandler::addWork(Work* w){ printf("WorkHandler::insertWork Thread, insertWork locking \n"); lock(); printf("WorkHandler::insertWork Locked, and inserting into queue \n"); m_workQueue.push(w); signal(); unLock(); } I followed a tutorial and I got this. I was wondering if it is ok to cha...
First, there is no correctness issue here. Either order will work. Recall that whenever you use condition variables, you must loop on a predicate while waiting: pthread_mutex_lock(mutex); while (!predicate) pthread_cond_wait(cvar); pthread_mutex_unlock(mutex); By signalling after the unlock, you don't introduce any ...
6,419,158
6,419,182
C++, .NET: Will this leak memory?
I am wondering if this will cause a memory leak in C++. Let say we have a function in C++ in .NET: test() { char buffer[NUMBER_OF_BYTES]; while(forever) { for(int i=0;i < NUMBER_OF_BYTES;i++) { buffer[i] = serial->ReadChar(); } String^ serialData = gcnew ...
A new one will be created every time. It is allocated with the garbage collector though and so will be deleted when it is no longer referenced. I don't think you need to worry about it causing a memory leak - the only way that would happen is if sendDataOut stores the strings permanently in some collection somewhere, w...
6,419,170
6,419,222
What is the best way to append data in C++
I am working on a network programming and I need a data structure to append data for the packet segmentation problem. For example, if a client sent a packet of size 500 bytes and for some reason, server received the packet as smaller packets of size 250 bytes each. On server side, it parses the header and gets the si...
The MTU for ethernet is 1500 bytes and the minimum size of an ethernet packet is 64 bytes. Therefore, I would use an array of 24 cells, each holding up to 1500 bytes. While not space-efficient, this array will accomodate any possible packet arrangement.
6,419,244
6,419,255
Getting different output with printf and cout - C++
I have a string I am trying to print. when I used cout, it outputs perfectly but using printf leaves it mangled. Here is the code: int main ( int argc, char *argv[] ) { // Check to make sure there is a single argument if ( argc != 2 ) { cout<<"usage: "<< argv[0] <<" <filename>\n"; return 1; ...
it's because rawname is defined as a std::string. You need to use printf("rawname: %s", rawname.c_str()); The reason is that printf with the %s is expecting a null terminated C string in memory. Whereas a std::string stl string isn't exactly raw - it eventually null terminates in your situation, not sure if that's e...
6,419,335
6,419,361
Loop within IF statement condition
i just want to know if there is a way for a loop to be on the If statement condition? sample: if((string.contains(stringlist.hello().value(0),Qt::CaseInsensitive))||(string.contains(stringlist.hello().value(1),Qt::CaseInsensitive))||(string.contains(stringlist.hello().value(2),Qt::CaseInsensitive))) { ... } to be: if ...
That code will not compile; instead, you might try a solution that checks each condition and stores the result into a variable determining whether or not the condition is met: bool testCond = false; for(int i=0; i < stringlist.hello().size(); i++) { if (string.contains(stringlist.hello().value(i),Qt::CaseInsensitiv...
6,419,599
6,419,672
Will the inefficiency of the postfix ++/-- operators be optimised away for STL iterators?
I know that the postfix versions of the increment/decrement operators will generally be optimised by the compiler for built-in types (i.e. no copy will be made), but is this the case for iterators? They are essentially just overloaded operators, and could be implemented in any number of ways, but since their behaviour ...
In the specific case of std::vector on GNU GCC's STL implementation (version 4.6.1), I don't think there would be a performance difference on sufficiently high optimization levels. The implementation for forward iterators on vector is provided by __gnu_cxx::__normal_iterator<typename _Iterator, typename _Container>. Le...
6,419,740
6,428,624
Causes for ENOMEM from ::popen()
I have an application that mostly works, but am having one condition wherein the call to ::popen() gets an error with errno set to ENOMEM. The man page for ::popen() refers you to page for ::fork() which itself lists ENOMEM with this brief comment on Linux: The fork() function may fail if: ENOMEM Insufficient s...
I have confirmed that the ENOMEM resulted from not calling ::pclose() after repeated ::popen() and eventually running out of file descriptors.
6,419,829
6,419,947
Are friends supposed to be transitive in nested classes?
class private_object { private: struct make_public; friend struct make_public; static void method1() {} }; struct private_object::make_public { class nested_outer { void callFromOuter() { private_object::method1(); } // Should this be an error? class nested_inner { void callFromInne...
In C++03, nested class cannot access private and protected members of enclosing class by default (see §11.8/1). But if you make them friend of the enclosing classs, then they can access them. But again nested class of nested class is still not friend of the outermost enclosing class, the nested class of the nested clas...
6,419,937
6,427,800
Is QML the way to go if designing a game in Qt?
Was looking into making a game with Qt and was wondering if QML has gotten to the point yet where it could be used as a serious tool on the desktop. Have seen some post from Qt stating that they will be transitioning most things to QML eventually, so this seems like it may be the way to go, at least according to Qt. E...
It may depend on "how long" you want to wait before releasing your game. The Trolls/Qt are re-doing its "graphics stack" right now: Rather than historic "every-widget-renders-itself" (which is the wrong paradigm for games and rich mobile apps), they are re-implementing to a single graphics stack that renders the WHOLE...
6,419,994
6,420,008
How to check if a string has more than 256 bytes?
I have a "char []" output and its size is 256 bytes. I want to check if the string i am about to allocate to the output has more than 256 bytes in it. How can i check this? Does this mean the string cannot contain more than 256 characters??
You can use strlen() if you want to measure the length of any random string. Nothing in your question would dictate the string cannot contain more than 8 characters. If you want to provide a little more information, such as where the string is coming from and where it is stored, I may be able to provide additional sugg...
6,420,085
32,697,323
Is constexpr supported with lambda functions / expressions?
struct Test { static const int value = []() -> int { return 0; } (); }; With gcc-4.6 I get something like, error: function needs to be constexpr. I have tried multiple combinations of putting constexpr at various places, but no luck. Is constexpr supported for lambda functions as well (irrespective of return type sp...
Update: As of C++17, lambdas are permitted in constant expressions. Lambdas are currently (C++14) not allowed in constant expressions as per [expr.const]/(2.6), but they will once N4487 is accepted (which can be found in the working draft N4582): This proposal suggests allowing lambda-expressions in constant expres...
6,420,268
6,420,317
Compiler chooses wrong template function specialization
I'm desperately trying to get my specializations working but still having non-compilable code due to deducing arguments to incorrect one. Note, that the errors are not about defining the templates but about applying irrelevant operation in wrong template implementation. The reduced example of code demonstrating the pro...
Cmp(test1); Here, T is deduced from the argument to be Test. It is not deduced to be const Test& so your specialization is not a match, hence why the primary template is instantiated. You would need to make your specialization take a Test by value. With this declaration, the specialization is indeed used: template<...
6,420,329
6,420,441
Can I delete[] a pointer that points into an allocated array, but not to the start of it?
I'm wondering specifically about the following situation (which I discovered in some code I have to work with): SomeClass *ar = new SomeClass[2]; ar++; delete[] ar; This code seems to be working fine - i.e. not crashing (win32, built with VS2005). Is this "legal"? It certainly doesn't feel right.
No, it is undefined to pass any address to delete which was not returned by new. Here is the quote from the Standard. § 3.7.4.2-3 If a deallocation function terminates by throwing an exception, the behavior is undefined. The value of the first argument supplied to a deallocation function may be a null pointer value; if...
6,420,452
6,420,533
What is the "cached function" referring to in this code article?
In relation to this article: http://www.bottlenose.demon.co.uk/article/lru.htm What is the cached function he is referring to? I am thinking of using it but I do not understand what the purpose of that function is and I could not figure out the test code. I'm not familiar with boost test. An example of simple use wou...
It's just a function that you provide when you construct the object. The object's purpose is to cache the result of calling the function. So if the function is expensive to compute, but you tend to call it over and over with the same input, the expensive computation will run once and later invocations can access the c...
6,420,458
6,420,608
How to use a Judy array
I am interested in Judy Arrays and try to use it. But i had unable to do any useful thing using it. Every time it gives me casting errors.. Sample c++ code and the error given below. #include "Judy.h" #include <iostream> using namespace std; int main() { int Rc_int; // return code -...
According to the documentation, you have the _PValue and JudyArray parameters reversed. Make your call look like this: JSLI( _PValue, JudyArray, (uint8_t *) String); Also, try not compiling it as C++ code. So far, your test uses no C++ features. I bet it will compile as C code. It looks like JudyArray relies on the ...
6,420,459
6,420,524
How do C++ HTTPS libraries compare in terms of performance (e.g. memory footprint, CPU time, etc?)
I've seen several posts stating that one networking library is better than another because of functionality or ease of use, but I haven't seen anything related to performance. I've checked all over Google and I can't find any comparisons. I am starting a networking project soon and I would like to use either Poco or l...
It does not matter. The bottleneck is almost certainly going to be the network media, or whatever processing you're doing on top of the HTTPS connection. SSL is cheap in terms of CPU time. (Unfortunately it's not cheap in terms of network latency but the library performance does not matter there). Performance is alway...
6,420,548
6,420,760
Why are my font edges not smooth when drawn with the DrawText API?
When I draw text on an dc, the text comes out with rough edges, and on the multiple windows that this WindowProc handles, the text between each of them look different, which looks unprofessional. Is there a way to draw it so it comes out with crisp, smooth edges? case WM_PAINT: { GetClientRect(hwnd, &rect);...
Myriad Pro is an OpenType font, not supported by GDI. Pick a TrueType font instead.
6,420,560
6,420,662
Why does my call to 'wxGetTranslation' result in the compiler error "ambiguous call to overloaded function"?
c:\wxwidgets-2.8.11\include\wx\filename.h(497): error C2668: 'wxGetTranslation' : ambiguous call to overloaded function c:\bitcoin\src\util.h(191): could be 'const char *wxGetTranslation(const char *)' c:\wxwidgets-2.8.11\include\wx\intl.h(579): or 'const wxChar *wxGetTranslation(const wxChar ...
That's because the other function has 2nd parameter as default argument. See here I have simulated the same effect. Unfortunately compiler doesn't show the default argument inside the error message: //intl.h const wxChar *wxGetTranslation(const wxChar *c1, const wxChar *c2 = <something>); More precisely, void foo (con...
6,420,620
6,421,029
How can I read line-by-line using Boost IOStreams' interface for Gzip files?
I managed to integrate the boost Iostream APIs for reading zipped files. I followed the documentation in boost page and have the following code so-far: std::stringstream outStr; ifstream file("file.gz", ios_base::in | ios_base::binary); try { boost::iostreams::filtering_istreambuf in; in.push(boost::io...
1) Yes, the above code will copy() the entire file into the string buffer outStr. According to the description of copy The function template copy reads data from a given model of Source and writes it to a given model of Sink until the end of stream is reached. 2) switch from filtering_istreambuf to filtering_istream...
6,420,675
6,420,697
Create shared library using gcc
I have a .cpp (jSide.cpp) file and I want to create a shared library(jside.dll) using the gcc command. I get how to use the gcc command, but I need to include header files that is required for jni. Here are the locations of my header files: C:\Program Files\Java\jdk1.6.0_24\include C:\Program Files\Java\jdk1.6.0_24\inc...
use -I flag to specify directory of header files. C:\>gcc -dll -o JSide.dll -I"C:\Program Files\Java\jdk1.6.0_24\include" -I"C:\Program Files\Java\jdk1.6.0_24\include\win32" jSide.cpp note that this is one line.
6,420,709
6,420,726
Need to have empty string as a template parameter
I want to have a class that stores a pair of variables of different types, but I need to pass the zero or null defaults for the variables as template parameters. I can do so for int or doubles, but how do I do so for string? I know that that c++ currently does not have string parameters, but what are the laternative de...
You cannot pass non-integral types as template parameters, except for pointers and references. The best behaviour you could hope for is to pass a function which returns a "default" value for atype and btype.
6,420,725
6,420,745
convert image buffer to filestream
Something similar to this may have been asked earlier, I could not find an exact answer to my problem to decided to ask here. I am working with a 3rd party framework that has it's own classes defined to handle image files. It only accepts the file name and the whole implementation is around being able to open these fil...
If the framework only takes a file name, then you have to pass it a file name. Which means the data must reside in the file system. The portable answer is "write your data to a temporary file and pass the name of that". On Unix, you might be able to use a named pipe and fork another thread to feed the data through the...
6,420,752
6,420,768
How can I set the name of a process created with CreateProcess?
I am starting a process with CreateProcess following the formulas found on google. What I am wondering, is can I set the process name of the created process so that it is obvious in the task manager? Thank you, --Douglas
That's not an available option. The process name as visible in Task Manager is derived from the file name. If you want another name to show up then simply rename the EXE file.
6,420,969
6,420,989
How do I use vector as input buffer for socket in C++
I normally set up a huge size buffer and read data from socket and I realized that it is not a good way to read data. I used to have something like this int bufsize = 4096; char *buf; int recv = read(sock, buf, bufsize) I liked to use std::vector to replace the char buffer. I am not sure this is the better way though...
That's easy: std::vector<char> buf(4096); // create buffer with preallocated size int recv = read( sock, &buf[0], buf.size() );
6,420,985
6,455,451
How to force a static member to be initialized?
Consider this example code: template<class D> char register_(){ return D::get_dummy(); // static function } template<class D> struct Foo{ static char const dummy; }; template<class D> char const Foo<D>::dummy = register_<D>(); struct Bar : Foo<Bar> { static char const get_dummy() { return 42; } }; (...
Consider: template<typename T, T> struct value { }; template<typename T> struct HasStatics { static int a; // we force this to be initialized typedef value<int&, a> value_user; }; template<typename T> int HasStatics<T>::a = /* whatever side-effect you want */ 0; It's also possible without introducing any member:...
6,421,033
6,428,924
How do I handle client disconnect (epoll)
I am working on a network programming using epoll. I was wondering how I can handle client disconnect. I read api document and epoll_wait had a argument for timeout. However, I was confused if the time out for the epoll_wait function or for the client that are being connected. Thanks in advance..
timeout specified is for epoll_wait. To handle client disconnect, Handle EPOLLHUP raised by epoll and also check if the recv function on socket returns zero that means socket is disconnected.
6,421,083
6,421,161
Reference pointing to a Null-object
I saw this discussion - Checking for a null object in C++ and I was surprised that no one talked about when reference can point to a null object. In our code, we use null objects routinely. There are functions as follows which return nullObj. const Obj& nullObj() { static obj* nullPtr = NULL; return sta...
I was surprised that no one talked about when reference can point to a null object That's because it can't, in a correct program. Your function that dereferences a nullpointer has Undefined Behavior. The compiler is allowed to emit code that, for example, causes a crash at that point. However, one possible effect of ...
6,421,130
6,423,865
Decent way to disallow virtual functions due to placement new usage
What would be a decent approach to check at compile/run-time that a particular struct/class does not have any virtual functions. This check is required in order to ensure the proper byte alignment when doing placement new. Having so much as a single virtual function will shift the entire data by a vtable pointer size, ...
You are almost certainly doing something wrong. However, given that you have decided to do something wrong, you don't want to know if your tpe has no virtual functions. You want to know if it is okay to treat your type as an array of bytes. In C++03, is your type POD? As luck would have it, there's a trait for that...
6,421,287
6,421,557
(Windows) When to delete object and device context?
Suppose I create a function that process a bitmap in memory dc and return it HBITMAP paint (HWND hwnd) { HDC windc = ::GetWindowDC(hwnd); HDC memdc = ::CreateCompatibleDC(windc); HBITMAP bitmap = ::CreateCompatibleBitmap(windc,100,100); //Don't bother with the height and width ::SelectObject(memdc,(HGDIOBJ)bitmap); /...
DeleteDC(windc); Never. You have to call ReleaseDC(windc); instead. After ::CreateCompatibleDC(windc); you don't need windc and don't care what happens with it. HDC returned by CreateCompatibleDC just derives some of the parameters (device dependent pixel representation, etc) but does not refer to windc in any way. In...
6,421,433
6,703,455
Address of labels (MSVC)
We are writing a byte-code for a high-level compiled language, and after a bit of profiling and optimization, it became clear that the current largest performance overhead is the switch statement we're using to jump to the byte-code cases. We investigated pulling out the address of each case label and storing it in the...
The only way of doing this in MSVC is by using inline assembly (which basically buggers you for x64): int _tmain(int argc, _TCHAR* argv[]) { case_1: void* p; __asm{ mov [p],offset case_1 } printf("0x%p\n",p); return 0; } If you plan on doing something like this, then the best way would be to write the ...
6,421,534
6,429,513
epoll exception handle
I am working on a network programming using epoll. I was wondering a situation that server didn't receive all the data client sent. For example if a client sent 100 bytes and somehow server only received 94bytes. How do I handle this case? Thanks in advance..
An epoll signals readiness, it does not give any guarantees about the amount of data. EPOLLIN only gives to you the guarantee that the next read operation on the descriptor will not block and will at least read 1 byte. As one normally sets descriptors to non-blocking for a variety of (partly os-specific) reasons, the u...
6,421,818
6,421,858
C++: Use memset or a struct constructor? What's the fastest?
I'm having trouble figuring out which is better in C++: I use a struct to manage clients in a message queue, the struct looks like this: typedef struct _MsgClient { int handle; int message_class; void *callback; void *private_data; int priority; } MsgClient; All of these being POD entities. Now, I have an ar...
On a conforming implementation, it's perfectly valid to value-initialize an array in the constructor initializer list with an empty member initializer. For your array members, this will have the effect of zero-initializing the members of each array element. The compiler should be able to make this very efficient and th...
6,422,114
6,422,165
Why has the destructor been called only once?
#include <iostream> using namespace std; class Test { public: Test() { printf("construct ..\n"); } ~Test() { printf("destruct...\n"); } }; Test Get() { Test t = Test(); return t; } int main(int argc, char *argv[]) { Test t = Get(); return 0; } th...
I suppose the reason is return value optimization in 'Get'. Have a look at http://en.wikipedia.org/wiki/Return_value_optimization Actually your code is not the standard example, but maybe your compiler applies it here as well.
6,422,371
6,422,419
Can't initialize vector C++
SockeClient.h file #define SIZE_OF_BUFFER 4096 class SocketClient { public: SocketClient(int cfd); virtual ~SocketClient(); int recv(); int getFd(); protected: int m_fd; char *m_buffer; vector<char> m_vbuffer; }; I was trying to do vector<char> m_vbuffer(S...
Use member-initialization-list, in the constructor's definition as: class SocketClient { public: SocketClient(int cfd) : m_vbuffer(SIZE_OF_BUFFER) { //^^^^^^^^^^^^^^^^^^^^^^^^^^^ member-initialization-list //other code... } protected: int m_fd; char ...
6,422,405
6,422,475
Object instantiation within destructor of same class and garbage collection
Recently, while taking an introductory unit focused on Object Oriented programming, I was introduced to the Garbage Collector in C#, and that it's role is to "clean up" objects that are no longer being referenced. Then I was introduced to destructors, and how they're called just before the object is deleted. Naturally,...
There's no real mystery here I think. It won't 'recurse' as such - you're just chucking a new object on the managed heap which is immediately dereferenced; thus making it a candidate for garbage collection. Eventually the garbage collector will come round again, triggering the operation again etc. That's not recursion ...
6,422,632
6,422,690
Finding anagrams in a word list
I have a word list and a file containing a number of anagrams. These anagrams are words found in the word list. I need to develop an algorithm to find the matching words and produce them in an output file. The code I have developed so far has only worked for the first two words. In addition, I can't get the code to pla...
Step 1: Build an index with a key of the sorted characters in each word in the wordlist and with the value being the the word. act - cat act - act dgo - dog ... aeeilnppp - pineapple .... etc... Step 2: For each anagram you want to find, sort the characters in your anagram word, and then match against the...
6,422,691
6,423,051
How to set the O_CLOEXEC when using std::ofstream
What is the c++ (std::ofstream) equivalent of: int fd = open(fn,O_WRONLY|O_NDELAY|O_APPEND|O_CREAT|O_CLOEXEC,0600); The application I would like to use this for will only run on newer versions of linux, therefor portability is not an issue.
There is (likely) no portable way to do this. There are at least two options. First option, obtain fd / attach fd Obtain the file descriptor of the ofstream Attach a file descriptor to the ofstream There are lots of examples of "attaching a file descriptor", "getting file descriptor from fstream" etc. If you can find...
6,422,757
6,422,851
C++ Multiple defintions error
I don't wish to create a wall of code so if you need any code just ask and i will post. I am getting multiple definition errors and i have no idea why. i believe the error is occurring because i am attempting to declare a variable in one header file(as well as create an object for it in the same header) and then use it...
Don't declare it in a header file (although technically, I mean don't define it there). In your header file you should have: extern int variableIWantOneCopyOfOnly; and then, in a single C source file that you will link in, put: int variableIWantOneCopyOfOnly; The former will let all your source files know about the e...
6,422,803
6,422,966
std::map question on C++
I've a incertitude about std::map on c++: I did a Object C_Configuration that loads a linked library (.so) C_ConfigurationLibrary. The C_Configuration class has a std::map and The C_ConfigurationLibrary has a method that initializes the std::map. If I access to the std::map from C_Configuration with a "for" loop: std::...
You're using const char*s as keys, but pointers are compared on their memory addresses and not the text to which they point. Consequently, when you have a string literal in the shared library, and the same text in a string literal in the main app object, they can have different addresses and will not compare equal as ...
6,422,993
6,423,230
Returning an array from a function
Here is my code double hour_payload_add(int entries , double array[]) { int index=0 ,k=0; int totalpayload=0; double returnarray[entries/120]; while(k< entries) { totalpayload = totalpayload + array[k]; if(k%120==0) { returnarray[index] = totalp...
Pass the array by reference to the function and don't return anything. Small example: void hour_payload_add(int entries , double array[], double (&returnArray)[SIZE]) { // returnArray will be updated as it's external to function. } or void hour_payload_add(int entries , double array[], double *returnArray) // <-- po...
6,423,078
6,423,293
Use C++ with Android ndk/jni
All the ndk samples only make use of basic C functions declared as extern in the header and defined in the cpp file. Then after including the header file in the C file containing the jni callback, everything works fine. Is it possible to use C++ classes with the android ndk? My application is not going to be a native a...
You can use C++ with NDK, but files with C++ code must have .cpp extension. From ANDROID-MK.html: Note that the default extension for C++ source files is '.cpp'. It is however possible to specify a different one by defining the variable LOCAL_CPP_EXTENSION. Don't forget the initial dot (i.e. '.cxx' will work, bu...
6,423,132
7,740,239
Selectively disabling checked iterators
I am writing a fairly complex application that makes heavy use of STL containers. The application has a single, relatively simple, performance sensitive section that iterates over multiple std::maps and is executed thousands of times. Testing has shown than compiling with checked iterators disabled (_SECURE_SCL set to ...
This works for me: vector<BYTE> v; vector<BYTE>::iterator i; vector<BYTE>::iterator::_Unchecked_type ui; i = v.end(); ui = i._Unchecked(); ui++;
6,423,210
6,423,346
Is std::map table initialization optimized?
Considering the example at the end of the question, is the map object going to be created every time the function GetName() is called? Or is the creation going to be optimized away and created as some lookup table? #include <iostream> #include <sstream> #include <map> #include <string> #include <boost/assign/list_of.hp...
Semantically and conceptually and with respect to The Holy Standard, it will be created every time. The rest is up to your compiler and how you support her: Possibly the compiler can inline the call and then move deduced invariants outside to a single point of initialization. Possibly the compiler dislikes that your ...
6,423,340
6,423,451
Undefined Reference to a function
I'm using Linux and I have the following files: main.c, main.h fileA.c, fileA.h fileB.cpp, fileB.h The function F1() is declared in fileB.h and defined in fileB.cpp. I need to use the function in fileA.c, and so I declared the function as extern void F1(); in fileA.c. However, during compilation, I got the error fi...
If you're really compiling fileA.c as C, not C++, then you need to make sure that the function has the proper, C-compatible linkage. You can do this with a special case of the extern keyword. Both at declaration and definition: extern "C" void F1(); extern "C" void F1() {} Otherwise the C linker will be looking for a ...
6,423,399
6,423,448
Recommended way of returning pointer from C++ function?
I have a pointer that is passed to a series of functions, where one function returns an address and assigns that address to the pointer. After seeking some help on Stackoverflow, the collect_file_path method has a parameter of type QStringList**. Although I understand what is going on I have not come across this nota...
You can pass by pointer reference also, which is more C++ style: void ThreadWorker::collect_file_paths(QStringList*& file_list) <-- see *& { } You don't have to pass the address of file_list now: collect_file_paths(file_list); // simply pass it But instead of that, I would still recommend following approach (which i...
6,423,549
6,423,915
Read from a file when a new line 's been written to it by another process
What is the fastest method in C++, to read a new line from a file which is written by another process. Or how my program can be notified that there is a new line in file so read it? (in linux)
The fastest method is to use pipes or events (for Windows apps). If you still want use files, first of all that you really need, making sure, that a file has been really modified (use seek and compare it with prew value). Than go to the 'last val of seek' and read it. And it will be better use mutex (if you read data f...
6,423,729
6,423,739
Get current cursor position
I want to get the current mouse position of the window, and assign it to 2 variables x and y (co-ordinates relative to the window, not to the screen as a whole). I'm using Win32 and C++. And a quick bonus question: how would you go about hiding the cursor/unhiding it?
You get the cursor position by calling GetCursorPos. POINT p; if (GetCursorPos(&p)) { //cursor position now in p.x and p.y } This returns the cursor position relative to screen coordinates. Call ScreenToClient to map to window coordinates. if (ScreenToClient(hwnd, &p)) { //p.x and p.y are now relative to hwnd...
6,423,872
6,427,107
Program output appears only sometimes in multi-threaded program
I'm using boost threads to parallelize the calculations in my program. A controller object manages the calculation jobs and the results. I create a bunch of worker threads which get their jobs from the controller object while the main thread displays the results. The results need to be shown in the correct order. To ac...
In the case where you don't see any output it could be throwing NoResultsLeft because nothing is in the queue on the first pass. The other possibility is that it is failing to add things to the queue in the first place or throwing NoJobsLeft. Adding std::cout statements into your catch blocks might help identify what...
6,423,900
6,424,830
How to understand corrupted infix pattern for freed block
We have PageHeap enabled and are running adplus on our system and recently have had a couple of "corrupted infix pattern for freed block" failures. Can someone shed some light on what this means, what it might look like in the code and suggest steps on how best to proceed with resolving the issue? =====================...
It is described pretty well in this MSDN Library article. Classic heap corruption bug, your code is writing to a heap block after it was freed. If the address repeats well then you can set a data breakpoint with the debugger to trap the write. If it doesn't then you'll need the tool between your ears to hunt the bug...
6,424,050
6,424,428
ofstream leaking memory
I have a C++ class that writes its data out to a binary std::ofstream. The class is storing the data as a boost:shared_array but I have eliminated this as the problem. The problem is with the call to write() on the ofstream. The issue is that it seems to leak memory. The system it is running on is CentOS 64bit, GCC ...
It looks like you don't have a problem, and that is just the system cache working as intended. Linux is very agressive on caching, so it will use almost all your free memory for this, but whenever an application needs more memory, it will release some of that memory and grant it to the application.
6,424,212
6,424,223
How to create application for mac?
I created an application in visual studio 2008 using c++ and poco library. Since output of visual studio is .exe i have no idea how to create a mac application(.app file) with this. Can any one help me with this.
Google can help: How to get started with Mac Programming Writing Mac OS X Applications with Visual Studio Express - Uses Mono
6,424,698
6,424,745
Initialization of vector of vector is very slow
I have a vector of vectors and I am trying to initialize it as follows: vector<vector<float> > matrix(numberOfRows, vector<float> (numberOfCols)); But this line lasts about 0.89 where the numberOfRows and numberOfCols are: const uint32_t numRows = 10000; const uint32_t numCols = 20000; Whereas initializing dynamics a...
The difference is that the vector is initialized to zero, while the dynamic array is not. With 200 million values, this is noticable. You have the option of delaying initialization of the vector rows until you have real values to assign them, by not expanding the columns in the initialization.
6,424,874
6,424,968
Use of fork for executing multiple commands
I have a list of class pointers. I have a function that calls a method from these pointers. Each pointer in the list is a derived class from a main class. What i am currently doing is iterate through the list and call the method of 1st pointer in the list, wait for it to finish, then go to the 2nd class object pointer ...
Yes, you can use fork() to do some work in a child thread. However, once the child process is done doing it's work, it returns and you are not sharing data between them. I am not clear on your implementation but if the intent is to spawn off some processes to do some extra work, then that seems OK, but you probably wan...
6,424,911
6,424,926
Link error with really simple functions C++ on .h file
I've made two functions to 'cast' a 32/64 bit pointer into a double. The code worked when used alone (Just the .h and a .cpp including it) but when using the .h somewhere else (copied into the project directory and then included) ith throws 'already defined' error for all the functions on the .h file when linking. the ...
Mark your functions inline inline double ptr2double(void* pv){ ptr_u ptr; ptr.p = pv; return (ptr.d); }; inline void* double2ptr(double dv){ ptr_u ptr; ptr.d = dv; return(ptr.p); }; You see, when you included the same function in two separate source files (translation units), you get multiple ...
6,424,996
6,427,025
Editing OpenCL in netbeans
I recently read a question on IDE's here on StackOverflow, having always been an emacs user I decided to try out one of these ide's, namely netbeans for editing C++. It was so nice that I got a little carried away and wanted to edit OpenCL files in it to. And now for my question. I have netbeans set up to process the o...
It is not the answer you want, but for temporary editing, just put lines like #define __kernel #define __global #define __local #define __private at the beginning of the cl file. This is working in Eclipse. I think it will work in Netbeans, too. Drawback: You need pay attention to remove the #define statements, other...
6,425,178
6,425,524
boost tuple: increasing maximum number of elements
The boost tuple documentation says: The current version supports tuples with 0-10 elements. If necessary, the upper limit can be increased up to, say, a few dozen elements. However, I could not find where it says how to do this. I would like the tuple to have BOOST_MPL_LIMIT_VECTOR_SIZE elements (20 by default)...
The tuple class is declared in the following way: // - tuple forward declaration ----------------------------------------------- template < class T0 = null_type, class T1 = null_type, class T2 = null_type, class T3 = null_type, class T4 = null_type, class T5 = null_type, class T6 = null_type, class T7 = null_type...
6,425,266
6,584,418
Boost graph recursive template problem
Hi I have a boost graph like: struct Vertex; struct Edge; typedef boost::adjacency_list<boost::vecS, boost::vecS, boost::bidirectionalS, Vertex, Edge> Graph_t; struct Vertex { }; struct Edge { typedef std::vector<Graph_t::vertex_descriptor> intermediate_vertices_t; intermediate_vertices_t intermediate_ver...
I ended up using a small wrapper class like: typedef Graph_t::vertex_descriptor vd_t; struct iVertexWrap{ iVertexWrap(vd_t v) : v(v) {} vd_t v; }; forward declaring it be...
6,425,589
6,425,712
atoi() with other languages
I am working on a internationalization project. Do other languages, such as Arabic or Chinese, use different representations for digits besides 0-9? If so, are there versions of atoi() that will account for these other representations? I should add that I am mainly concerned with parsing input from the user. If the...
I may use std::wistringstream and locale to generate this integer. #include <sstream> #include <locale> using namespace std; int main() { locale mylocale("en-EN"); // Construct locale object with the user's default preferences wistringstream wss(L"1"); // your number string wss.imbue( mylocale ); // Imbue th...
6,425,624
6,425,984
Passing a const reference down a chain of constructors
I get a runtime error with the following code, which is a reproducible reduction of my actual code. I am sure I am not instantiating something properly, but I cannot figure out what it is. #include <iostream> using namespace std; class A { int n; public: A(); A(const int k); int getn() const { return...
The problem is in this line: C::C(const A& anA) : myA(anA), myB(myA) {} myB is a reference. But to what? The answer is to a temporary. myB(myA) will construct a temp object that is assigned to your reference. Unfortunately this object will be destroyed after the Ctor exits. Change your code to the following: class C ...
6,426,146
6,426,228
Moving from void* and casting to an ABC with PVFs (will there be a speed hit?)
I've just inherited (ahem) a QNX realtime project which uses a void*/downcasting/case statement mechanism to handle messaging. I'd prefer to switch to an abstract base class with pure virtual functions instead but I'm wondering if the original solution was done like that for speed reasons? it looks a lot like it was wr...
I doubt that performance will be a concern. If there are sufficient disparate values in the switch/case your compiler may not even optimize it into a jump table, setting up the possibility that the virtual dispatch could be faster than the switch. If a pure virtual interface makes sense design-wise I would definitely g...
6,426,962
6,428,200
Finding the element count of an stl deque in windbg
How can I find the element count of an STL deque container in windbg? It appears that the !stl extension doesn't support deques. I've tried looking into the internals of the data structure, but haven't found an obvious member variable for element count. I have a memory dump of a non-reproducible issue, so logging isn't...
In recent Visual C++ Standard C++ Library implementations--at least Visual C++ 2008 and Visual C++ 2010--std::deque has a _Mysize data member that holds the number of elements in the container.
6,427,578
6,427,622
WPF with C++, is it possible?
I have my main program in C++, but now I need to build a beautiful application and I know that WPF is easy and makes for beautiful apps. Can WPF work with C++ or C# and C++? (If yes, how?) Is WPF the best thing for me?
You can use WPF in a managed C++ project, but you're better off keeping your C++ in a separate assembly and referencing it from a C# or VB WPF project.
6,427,698
6,427,761
Write to the middle of an existing binary file c++
I'm trying to open a binary file for writing without erasing the content. But I do not want to write to eof. I want to write to a specific position in file. Here is a litte example: ofstream out("test.txt", ios::binary | ios::app); for(int i = 0; i < 100; i++) out.put('_'); out.write("Hallo", 5); out.close(); ofs...
try the second overload of seekp, which allows you to provide an offset and a direction, this could be begining of file in your case (i.e. ios_base::beg). This of course assumes you know what you are doing and all you want to do is overwrite an existing number of characters. EDIT: here is fully working example: #includ...
6,427,810
6,427,879
What data structure discards the oldest item when a new one is added?
I've been trying to remember this and it's driving me crazy. Basically, it's like a small array, of let's say size five, and as you add items it starts to fill up. When it's full, and you add a new item, the oldest one (first added) is removed. You can access the values by something like variable[0], variable[1] etc, w...
Boost Circular Buffer http://www.boost.org/doc/libs/1_46_1/libs/circular_buffer/doc/circular_buffer.html From the Boost docs: // Create a circular buffer with a capacity for 3 integers. boost::circular_buffer<int> cb(3); // Insert some elements into the buffer. cb.push_back(1); cb.push_back(2); cb.push_bac...
6,427,977
6,428,143
Intel TBB will work on AMD processors?
Possible Duplicate: AMD multi-core programming Is Intel TBB processor dependent? Will it work on amd or on ARM (under meeGo for example?)
The answer is yes, for AMD anyhow. For ARM things are more complex, judging by feedback on the Intel forums. I don't see anybody has gotten this working? For example see http://software.intel.com/en-us/forums/showthread.php?t=74346 The commercial version 3.0 has this in its release notes regarding recommended hardwar...
6,428,382
6,432,313
mpl::transform on boost::fusion::tuple
The following code does not compile on g++ (GCC) 4.6.0 20110603 (prerelease) with -std=c++0x and Boost 1.46.1. Am I missing an include or is this actually a bug? If the latter, how to work around it? #include <boost/mpl/vector.hpp> #include <boost/mpl/transform.hpp> #include <boost/mpl/clear.hpp> #include <boost/fusio...
When you do not provide an inserter, transform has to generate one for you (the result has to be accumulated somewhere), which essentially amounts to doing something like back_inserter< clear<OriginalSequence>::type >. The transform docs are somewhat misleading here since they do not document this extra requirement for...
6,428,729
6,429,678
Pushing MPEG4 video samples to decoder - How to use CBaseOutputPin::DeliverNewSegment()?
I wrote my own RTSP Push Source DirectShow filter (CBaseFilter), that works for H264 like a charm! But, when I tried to support MPEG4 (MP4V-ES stream), I stumbled upon a problem... My stream gets decoded (with ffdshow Video Decoder filter, or DivX Video Decoder) and rendered perfectly for exactly 10 seconds. Picture is...
I'm not convinced that NewSegment causes the issues you are seeing. NewSegment is used for those cases where the data you push in a single packet crosses the start time or the stop time, and it allows the decoder to only deliver up to the stop time. In this case you could call NewSegment (0, MAX_LONGLONG, 1) once at st...
6,428,737
6,428,814
C++ Cleared Memory still accessible
I have a question about why I can access certain pieces of memory, and I think it has to do with the way I understand (or don't understand) how the compiler saves things in memory. This is the sample code I'm working with: The header file: #include <iostream> using namespace std; class A { public: int value; A (int n...
The answer to the first question is easy: the instruction is written at compile time. The compiler obviously won't know whether that value has been deleted or not, so it just blindly copies the value of pC over ppA. The answer to your second question is: it might not work. You have entered scary undefined-behavior-land...
6,428,767
6,429,416
Proper choice of file stream objects
Application uses RapidXML to edit XML file. Editing is not automated and takes place occasionally: XML content is displayed in GUI and user performs some actions which change XML. Each change must be saved to disk immediately. Loading RapidXML document object requires copying the content of the file into a string. Each...
Editing files in place when the amount of data to re-write is different from the original data is a real pain. If your file format requires data to be sequential and has no syntax for holes, then you don't really have a choice but to re-write the file (at least from the start of the modified position). Also, there are...
6,428,784
6,428,953
is it possible to build android for any device that passes the minimum requirements?
Suppose i have a device that passes the minimum requirements for android OS , now can i program the bootloader and all and run android OS in it? the device is : LG gt350i i wouldnt want to run android 3.0 , perhaps 1.6 or 2.1.
Since the code is open source, you can port it to anything you want, if you have the development tools for your device and can write drivers for it's peripherals. Unfortunately companies usually don't provide that tools for users (you can develop an app for their OS, but you can't change the OS itself), nor hardware sp...