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,317,420
3,318,596
How to know what optimizations are done automatically by my compiler
I was going through this link Will it optimize and wondered how can we know what optimizations are done by a particular compiler. Like does VC8.0 convert if-else statements to switch-case? Is such information available on msdn?
As everyone seems to be bent on telling the OP that he shouldn't worry about it, there is some useful although not as specific as the OP requested) information about compiler optimization (options). You'll have to figure out what flags you're using, especially for MSVC and Intel (GCC release build should default to -O2...
3,317,536
3,329,714
Visual Studio Warning C4996
I'm getting the following warning warning C4996: 'std::_Uninitialized_copy0': Function call with parameters that may be unsafe - this call relies on the caller to check that the passed values are correct. To disable this warning, use -D_SCL_SECURE_NO_WARNINGS. See documentation on how to use Visual C++ 'Checked Iterat...
First, I would like to say that I am quite fond of compiler warnings. I invoke gcc with -Wall -Wextra. However, the MSVC warning C4996 mostly fires on completely valid code. The changes proposed in the warning text often seriously compromise the code portability, while they never substantially improve the code quality....
3,317,543
3,317,579
compile error using qFromBigEndian
I'm trying to use qFromBigEndian to read a 32-bit int from a byte stream received over a udp socket. void processData(uchar *data) { qint32 addr; addr = qFromBigEndian(data); } Compiling this gives the following error: error: invalid conversion from 'uchar*' to 'qint32' The Qt documentation says: T qFromBigEndi...
Note that qFromBigEndian(const uchar *src) is a function template. You're missing the template parameter, use addr = qFromBigEndian<qint32>(data); instead, and things will work as expected.
3,317,545
3,317,615
writing a C/C++ daemon (Linux)
I want to write a generic (C/C++) library that I will use to develop daemons in the Linux environment. Rather than reinventing the wheel, I thought I'd come in here to find out if there are any well known libraries in use. The library could be either C or C++ - although I would prefer C++ (maybe something that was part...
An alternative solution is to use a process monitor such as supervisord, which manages multiple services, restarts them when they crash, provides a minimalistic web page to view and control the status of processes, can manage groups of services, supports a general-purpose status-change event forwarding mechanism and ot...
3,317,607
3,317,657
Bind function trouble
I'm using boost (signals + bind) and c++ for passing function reference. Here is the code: #define CONNECT(FunctionPointer) \ connect(bind(FunctionPointer, this, _1)); I use this like this: class SomeClass { void test1() {} void test2(int someArg) {} SomeClass() { CONNECT(&SomeClass::test1); C...
_1 is a placeholder argument that means "substitute with the first input argument". The method test1 does not have arguments. Create two different macros: #define CONNECT1(FunctionPointer) connect(bind(FunctionPointer, this, _1)); #define CONNECT0(FunctionPointer) connect(bind(FunctionPointer, this)); But remember mac...
3,317,646
3,322,670
Who's using MFC's VERIFY Macro?
To think ... there I have been happily programming in an MFC riddled environment for years, using ASSERT() whenever it seemed OK and just today I (was) stumbled upon the VERIFY Macro: http://msdn.microsoft.com/en-us/library/fcatwy09%28v=VS.71%29.aspx It's basically the same as ASSERT() except the expression will not be...
When I used to do MFC programming, I used it all the time. Basically everything which returns something that I'm normally too lazy to check the return from, but which Lint then whines at you about, I would wrap in a VERIFY. (Calls like ::CloseHandle, for example) There cannot be any adverse side effects to using it i...
3,317,654
3,317,682
Solving aliasing problem in c++
I was trying following code in which I defined copy c'tor explicitly to solve aliasing problem. But code is giving runtime error. #include<iostream> #include<cstring> using namespace std; class word { public: word(const char *s) // No default c'tor { str=const_cast<char*>(s); cnt=strlen(s); ...
Problem is in this constructor: word(const char *s) // No default c'tor { str=const_cast<char*>(s); cnt=strlen(s); } Here you are not allocating any memory to copy the string into str variable. But in destructor of the class you are doing delete[] str;, since the memory for the str is not allocat...
3,317,740
3,318,452
checking data availability before calling std::getline
I would like to read some data from a stream I have using std::getline. Below a sample using the std::cin. std::string line; std::getline( std::cin, line ); This is a blocking function i.e. if there is no data or line to read it blocks execution. Do you know if exists a function for checking data availability before c...
The iostream library doesn't support the concept of non-blocking I/O. I don't think there's anything in the C++ standard that does. Any good solution would likely be platform-specific. If you can use the POSIX libraries, you might look into select. It's usually used for networking stuff, but it'll work just fine if...
3,317,978
3,318,236
struct as key of unordered_map
I have a problem putting data into an unordered_map using a struct as key: typedef struct osdpi_flow_identificator { u32 lower_ip; u32 upper_ip; u16 lower_port; u16 upper_port; u8 protocol; } osdpi_flow_identificator_t; // custom hash function for osdpi_flow_identificator struct osdpi_flow_hash { std::size_t op...
Ok, I finally found it :-) In fact you need to define an EqualOperator for your hash, since you are using pointers. It should be something like : struct Eq { bool operator() ( osdpi_flow_identificator * id1, osdpi_flow_identificator * id2) const { id1->lower_ip == id2->lower_ip && // compare all fields. } }; ...
3,318,204
3,318,426
glBufferData fails silently with overly large sizes
i just noticed, that glBufferData fails silently when i try to call it with size: 1085859108 and data: NULL. Following calls to glBufferSubData fail with a OUT_OF_MEMORY 'Exception'. This is on Windows XP 32bit, NVIDIA Gforce 9500 GT (1024MB) and 195.62 Drivers. Is there any way to determinate if a buffer was created s...
I doubt that it's really silent. I'd guess that glGetError would return GL_OUT_OF_MEMORY after that attempt.
3,318,293
3,318,445
Returning values from pthread asynchronously at regular intervals
The main() function creates a thread that is supposed to live until the user wishes to exit the program. The thread needs to return values to the main functions at periodic intervals. I tried doing something like this, but hasn't worked well - std::queue<std::string> q; void start_thread(int num) { std::string str; ...
It is not safe to read and write from STL containers concurrently. You need a lock to synchronize access (see pthread_mutex_t). Your thread pushes a single value into the queue. You seem to be expecting periodic values, so you'll want to modify start_thread to include a loop that calls queue.push. The return 0; in t...
3,318,322
3,318,342
Do inline functions have addresses?
In section 7.1.1 of the book "The C++ Programming Language" the author states: "inline function still has a unique address and so do the static variables of an inline function" I am confused. If I have an inline function then it can't have address. Does this happen in C also?
The inline attribute is just a hint to the compiler that it should try to inline your function. It's still possible to take the address of the function, and in that case the compiler will also need to emit a non-inline version. For example: #include <stdio.h> inline void f() { printf("hello\n"); } int main() { ...
3,318,451
3,318,550
full code from java in c++
here is full code from algorithm and data structure in java written in c++ #include <iostream> using namespace std; class link { public: int idata; double ddata; link *next; link ( int id,double dd){ idata=id; ddata=dd; } public : void display(){ cout<<idata<<"=>"; ...
void displaylist(){ cout<<"List (first-->last"; link *current=first; while (current!=NULL) { //display the current node current->display(); //then move to the next one current = current->next; } }
3,318,564
7,168,613
Win32 API stack walk with MinGW/MSYS?
i've to develop a stack trace walk to our win32 API plattform support to catch any exception with a behaviour of a JAVA stacktrace. Actually we got a full functional implementation for Linux plattforms. First i've tried to implement a stackwalk using the win32 CaptureStackBackTrace API mechanism. But this method is not...
Check Mr. Edd's stack trace library at the following link. It will produce a nice stack frame listing and has specific code to support MinGW. http://www.mr-edd.co.uk/code/stack_trace His library uses dbghelp.dll, however, so you may get into some problems trying to compile it. As far as I know, MinGW doesn't include a...
3,318,692
3,318,822
how does GlPolygonStipple's mask parameter work?
I can't find a tutorial showing me how this works and I don't get it. I'd like to use it to draw dashed lines since I have an algorithm that generates triangles and would like it to skip some after a certain distance has been reach (a bit like glLineStipple) Thanks
It's difficult to understand exactly what you want to do from your question, but the way poly stippling in gl works is basically this: you can enable polygon stippling and supply a 32x32 pattern that is used to control the stippling. It is as if this pattern were tiled over the entire window you are drawing to. Polygon...
3,318,714
3,318,793
Check if ostream object is cout or ofstream, c++
Is there a way in C++ to check if an ostream object is cout or a ofstream object? Something like: ostream& output(ostream& out) { if (out == cout) return out; else { out << "something different because its not going to the console" << endl; return out; } } The reason I want to ...
It's possible by checking the stream's 'identity': if ( &out == &cout ) .... However, I'm in doubt on the usefullness of this test. If your function can handle any output stream, why bother about what stream it is using?
3,318,764
3,320,011
Looking for an easy to use embedded key-value store for C++
I need to write a C++ application that reads and writes large amounts of data (more than the available RAM) but always in a sequential way. In order to keep the data in a future proof and easy to document way I use Protocol Buffer. Protocol buffer however does not handle large amounts of data. My previous solution cons...
I think I have found the answer to my problem. I did not notice that Berkeley DB provides two APIs for C++: a vanilla C like API an STL API This STL API provides STL compatible vectors and map abstractions that give direct access to the database. Thus doing value = data_container[key] becomes possible. This seems to ...
3,318,898
3,318,952
Why is c++ that powerful concerning game development?
I was just wondering why c++ ist that powerful and performant for developing games. I wrote a lot of games in c# and delphi, always using the timer component to make objects "move". Another option for the movement were loops, but they are definitely not performant. So what technique does c++ use that users can develop ...
C++ give you finer grain of control over the actual hardware and bit pushing. For common business needs, a third generation language such as Java or C# is quicker to program and takes worries like pointers and garbage collection off the hands of the developer. This is at a cost of lack of ability to optimize and fine t...
3,318,960
3,319,009
Can derived class use friend function of the basis class?
If I have some class Basis, and derived from it Derived, inside basis I have friend function friend int operator!=(const Basis&, const Basis&) Inside derived class I don't have such function So my question is if I have inside my main If( derived1 != derived2 ) ... why does it work? i don't have any constructor for c...
The compiler is comparing them as objects of class Basis. Since you can always implicitly convert from a derived class to a base class, the compiler is able to pass them to the Basis overload of operator !=. Of course, this comparison can only use fields declared in Basis, so if you want the comparison to be more spe...
3,318,979
7,180,310
How to serialize the GMP mpf type?
It seems that GMP provides only string serialization of the mpf (floating point) type: mpf_get_str(), mpf_class::get_str() The mpz (integer) type has an additional interface for raw bytes: mpz_out_raw() http://gmplib.org/manual/Function-Index.html Am I missing something? Does anyone know of another library that can se...
This was a long time ago, but I wound up doing something like this: int mpf_out_raw (FILE *f, mpf_t X) { int expt; mpz_t Z; size_t nz; expt = X->_mp_exp; fwrite(&expt, sizeof(int), 1, f); nz = X->_mp_size; Z->_mp_alloc = nz; Z->_mp_size = nz; Z->_mp_d = X->_mp_d; return (mpz_out_raw(f, Z)...
3,318,981
3,319,068
best data structure for byIndex and byName retrieval
suppose you need to implement container of a T items, which its value could be retrieved by numeric index (which is random access) and by name (as string). which one is better in term of performance of common operation such as retrieval, adding, and removing the items: (in this case retrieval by index need to be imple...
Or you could go with the most awesome Boost::MultiIndex containers.
3,319,051
3,319,512
C++ link error on Visual Studio 2010 x64
I'm upgrading a C++ code base from VS2005 to VS2010 and I'm rebuilding some third party C++ dependencies. I have no problem building these 32-bit but keep running into problems linking 64-bit (x64). I'm getting unresolved externals for a number of standard library functions. For example: error LNK2001: unresolved exter...
You might try enabling /showIncludes to see what header files are being brought in. Because in general I would expect those functions to be inlined into your resulting binary.
3,319,094
3,319,283
How to avoid writing multiple versions of the same loop
Inside a large loop, I currently have a statement similar to if (ptr == NULL || ptr->calculate() > 5) {do something} where ptr is an object pointer set before the loop and never changed. I would like to avoid comparing ptr to NULL in every iteration of the loop. (The current final program does that, right?) A simp...
In C++, although completely overkill you can put the loop in a function and use a template. This will generate twice the body of the function, but eliminate the extra check which will be optimized out. While I certainly don't recommend it, here is the code: template<bool ptr_is_null> void loop() { for(int i = x; i ...
3,319,503
3,319,771
"templating" a namespace
I'd like to build something like this: File 1: template<typename Vector> namespace myNamespace { class myClass1{ myClass1(Vector v) {...} } } File 2: template<typename Vector> namespace myNamespace { class myClass2{ myClass2(Vector v) {...} } } Of course this is not possible because you cannot template namespaces...
Following up on your comment: Instead of writing using namespace myNamespace<int>; Just use templated classes and write this instead (or whatever variation): typedef myNamespace::myClass1<int> myClass1Int; typedef myNamespace::myClass2<int> myClass2Int; I tend to think it's better to be explicit about what types are b...
3,319,636
3,320,023
std::vector<std::vector<type>> for sparse matrix structure or something else?
I am implementing a sparse matrix class in compressed row format. This means i have a fixed number of rows and each row consists of a number of elements (this number can be different for different rows but will not change after the matrix has been initialised. Is it suitable to implement this via vectors of vectors or ...
The general rule with sparse matrices is that you pick a structure that best fits the location of non-zeros in matrix; so maybe you could write a bit more about the matrix structure, and also what (sort of) algorithms will be invoked on it. About the memory -- if this matrix is not too big, it is better to alloc it as ...
3,319,718
3,319,828
RegQueryValueExW only brings back one value from registry
I am querying the registry on Windows CE. I want to pull back the DhcpDNS value from the TcpIp area of the registry, which works. What happens though, however, is if there is two values - displayed as "x.x.x.x" "x.x.x.x" in my CE registry editor - then it only brings back one of them. I am sure this is a silly mistak...
The value is a multi_sz, which is in the format: {data}\0{data}\0\0 I don't know what the Unicode::UnicodeToAnsi does, but it's likely just looking for that first null terminator and stopping there. You have to parse past single nulls until you hit the double-null. EDIT You have to update your code - very likely your ...
3,319,837
3,320,151
Ambiguous operator <<
#include "stdafx.h" #include "Record.h" template<class T>//If I make instead of template regular fnc this compiles //otherwise I'm getting an error (listed on the very bottom) saying // that operator << is ambiguous, WHY? ostream& operator<<(ostream& out, const T& obj) { out << "Price: " << (obj.getPr...
First, you need to read the error message more carefully. As an alternative, consider breaking the statement up, something like this: out << "Price: "; out << (obj.getPrice()); out << "\tCount: "; out << obj.getCount(); out << '\n'; When you do, you'll realize that what's really causing the problem is not where you tr...
3,319,892
3,319,952
C++: Why does my DerivedClass's constructor not have access to the BaseClass's protected field?
I have a constructor attempting to initialize a field in a base class. The compiler complains. The field is protected, so derived classes should have access. //The base class: class BaseClass { public: BaseClass(std::string); BaseClass(const BaseClass& orig); virtual ~BaseClass(); const std::string...
You cannot initialize m_data in the derived class constructor but instead pass it as an argument to the base class constructor. That is: DerivedClass::DerivedClass(std::string data) : BaseClass(data) { }
3,320,184
3,320,219
C++ template duck-typing vs pure virtual base class inheritance
Which are the guidelines for choosing between template duck-typing and pure virtual base class inheritance? Examples: // templates class duck { void sing() { std::cout << "quack\n"; } }; template<typename bird> void somefunc(const bird& b) { b.sing(); } // pure virtual base class class bird { virtual void...
With template duck-typing, you are doing static polymorphism. Thus, you cannot do things like std::vector<bird*> birds; birds.push_back(new duck()); However, since you are relying on compile time typing, you are a little more efficient (no virtual call implies no dynamic dispatch (base on the dynamic type)).
3,320,194
3,320,236
Where can I read more about memory structure in C++?
I came across this presentation while browsing SO some time ago, and it relates performance to specific memory allocation decisions. The author has some interesting diagrams that show how various objects are allocated by a C++ program, and goes on to optimise the program by making some changes in the code. His diagrams...
You should have no problem finding any number of sites with information on C++ memory allocation. Here is a small sample from a quick Google search: http://www.cplusplus.com/doc/tutorial/dynamic/ http://oopweb.com/CPP/Documents/CPPHOWTO/Volume/C++Programming-HOWTO-9.html https://users.cs.jmu.edu/bernstdh/web/common/le...
3,320,393
3,320,408
Performance - checking if container is empty before doing operations on it?
Is there a significant difference between doing this... if ( !myVector.empty()) { for ( unsigned int i = 0; i < myVector.size(); ++i ) { // do stuff } } and this for ( unsigned int i = 0; i < myVector.size(); ++i ) { // do stuff } if the vector is empty? What is the cost of this on an empty vector?
Both size and empty are constant time for vectors. So most of the time (non-empty vectors), the first one just adds a small, constant amount of work. The second is clearly cleaner, and probably negligibly more efficient on average.
3,320,622
3,320,652
The use case of 'this' pointer in C++
I understand the meaning of 'this', but I can't see the use case of it. For the following example, I should teach the compiler if the parameter is the same as member variable, and I need this pointer. #include <iostream> using namespace std; class AAA { int x; public: int hello(int x) { this->x = x;} int...
Sometimes you want to return yourself from an operator, such as operator= MyClass& operator=(const MyClass &rhs) { // assign rhs into myself return *this; }
3,320,898
3,320,934
C++ alternative to perror()
I know we can use perror() in C to print errors. I was just wondering if there is a C++ alternative to this, or whether I have to include this (and therefore stdio.h) in my program. I am trying to avoid as many C functions as possible.
You could do something like: std::cerr << strerror(errno) << std::endl; That still ends up calling strerror, so you're really just substituting one C function for another. OTOH, it does let you write via streams, instead of mixing C and C++ output, which is generally a good thing. At least AFAIK, C++ doesn't add anyth...
3,320,973
3,321,071
Passing smart pointer to the function (which acccepts void*) without calling destructor of pointee
I have my own implementation of smart pointer which uses reference counting as ownership mechanism (Note: I have tested it and it has no bugs). Following is my code flow. Create Object and create Smart pointer to the object Call function which has following defination : void Func(void* param) (Note: This function ru...
Smart pointers mean that the referenced object gets deleted as soon as the last smart pointer for it is destructed, so what's happening in your code is as expected. You would need to release the pointer from your smart pointer instance, transferring ownership to Func.
3,321,074
3,321,144
Deleting a nested struct with void pointers as members?
I have the following class: class Stack { struct Link { void* data; Link* next; void initialize(void* dat, Link* nxt); }* head; public: void initialize(); void push(void* dat); void* peek(); void* pop(); void cleanup(); }; The pop method is: void* Stack::pop() { if(head == 0) return 0; vo...
Your terminology is causing ambiguity, but let me explain. Let's say you have: struct foo { void* bar; }; Whenever a foo ends its lifetime, bar simply stops existing too. So if you have: { foo f = { new int; } } You've leaked, as new int is never deleted. Likewise, when you do: { foo* f = new foo; f->...
3,321,134
3,323,458
Why can a Boost.Bind function be called with extra parameters?
#include <iostream> #include <string> #include <boost/bind.hpp> void foo(std::string const& dummy) { std::cout << "Yo: " << dummy << std::endl; } int main() { int* test; std::string bar("platypus"); (boost::bind(&foo, bar))(test, test, test, test, test, test, test, test); } When run, it prints out, ...
I don't know why this is allowed, but I do know it is expected behavior. From here: bind can handle functions with more than two arguments, and its argument substitution mechanism is more general: bind(f, _2, _1)(x, y); // f(y, x) bind(g, _1, 9, _1)(x); // g(x, 9, x) bind(g, _3, _...
3,321,169
3,321,847
How to delete dlldata.c during clean build in Visual Studio?
I will be creating a series of projects set up to build COM objects. I attempting to create a property sheet (.vsprops file) which will set up the builds for each project. One of the things I am doing with the properties file is customizing the location and names of the files created by the MIDL compiler. Here's the...
Not your problem, it is a bug in the build system. The dlldata.c file doesn't get deleted using a regular build either. There aren't enough diagnostics available in the msbuild .log files to see what target fumbles this. I'm guessing it has something to do with the <FilePatternsToDelete> item in the Microsoft.CppCle...
3,321,211
3,336,347
CMake link stage question
I am currently building a rather large application, using cmake to generate cross platform build scripts. During this process of putting together the cmake build scripts, I have discovered the pain of gcc link line ordering. The basic issues is that including static libraries in the wrong order leads to unused library ...
I think this is less of a CMake issue, and more of a GCC behavior. This question/answer should help out a bit: Linker order in GCC You will have to bite the bullet and modify your CMakeLists.txt files to link properly on Linux. Since the Windows developers don't care, you shouldn't disturb them. Best, -dan
3,321,283
3,321,822
C++0x lambda, how can I pass as a parameter?
Please look at the following C++0x lambda related code: typedef uint64_t (*WEIGHT_FUNC)(void* param); typedef std::map<std::string, WEIGHT_FUNC> CallbackTable; CallbackTable table; table["rand_weight"] = [](void* param) -> uint64_t { return (rand() % 100 + 1); }; I got an error (in Visual Studio 2010) that the lamb...
The conversion to function pointer is relatively new: It was introduced with N3043 on February 15, 2010. While e.g. GCC 4.5 implements it, Visual Studio 10 was released on April 12, 2010 and thus just didn't implement it in time. As James pointed out, this will be fixed in future releases. For the moment you have to ...
3,321,505
3,321,863
Finding external calls in a C++ dll
We currently use a hardware driver's DLL for a particular piece of hardware we interface with. However, we also have an old internally developed DLL written with VC++ around 2002 that wraps that DLL for a few core functions. This code has been long lost, and was developed well before I came on the scene. So, it cannot ...
I think that PE.Explorer might help you. Even if it doesn't list it directly, you can still get the dissassembly and check for import tables mapping. Maybe by pairing this tool with another one like Windbg or OllyDbg you might get interesting results. Any tool that can help you WILL have to deal with dissassembly. Wit...
3,321,733
3,322,316
Qt - Problems while serializing "double"
I serialize "double" data type and get an error though QDataStream & operator<< ( double f ) operator is defined. Here is the error message: error: conversion from 'double' to 'const QChar' is ambiguous Did you meat this situation or understand why it can be like this?
It sounds like it can't see the operator for double, so it's trying to implicitly create a QChar from the double to send to the stream, but QChar has multiple constructors that could possibly match. Make sure that your header includes are all correct. Can you show us the code where you're trying to serialize the double...
3,321,819
3,321,918
What is the efficient way of implementing a queue?
What is the efficient way of implementing a queue, inorder to learn how it is implemented? EDIT: I looked into stl::queue code inorder to learn abt how it is implemented, but the template code making it difficult to understand. After all there is better efficient way is used than having a linked list.
Of course for any production code you should rely on a robust library implementation that's already withstood the test of time. That said, for self-teaching it can be fun to write one yourself. I've done it before. The most efficient way I know of is to use a similar approach to what most resizable collections do inte...
3,321,833
3,324,055
Side effects of exit() without exiting?
If my application runs out of memory, I would like to re-run it with changed parameters. I have malloc / new in various parts of the application, the sizes of which are not known in advance. I see two options: Track all memory allocations and write a restarting procedure which deallocates all before re-running with ch...
simplicity rules: just restart your app with different parameters. it is very hard to either track down all allocs/deallocs and clean up the memory (just forget some minor blocks inside bigger chunks [fragmentation] and you still have problems to rerun the class), or to do introduce your own heap-management (very cle...
3,321,913
3,322,414
Merge sorted arrays - Efficient solution
Goal here is to merge multiple arrays which are already sorted into a resultant array. I've written the following solution and wondering if there is a way to improve the solution /* Goal is to merge all sorted arrays */ void mergeAll(const vector< vector<int> >& listOfIntegers, vector<int>& result) { int tota...
You can generalize Merge Sort algorithm and work with multiple pointers. Initially, all of them are pointing to the beginning of each array. You maintain these pointers sorted (by the values they point to) in a priority queue. In each step, you remove the smallest element in the heap in O(log n) (n is the number of arr...
3,321,976
3,322,043
Not able to solve the puzzle regarding this code
int i,n=20; for(i=0;i<n;i--) printf("-"); I have been rattling my brain but have not been able to solve this. Delete any single character or operator from above code and the program should print "-" 20 times Please help!
I don't think you can do it by deleting a character, but I have three solutions that replace (well, one of them adds a character, but only because you have no whitespace in your program. If you had whitespace, it would replace a space). Solution 1 int i,n=20; for(i=0;-i<n;i--) // -i < n printf("-"); Solution 2 in...
3,321,997
3,322,081
C++ Elegant solution to partition problem
I would like to see the most elegant STL like extension to the partition algorithm in the STL: given a vector of ints, partition the vector so that the positive integers appear to the front of the negative integers AND return a map<int, int> where map[i]=j means that integer at index i is now at j. Obviously the first...
Copy your vector of ints into a vector of something like: struct ValIdx { int val; size_t idx; }; Partition with an appropriate functor, then iterate over the result copying the ints back out and building your map.
3,322,032
3,322,239
Parallel Processes In User Runtime Environment
I have a C++ program that allows a user to single step through processor instructions as a processor simulator emulates a MIPS processor. The problem is that, at least in my testing stages, I need to initialize ~2^32 integers to 0xDEADBEEF. I do this at start-up. It isn't extremely important that this happens comple...
It depends. A separate process means that what happens to its runtime environment has no affect on other processes' runtime environments. If your initialization needs to affect the runtime environment of the main process, then a separate process would be tricky. A separate thread would be better, as it can affect the r...
3,322,129
3,322,196
Array Division - What is the best way to divide two numbers stored in an array?
I have two arrays (dividend, divisor): dividend[] = {1,2,0,9,8,7,5,6,6}; divisor[] = {9,8}; I need the result (dividend/divisor) as: quotient[] = {1,2,3,4,5,6,7}; I did this using array subtraction: subtract divisor from dividend until dividend becomes 0 or less than divisor, each time incrementing quotient by 1, b...
Is there a better way to do this? You can use long division.
3,322,163
3,322,989
Combination of types using boost::mpl
I have a list of types, from which I want to construct the list of all combinations with two elements. For example: namespace mpl = boost::mpl; typedef mpl::vector<int, long> typelist; // mpl magic... // the wanted list is equivalent to: typedef mpl::vector<pair<int, int>, pair<int, long>, pair<long...
The list of combinations of a single type int with the list of types mpl::vector<int, long> can be computed by invoking mpl::fold: typedef fold< mpl::vector<int, long>, vector<>, push_back<mpl::_1, std::pair<int, mpl::_2> > >::type list_of_pairs; Now, if we wrap that into a separate meta-function and invoke ...
3,322,244
3,442,903
Link Error With Visual Studio 2005 Using Windows SDK 7.1
I am in the process of evaluating an upgrade to Windows SDK 7.1 Part of my team's legacy codebase is a large number of ATL web services, which are still maintained using Visual Studio 2005 because (I am told) ATL web services are not supported in versions beyond 2005. When I pointed the IDE to SDK 7.1, I began to recei...
The hotfix listed here appears to address the link error. Not sure how I missed it before. Including here in case anyone ever searches for it using similar language.
3,322,270
3,322,942
fscanf multiple lines [c++]
I am reading in a file with multiple lines of data like this: :100093000202C4C0E0E57FB40005D0E0020C03B463 :1000A3000105D0E0022803B40205D0E0027C03027C :1000B30002E3C0E0E57FB40005D0E0020C0BB4011D I am reading in values byte by byte and storing them in an array. fscanf_s(in_file,"%c", &sc); // start code fsc...
My suggestion is to dump fscanf_s and use either fgets or std::getline. That said, your issue is handling the newlines, and the next beginning of record token, the ':'. One method is to use fscanf_s("%c") until the ':' character is read or the end of file is reached: char start_of_record; do { fscanf_s(infile, "%c", ...
3,322,359
3,322,377
Learning parsing with C++
I want to learn the basics of Parsing with C++. For that matter I thought of a simple Configuration Language that might look like this: /* same comment syntax as in C++ keywords: "section" = begins a new section block "var" = defines a new var ... */ section MySection { // also val...
The wikipedia entry on recursive descent parsers should get you started.
3,322,459
3,546,197
What are some areas of C++ code that could be affected by porting to Visual 2005 and changing to unicode?
We recently ported over legacy code to now use Visual Studio 2005 and unicode. What are the key areas that are affected by switching to the unicode character set?
My biggest nightmare of all while starting to support unicode (I don't like the word 'converting to unicode') is 3rd-party libraries which accept char* for filenames, and then forward these to legacy windows APIs like CreateFileA. It is very hard to make these support unicode if you don't have the library source code,...
3,322,482
3,322,493
C++ array value sorting
If I want to sort the second dimension's 0 element like that: short arr[5]; arr[0][0] = 122; arr[0][1] = 33; arr[0][2] = 45; arr[1][0] = 33; arr[1][1] = 12; arr[1][2] = 42; . . . It will sort arr[i][0], but arr[i][1] and arr[i][2] will come with arr[i][0] to a new element.
This should help you : http://www.cplusplus.com/reference/algorithm/sort/
3,322,739
3,322,754
Stream Operator Overloading
Why should overloading of stream operators(<<,>>) be kept as friends rather than making them members of the class?
When you overload a binary operator as a member function of a class the overload is used when the first operand is of the class type. For stream operators, the first operand is the stream and not (usually) the custom class. For this reason overloaded stream operators for custom classes which are designed to be used in ...
3,322,790
3,322,830
C++ vector copy elements?
I would like to use a dynamic array in C++ (something like an ArrayList or a Vector in Java.) In this example are the t1, t2... objects are copied or only its address is added to the vector? Do I need to implement a copy constructor for Node class or will the default constructor make a "proper" copy (because there is a...
In your example vector<Node> will store copies of your nodes, so t1,t2 will be copied. Also, the default copy constructor for Node will make a "shallow" copy. Thus Node* head = new Node(); Node* next = new Node(); head->other_node = next; Node* other_head = new Node(*head); *(other_head->other_node) is the same Node ...
3,322,903
3,322,937
C++ Replacing system("pause") call
I've read that system("pause") is slow and not advisable to use. Is there any function that I can use instead of that? I've tried getchar() but if I have a scanf call before, it simply does not waits for an other input, only if I put an other getchar() under it (but I don't think it's a good solution). edit: I'm using ...
I've tried getchar() but if I have a scanf call before, it simply does not waits for an other input Make sure you empty the input buffer before calling it; otherwise it might grab a key that was already in the buffer (like, say, a newline character...).
3,322,969
3,322,986
C++ variable scope error inside for loop
//Constructing set of all Places in Conflict with each other int l_placeVec, l_placeVec1,p; for(SP_ListListNode::const_iterator iter = m_postTransitionsSet.begin(),l_placeVec=0; iter != m_postTransitionsSet.end(); iter++,l_placeVec++) { for(SP_ListListNode::const_iterator inneriter = m_postTransitionsSet.begin(),l_...
You declared a completely different variable p in the inner loop. Here for(SP_ListNode::const_iterator iterplaces = m_placeNodes->begin(),p=0; ... The above is equivalent to declaring SP_ListNode::const_iterator p = 0 which, of course, hides the outer p. The outer p remains unused, which is what the compiler is warni...
3,322,985
3,385,510
ANTLR3 C Target with C++ Exceptions
I have some experience with ANTLR 2's C++ target, but have been hesitant to spend much time on ANTLR 3 because of my fears about exception safety. Sadly, ANTLR 3 only has a C target which produces C which is "C++ compatible." This does not seem to include C++ exception safety, based on the following: You can probably...
I don't have any ANTLR experience (sadly...), but there is NO way to make C code work with exceptions around. I refer you to More Effective C++, item 9 : "Use destructors to prevent resource leaks" The idea is that if an exception is thrown during cleanup, you have no information on what is already delete()ed an what i...
3,323,102
3,323,110
Way for C++ destructor to skip work when specific exception being thrown?
I have an object on the stack for which I wish its destructor to skip some work when the destructor is being called because the stack is being unwound due to a specific exception being thrown through the scope of the object on the stack. Now I could add a try catch block inside the scope of the stack item and catch the...
You can almost do this with std::uncaught_exception(), but not quite. Herb Sutter explains the "almost" better than I do: http://www.gotw.ca/gotw/047.htm There are corner cases where std::uncaught_exception() returns true when called from a destructor but the object in question isn't actually being destroyed by the sta...
3,323,177
3,323,183
C++: Convert wchar_t* to BSTR?
I'm trying to convert a wchar_t * to BSTR. #include <iostream> #include <atlstr.h> using namespace std; int main() { wchar_t* pwsz = L"foo"; BSTR bstr(pwsz); cout << SysStringLen(bstr) << endl; getchar(); } This prints 0, which is less than what I'd hoped. What is the correct way to do this conv...
You need to use SysAllocString (and then SysFreeString). BSTR bstr = SysAllocString(pwsz); // ... SysFreeString(bstr); A BSTR is a managed string with the characters of the string prefixed by their length. SysAllocString allocates the correct amount of storage and set up the length and contents of the string correct...
3,323,231
3,323,249
Argument Preceded by a # Token in a Macro
#define LINK_ENTITY_TO_CLASS(mapClassName,DLLClassName) \ static CEntityFactory<DLLClassName> mapClassName( #mapClassName ); This is a macro from the Alien Swarm mod for Half-Life 2, meant to be compiled with MSVC. I've never seen an argument preceded by a # in a macro before, and I'm not sure if this is a MSVC sp...
This is part of both standard C and C++ and is not implementation-specific. The # preprocessing operator stringizes its argument. It takes whatever tokens were passed into the macro for the parameter designated by its operand (in this case, the parameter mapClassName) and makes a string literal out of them. So, for ...
3,323,309
3,323,396
Question about combating contravariance. Callback-related question
I have the following piece of code which doesn't compile when I try to instance something like CommandGlobal<int> because it tries to override virtual void Execute() const =0; with a function which returns int. It gives a non-covariance error. class CommandBase { public: virtual void Execute() const =0; }; templat...
I think he meant something like (a little bit simplified): class CommandBase { private: virtual void* ExecuteMe() const =0; }; template< class T > struct CommandGlobal : CommandBase { typedef boost::function Command; Command comm; T Execute() const { return ((T)(ExecuteMe())); } privat...
3,323,319
3,323,338
C++ - parameter question
I am looking for some simple and efficient parameter container that would act like a in-memory-xml file representation (or ini-file, as another sample). I mean, basically it could store sections and sets of parameters for each section, have easy accessors like GetValue("ParameterName") and simple return value casting. ...
Take a look at boost::program_options. It does what you want and more: INI file parsing, environment variables parsing, commandline options parsing and extensibility.
3,323,447
3,323,572
Link external libraries portably?
I've got a .dll file created in VC++ 2008 that needs to be widely distributed, but also requires external resources (namely OpenSSL libraries) to operate. The dll compiles and runs perfectly well on my own system, as well as any other system with the appropriate external libraries manually installed on them, but I need...
Include OpenSSL DLLs with your distribution, or link your DLL with static OpenSSL libraries. From their INSTALL.W32: ... You can also build a static version of the library using the Makefile ms\nt.mak...
3,323,541
3,323,754
How can I make the Win32 API window more modern looking?
I ordered Programming Windows Fifth Edition a few days ago, and started working with it. I'm starting to learn the win32 api, however, I got a question. The windows do not look modern winxp/win vista/win 7 style at all. How do I fix this? It currently looks like this, crap font and all. Thanks in advance! Machiel
To get the font right you should call this after CreateWindow(Ex): NONCLIENTMETRICS ncm; ncm.cbSize = sizeof(NONCLIENTMETRICS); ::SystemParametersInfo(SPI_GETNONCLIENTMETRICS, sizeof(NONCLIENTMETRICS), &ncm, 0); HFONT hFont = ::CreateFontIndirect(&ncm.lfMessageFont); ::SendMessage(hwnd, WM_SETFONT, (WPARAM)hFont, MAKEL...
3,323,652
3,323,999
Compiling GCC 4.x.x on MinGW / MSYS Fails
I've been attempting for the last week or so to compile any of the GCC 4 series of compilers to run in MinGW 5.1.6 / MSYS 1.0.11 (automated installers both from Sourceforge.org) which ships with GCC version 3.4.5. The end goal is to get GCC 4.5 to install, but I haven't been able to get any of the 4.x.x compilers to b...
insn-modes.c should not be gigantic or filled with whitespace; genmodes is malfunctioning. I don't know why it would fail that way, but I'd be very curious to have a look at insn-modes.c (if you put it in a .zip file that should shrink it down to the point where you can reasonably upload it somewhere and edit the URL ...
3,323,675
3,323,676
C++: Fastest method to return a C string
I have a simple function that takes a char and return a string, in C it looks like; char* get_string(char c) { switch(c) { case 'A': return "some string"; Case 'B': return "some other string"; ... And it works fine, but then I wanted my code to work in C++, and the C++ compilers throws a gazillions "depreca...
Return a const char* instead of char*. The const in this context means "this pointer points to a constant pointee" - in other words, the caller cannot modify the returned string. This allows the compiler to place the strings in some memory location so the get_string() function can just return addresses to those strings...
3,323,706
3,323,748
How could this be done?
Given the following path: alt text http://img198.imageshack.us/img198/3692/curve.png How could these smooth curves be generated given that the user provides the points and that cubic bezier is used? How would the control points or bezier handles be solved for, or how could I compute these points using cubic bezier give...
Look up Catmull-Rom splines. Here's an introduction. Further reading: Catmull-Rom splines - how do they work? http://actionsnippet.com/?p=1031 http://www.cse.unsw.edu.au/~lambert/splines/CatmullRom.html (source)
3,323,759
3,369,448
Lazy symbol binding failed when linking C++ dynamic library
I'm writing a dylib in C++, but when I try to link it into my application, it gives me an error on execution: dyld: lazy symbol binding failed: Symbol not found: __ZN8Vector2DC1Ev Referenced from: /Users/noahz/Desktop/Singularity/Singularity Test App/build/Debug/Singularity Test App Expected in: /Users/noahz/Deskto...
I solved the problem by linking the library statically. It's not as elegant as dynamic linking was, but at least it doesn't crash repeatedly.
3,323,771
3,323,894
Solving linear systems of equations
I have a system of 6 equations that I need to solve over and over again in a program (with many different inputs of course). I am currently using the Cramer's rule method of solving the system and it works quite well (it seems that my processor really likes add and multiply operations, it gets solutions in 1 microsecon...
perhaps you could give http://arma.sourceforge.net/docs.html a try. It provides premade solve function, http://arma.sourceforge.net/docs.html#solve. however it uses atlas/lapack backand, which is geared more towards larger functions. You can also try multiplication by inverse, http://arma.sourceforge.net/docs.html#inv...
3,323,900
3,323,935
Passing double types to ceil results in different values for different optimization levels in GCC
Below, the result1 and result2 variable values are reporting different values depending upon whether or not you compile the code with -g or with -O on GCC 4.2.1 and on GCC 3.2.0 (and I have not tried more recent GCC versions): double double_identity(double in_double) { return in_double; } ... double result1 = cei...
On x86, with optimizations on, the results of subexpressions are not necessarily stored into a 64-bit memory location before being used as part of a larger expression. Because x86's standard floating-point registers are 80 bits, this means that in such cases, extra precision is available. IF you then divide (or multip...
3,323,932
3,323,951
Compiler problem in a (very) simple C++ program that gets numeric input from a file
#include <iostream> #include <fstream> #include <cstdlib> using namespace std; const int FILENAME_MAX=20; int main() { ifstream input; char name[FILENAME_MAX + 1]; int value; do { cout << "Enter the filename (maximum of " << (FILENAME_MAX+1) << " characters: "; cin >> name...
FILENAME_MAX is a macro that is defined by the standard library*, and so it is already taken for use as an identifier. When you try to use it as an identifier, it's actually being replaced during preprocessing to some number. A number is not a valid identifier, so you get an error. (Which is why it's saying "I was expe...
3,324,023
3,324,066
Passing condition as parameter
First of all to explain what I'm trying to do: void Foo(int &num, bool condition); Foo(x, x > 3); This code basically would evaluate the bool of the condition before calling the function and then pass pure true or false. I'm looking for a way to make it pass the condition itself, so I could do something like this: vo...
One example using a standard library functor: #include <functional> template<class UnaryPred> void func(int& num, UnaryPred predicate) { while(!predicate(num)) num = std::rand(); } void test() { int i = 0; func(i, std::bind1st(std::greater<int>(), 3)); } See the documentation on <functional> for what C++...
3,324,130
3,324,139
Erasing numbers from beginning and end of std::string
Would there be a better way to do this using alogrithm functions like std::find()? std::string s = "012X012Y012"; //After erasing the numbers from beginning and end; the end result should be X012Y size_t index = s.find_first_not_of("0123456789"); string::iterator iter_end = s.begin(); advance(iter_end, index); s.eras...
Seems fine enough. I'd factor out your constant: const std::string Numbers = "0123456789"; And re-use that. erase does allow you to use indices instead of iterators, so you can trim all that iterator stuff from your code. You should also check the results of your search, otherwise you'll do weird things to your string...
3,324,198
3,324,213
Compile errors for double linked list code
I have tried to implement doubly linked list in C++. Here is the code, #include <iostream> using namespace std; //double linked list class Link{ public: long data; Link *next; public: Link(long d) { data=d; } void displaylink() { cout<<data<<" "<<...
if (empthy) is wrong, empthy is a function so it should be if (empthy()).BTW, method name should be empty.
3,324,248
3,324,741
How to name this key-oriented access-protection pattern?
Apparently this key-oriented access-protection pattern: class SomeKey { friend class Foo; SomeKey() {} // possibly non-copyable too }; class Bar { public: void protectedMethod(SomeKey); // only friends of SomeKey have access }; ... doesn't have a known name yet, thus i'd like to find a good one for ...
I like, in decreasing preference: passkey friend idiom passkey-door friend idiom pass-door friend idiom key-door friend idiom partial-friend idiom restricted-friend idiom I moved away from the key-lock/key-keyhole naming scheme to the pass naming scheme, which grew on me.
3,324,293
7,355,110
boost::asio hangs in resolver service destructor after throwing out of io_service::run()
I'm using a fairly simple boost::asio set-up, where I call io_service.run() from the main thread. I have a tcp resolver, and use async resolve to look up an address. When that look-up fails, I throw an exception inside the asynchronous callback. I catch this exception outside the run() call, inside the main function. I...
I then call stop() on my io_service Try to use this trick (copied from io_service documentation) when you need to stop io_service: boost::asio::io_service io_service; auto_ptr<boost::asio::io_service::work> work( new boost::asio::io_service::work(io_service)); ... work.reset(); // Allow run() to exit. The reaso...
3,324,312
3,324,323
C++ int a[n] working in g++ but not with vs2008
I have the following code: ... int n; cin >> n; int numbers[n]; ... It compiled with NetBeans on Mac using g++ (I think) and it didn't compile using VS2008 on Windows. Why is it so hard to make it work with every compiler? The size of the array is known before allocating it. EDIT: I know about std::vector. Actually th...
Although the size of the array is known before it is allocated, it's still not known until runtime. This is known as variable length array (VLA) and is a C99ism, supported in g++ by an extension that is enabled by default. To be explicit, this is not conformant C++ 98/03, and thus Visual C++ is well within its right ...
3,324,490
3,324,560
Perforce P4Python API Bug
I am compiling on Ubuntu 10.04 LTS. The Perforce Python API uses their C++ API for some of it. So, I point the setup.py at the C++'s API directory using the --apidir= they say to use. When it starts to compile the C++, I get a whole load of errors (temporary error list link is now gone). No one else has had these error...
Woops! Forgot I still needed to install python-dev...
3,324,554
3,324,748
Catching functors using SFINAE in structure partial specialisation
For some complicated reason, I want to convert any supported type T (coming from a template) to a list of types I have chosen. For this, I tried using a template structure named "Convert". For example: Convert<short>::type should be int Convert<int>::type should be int Convert<char>::type should be int Convert<float>::...
I'd suggest you use the first approach, but to make it work, you'll have to Declare the master template with one unused template-argument: template <class T, class = void> Convert; Add a void parameter to all specializations of the template you use now. Define your "functor specialization" like this: template<typename...
3,324,640
3,324,659
Strange "Could not deduce template argument for 'T'" error
The error is in this code: //myutil.h template <class T, class predicate> T ConditionalInput(LPSTR inputMessage, LPSTR errorMessage, predicate condition); //myutil.cpp template <class T, class Pred> T ConditionalInput(LPSTR inputMessage, LPSTR errorMessage, Pred condition) { T input cout<< inputMes...
C++ cannot deduce the return type of a function. It only works with its arguments. You have to explicitly call ConditionalInput<int>(...).
3,325,115
3,325,149
Remove a list of selected items in the QListView
How can I remove a list of selected items in the QListView in QT 4.6. Something like this does not work, the iterator becomes invalid: QModelIndexList indexes = ui.listview_files->selectionModel()->selectedIndexes(); foreach(QModelIndex index, indexes) { model->removeRow(index.row()); } removeRows also not...
QModelIndexList indexes; while((indexes = ui.listview_files->selectionModel()->selectedIndexes()).size()) { model->removeRow(indexes.first().row()); }
3,325,128
3,325,134
Problem with C++ templates
I am trying to build small logger library. I am facig some problem with c++ templates. Here is what my class structure looks like. class abstract_logger_t { public: typedef abstract_logger_t logger_type; template<typename data_t> abstract_logger_t& log(const data_t& data) { return *this; } }; class stdou...
template<typename data_t> abstract_logger_t& operator<< (abstract_logger_t& logger, const data_t& data) { output(logger, data); return logger; } Here, whatever logger you pass in, the compiler will convert it into an abstract_logger_t&. You need to make the first argument templated too. template<typename T, typen...
3,325,524
3,325,539
What is the << operator doing in C++?
In the example below, what exactally is the << operator doing? I'm guessing it is not a bitwise operator. std::cout << "Mouse down @ " << event.getPos() << std::endl; I understand what the code will do here: Use standard out, send this text, send an end of line. Just I've never come accross the use of this << apart fr...
The answer is: The << operator does left shifts by default for integral types, but it can be overloaded to do whatever you want it to! This syntax for piping strings into a stream was first (I think) demonstrated in C++ inventor Bjarne Stroustroup's eponymous book The C++ Programming Language. Personally, I feel that r...
3,325,625
3,325,724
Visual Studio: Syntax highlighting for Doxygen-style C++ comments
I want enchanted syntax coloring in comments for C++ language in Visual Studio 2010. For example, I have the following code: /*! \sa testMeToo() \param a the first argument. \param s the second argument. */ int testMe(int a,const char *s); In Visual Studio all \param, \sa and other Doxygen commands a...
You can use Visual Studio Extensibility to add custom syntax highlighting. You'll have to check MSDN and the Visual Studio Extensibility SDK to find out how though.
3,325,744
3,326,027
Fastest way to create random vectors for benchmarking
So, I'm just playing around implementing some sorting algorithms in C++, but I'm finding it irritating to benchmark them at the moment, due to the length of time it takes to not run the algorithm, but to create the input data. I currently test each length of input (1000, 2000, ...) 10 times, to gain a somewhat averaged...
Is there a better way to do this? Yup, there are a few things you might want to do here to help speed things up. As mentioned before, reserving space in the std::vector and then assigning values to the known elements, is faster. Also, pre incrementing ( ++var instead of var++ ) is faster when using non optimized com...
3,325,761
3,325,850
Behavior of an expression: Defined or Undefined?
I have the following code int m[4]={1,2,3,4}, *y; y=m; *y = f(y++); // Expression A My friend told me that Expression A has a well defined behavior but I am not sure whether he is correct. According to him function f() introduces a sequence point in between and hence the behavior is well defined. Someone please c...
At best, the code in question has unspecified behavior. For the assignment operators, "the order of evaluation of the operands is unspecified" (C99 §6.5.16/4). If the left operand is evaluated first, the result of f(y++) will be stored in m[0]. If the right operand is evaluated first, the result will be stored in m[1...
3,325,848
3,325,892
Way of determining the size of the container
Is there any other way to determine size of the container than : //those are valid iterators from a container BidIt begin; BidIt end; std::size_t size = 0; while (begin != end) {//Here throug iterating I'm getting adventually the correct size ++size; ++begin; } but I wonder if I could check size of this contain...
You can use the distance function. Note that if your iterators are not RandomAccessIterators the distance function will use basically the same method of calculating the distance that you've shown.
3,325,870
3,326,089
C++: extern and inline functions
I have a couple of files written in C, and I want them to be C++-compatible, so for my C headers I use; #ifdef __cplusplus extern "C" { #endif at the beginning of the file and of course #ifdef __cplusplus } #endif ...at the end. But it seems to create problems with the 'inline' keyword. My solution is to simply remo...
If I understand correctly, I would do: #ifdef __cplusplus #define D_INLINE static extern "C" { #else #define D_INLINE inline #endif And use the D_INLINE for the functions that I think should need inline. As delnan said, the compiler will optimize it anyway and the inline keyword is just a hint to the compiler t...
3,325,891
3,775,127
Scheduler library in C++ similar to Java Quartz
I'm looking for a cross-platform library in C/C++ which can schedule jobs, function calls, etc. It would be nice if it is closer to Java Quartz. I would prefer BSD style licenses, LGPL would be okay too.
Libevent: http://www.monkey.org/~provos/libevent/ is probably too heavyweight for your use case, but you can decide for yourself if it works for you. Edit: This is more about scheduling functions after certain timeouts within a program. Looking at Quartz, it appears to be broader. So I doubt if libevent is what you are...
3,326,076
3,326,085
question about qsort implementation
i have implement this code from programming pearls and i think it should be correct but it gives me this mistake code: #include <stdio.h> #include <iostream> #include <string.h> using namespace std; using std::qsort; int charcmp(char*x,char *y){ return *x-*y;} #define wordmax 100 int main(void){ char word[wordmax...
Your charcmp function needs to take const void* parameters: int charcmp(const void* x, const void* y) { return *(const char*)x - *(const char*)y; } The error message: cannot convert parameter 4 from 'int (__cdecl *)(char *,char *)' to 'int (__cdecl *)(const void *,const void *)' is telling you that the argume...
3,326,102
3,326,137
Seg fault vector<vector<list<Object*> > > push_back
I have a 3D vector defined like this... std::vector<std::vector<std::list<Object*> > > m_objectTiles; I have this code... void ObjectManager::AddObject( Object *object ) { m_objects.push_back( object ); m_objectTypes.insert( std::make_pair( ObjectAttorney::GetType( object ), object )); int x = ObjectAttorn...
std::vector's [] for performance reasons doesn't do range checks. Obviously that second variant doesn't help if x or y are out of range. Add a check like that: m_objectTiles.size() < x && m_objectTiles[x].size() < y It is hard to judge from the quoted code, but it might be that you want std::vector to grow automatical...
3,326,134
3,326,219
C++ boost/asio client doesn't connect to server
I am learning boost/asio ad wrote 2 programs(client and server) from e-book with minor changes. Basically it should connect to my server. When i try to connect to outside world(some random http server ) all is good and it works but when i change destination to "localhost:40002" it says invalid argument. client code: #i...
The second parameter to ip::tcp::resolver::query is the service name, not a port number: boost::asio::ip::tcp::resolver::query query("localhost", 40002); should be boost::asio::ip::tcp::resolver::query query("localhost", "40002"); fyi, when I compiled your code on my system it failed: resolve.cc: In function ‘int...
3,326,238
3,326,262
Is destructor called when removing element from STL container?
Say I have two containers storing pointers to the same objects: std::list<Foo*> fooList; std::vector<Foo*> fooVec; Let's say I remove an object from one of these containers via one if its methods: std::vector<Foo*>::iterator itr = std::find( fooVec.begin(), fooVec.end(), pToObj ); fooVec.erase( itr ); CppReference...
No. When you remove a pointer from a container, all you've done is take that pointer value from the container, nothing is deleted. (i.e.: pointers have no destructor.) However, it's dangerous to have pointers of things in containers. Consider: std::vector<int*> v; v.push_back(new int()); v.push_back(new int()); v.push_...
3,326,351
3,326,381
Dynamic Programming Problem
I am just unable to get the hang of dp. I know what I've to do but am just unable to implement it.E.g this practice problem from 'Codechef' http://www.codechef.com/problems/MIXTURES/ If i consider the min smoke for mixtures i to j as m[i,j] then for k<- i to j m[i,j]=min(m[i,k]+m[k+1,j]+cost of mixing the resulting ...
Yes, you are on the right track. The color of m[i,j] does not depend on the order of the mixtures.
3,326,433
3,326,628
Is this a "recognised" OO pattern? Need sanity check!
Say if I want to extend the functionality of a range of objects that I cannot change - for instance for adding formatting, and don't want to derive a huge amount of classes to extend the functionality - would the following considered bad? (I'm using int and float as an example, but in my program I have about 20 or 30 ...
Have you considered specializing your template for each of the types you wish to print? This should work without changing the way you're calling the code - but it'll also provide some compile-time type checking to ensure that your generic type has a valid print() method. template<> class ObjectNode<int> : public virtua...
3,326,566
3,326,574
Implementing something like std::vector.back()
I would like to implement something like this because my application is divided into scenes and this gets sort of messy: glEngine.scene[glEngine.current.currentScene].layer[glEngine.scene[glEngine.current.currentScene].currentLayer].Shapes.push_back(CGlShape()); instead I'd want to be able to do something like this: g...
We have no idea what your classes are, but just make a function: struct glEngine { // ... scene_type& Scene() { return scene[current.currentScene]; } }; You can also do this for Scene, returning the current layer: struct scene_type { // ... layer_type& Layer() { return lay...
3,326,690
3,326,762
Qt - There is a bug in QPropertyAnimation?
I face a very serious situation. By writing this question I hope that really professionals will express their opinion regarding to the problem I am going to describe. I have reported a bug in https://bugreports.qt.io/ : I have created QPropertyAnimation for maximumWidth property of QTextEdit and it does not work (it i...
Did you check the actual value of maximumWidth? You don't seem to set a specific maximumWidth in your code. The default value for maximumWidth is 16777215, and you set a duration of 1 msec. for the closing animation. Fading from 16777215 to 3 in 1 msec. would look like "instant", I guess.
3,326,717
3,327,088
Another 'x was not declared in this scope'
this is my first question here. Writing some code, i receive this error from g++: "Entity was not declared in this scope", in this context: #ifndef Psyco2D_GameManager_ #define Psyco2D_GameManager_ #include <vector> #include "Entity.h" namespace Psyco2D{ class GameManager{J private: std::vector<Entity...
Assuming the first snippet is part of GameManager.h you have a circular header dependency. I believe you can fix this by changing the GameManager.h include in Entity.h to class GameManager; instead. Additionally as GMan noted, Entity is in a namespace and you need to qualify Entity with the namespace name.