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
5,497,541
5,497,679
templated template parameter list with template types
C++ allows templated template parameters like this: template <template <bool> class T> struct something1 {}; Bool type can be replaced by a typedef (so there is no requirement for the original type name to appear in the declaration): typedef bool bool_t; template <template <bool_t> class T> struct something2 {}; This...
That appears to be a bug in VC++; I verified that the behavior is unchanged in VC++ 2010 SP1. I recommend posting a bug report on MS Connect then posting the link here so we can vote it up.
5,497,593
5,497,633
operator "<<" to a pointer
I have a class Terminallog which is overloading the << operator. If I do the following Terminallog clog(3); clog << "stackoverflow.com is cool" << endl; everything works fine. "stackoverflow.com is cool" is printed in a nice colored way to the screen, exactly what Terminallog is supposed to do. Now I try Terminallog*...
Dereferencing a pointer to write *clog << "My message" << endl; does not create a copy of the object being pointed at. In general, pointer dereferences don't make copies, and the only way to make a copy is to either explicitly create one, pass an object into a function by value, or return an object from a function by...
5,497,605
5,513,845
Bind a function against a range to make an iterating function
I am trying to implement my own bind_range that can bind against a range. It should allow client code like this: void f(int x, int y) { std::cout << x + y << ','; } std::vector<int> v1; // contains 1,2,3 void go() { boost::function<void(int y)> f_bound = bind_range(f, v1, _1); f_bound(10); // prints 11,1...
I worked on this a little and here is what I came up with. It works, but is incomplete as there are only templates for unary functions and binary functions where the range is bound to the first parameter. If anyone takes this further and makes it more generic, please do post back here. #include <boost/bind.hpp> #incl...
5,497,987
5,498,052
Constructing struct within union
I have created a union comprising a uint64_t and a struct. I would like the union constructor to construct the inner struct but I can't seem to get it working. Here's a couple of variations I have tried: union subid_u { inline subid_u(uint32_t gid_, uint32_t sid_) : detail.gid(gid_), detail.sid(sid_) {} ...
You can't initialise members of members like that: you'd have to have a constructor in detail and invoke that from subid_u's ctor-initialiser. union subid_u { inline subid_u(uint32_t gid, uint32_t sid) : detail(gid, sid) {} struct detail_t { detail_t(uint32_t gid, uint32_t sid) : gid(gid), sid(sid)...
5,498,210
5,498,294
Reflection in Qt/C++
I just started with Qt and discovered the QMetaObject wich is very nice/handy in my opinion. Now I wondered if it is possible to get information like current function name, calling function name or current stack with Qt/standard C++ or any other C++ library. I need this for debugging/logging purposes. In C# for example...
There is a macro PRETTY_FUNCTION that returns a nice formatted function name. It is available in GCC and maybe some other compilers.
5,498,256
5,498,341
Vector template question
Question as I have not done much with vectors and templates. If I have a class foo that is templated class and I want to create a vector of foo pointers regardless of foo type, what would the syntax look like?
Not possible. When you use a class template anywhere, you need it instantiated on a type. One possibility to circumvent that, is to provide a polymorphic interface base class for foo and have a vector of those pointers. class IFoo{ virtual void bar() = 0; virtual int baz() = 0; }; template<class T> class Foo : IFo...
5,498,389
5,503,735
Mediator C++ GUI sample
I have heard that somewhere @ web I'll be able to find good C++ example of Mediator working with GUI components. But I menaged to find only that GoF sample or things from sorcemaking and similar that aren't helpful to me. So... do you know where that mentioned GUI sample can be found? Sorry for that kind of question, b...
How about this one: http://www.andypatterns.com/index.php/design_patterns/model_gui_mediator_pattern/. It appears the author is applying the pattern specifically to the 'view' part of the GUI functionality (as opposed to the data modeling behind it). Not sure if that's what you were looking for...
5,498,474
6,315,990
How to achieve smooth sound fading effects?
What is the best possible way to smoothly fade in/out a sound with SFML 1.6? It has SetVolume() and SetAttenuation(). These two directly set these values. But I need a smooth transition from one sound to another.
I think the best way would be to set the volume lower and lower with each frame/time step.
5,498,487
5,498,547
Binary search Tree Implementation.
I was trying to implement binary search tree but I think I have made a mistake in my insert function. Here's my code #include<iostream> #include<memory.h> #include <cstddef> using namespace std; struct bst_node { int info; struct bst_node *left_node_ptr; struct bst_node *right_node_ptr; }; struct bst_node*...
You never actually set the left_node_ptr or right_node_ptr values of your nodes. Your insert function runs down the tree finding the correct place to put the new node, then allocates the node - but doesn't actually attach the new node to the left or right of the parent you found.
5,498,515
5,498,538
C++ want to call derived function from base class
I have following situation class base { public: virtual void Accepted(SOCKET s) //// Event { } void Listner() { SOCKET acpted; Accepted(acpted); /// When I call I want derived class's Accepted() to get called } }; class derived { virtual void Accepted(SOCKET s) //// Even...
class derived : public base will make derived actually inherit from base. Then your virtual function call will work as expected. Note that you cannot make such virtual function calls in the constructor or destructor of base - At the time base's constructor is invoked, the derived part doesn't yet exist. At the time bas...
5,498,619
5,498,635
Is struct assignment atomic in C/C++?
I am writing a program which has one process reading and writing to a shared memory and another process only reading it. In the shared memory there is a struct like this: struct A{ int a; int b; double c; }; what I expect is to read the struct at once because while I am reading, the other process might ...
No, both C and C++ standard don't guarantee assignment operations to be atomic. You need some implementation-specific stuff for that - either something in the compiler or in the operating system.
5,498,701
5,498,752
C++ std::async vs async/await in C#
I'm wondering if the new c++ feature std::async is quite comparable to the two C# keywords async/await or not and if not why?
Not really, assuming I'm reading this std::async documentation correctly. C# 5's async/await feature involves a complex compiler transformation of the asynchronous method so that you can write code which looks pretty much synchronous, but has points of asynchrony. The compiler builds a state machine for you, creates ap...
5,498,937
5,498,993
When do we need to have a default constructor?
My question is simple. When do we need to have a default constructor? Please refer to the code below: class Shape { int k; public: Shape(int n) : k(n) {} ~Shape() {} }; class Rect : public Shape { int l; public: Rect(int n): l(n) {} //error C2512: 'Shape' : no appropriate default constr...
A default constructor is not synthesised if you created your own constructor with arguments. Since you gave Shape a constructor of your own, you'd have to explicitly write out a default Shape constructor now: class Shape { int k; public: Shape() : k(0) {} Shape(int n) : k(n) {} ~Shape() {} };...
5,499,085
5,499,150
c++ overload constructor with int and char*
I try to overload constructor with int and char *. Then there is ambiguity in call with 0. Is there any workaround/solution for this? CBigInt (unsigned int); CBigInt (const char *); The problem is on the line with 0: CBigInt a; // some more code a *= 0; Thanks for answering.
Make one of the constructors explicit. It will then only be used when passed type exactly matches. CBigInt (unsigned int); explicit CBigInt (const char *);
5,499,155
5,499,169
C++ member-function pointer
Consider the following class class Foo { typedef bool (*filter_function)(Tree* node, std::list<std::string>& arg); void filter(int filter, std::list<std::string>& args) { ... if (filter & FILTER_BY_EVENTS) { do_filter(events_filter, args, false, filter & FILTER_NEGATION); ...
bool (Foo::*filter_Function)(Tree* node, std::list<std::string>& arg) Will give you a member function pointer. You pass one with: Foo f; f.filter(&Foo::events_filter,...); And invoke it with: (this->*ff)(...); // the parenthesis around this->*ff are important If you want to be able to pass any kind of function / func...
5,499,189
5,499,222
std::string vs string in c++
Possible Duplicates: Why is 'using namespace std;' considered a bad practice in C++? Using std Namespace Ive been hovering around a bunch of different forums and i seem to see this pop up every time and again. Its a very much beginner question. I usually define a program with #include<string> using namespace std; s...
As the other answer already stated, using std:: is necessary unless you import either the whole std namespace or std::string (see below). In my opinion it's nicer to use std::string instead of string as it explicitly shows that it's a std::string and not some other string implementation. If you prefer to write just str...
5,499,392
5,500,341
Rationale on Boost.Preprocessor using macros instead of simple defines?
For example BOOST_PP_ITERATE and BOOST_PP_ITERATION, as seen on GMan's answere here, are preprocessor macros, without any parameters. Is there a reason they're not just simple defines and used as such without ()?
Generally, function like macro can be used to prevent unintentional macro expansion. For example, assuming that we have the following macro call: BOOST_PP_CAT( BOOST_PP_ITERATION, _DEPTH ) and we expect this will be expanded into BOOST_PP_ITERATION_DEPTH. However, if BOOST_PP_ITERATION is an object like(non-functional...
5,499,464
5,502,311
Use Informix Object Interface for C++ for stored procedures/functions with out parameters
It's simple - is there a way to use this lib to call stored procedure or function, that returns more than one result? I know about the ITRoutingManager, but it seems to return just one value.. In details, here's what I mean: CREATE FUNCTION test_out1( pin INT ) RETURNING INT; DEFINE param INT; LET param =...
As you note, Informix does not have 'OUT' parameters really; it returns values. In regular ESQL/C, you treat a list of output values symmetrically with a list of input values; I would expect to do the same with this code, therefore. Whatever technique you use to pass 2 arguments to the function is likely - but by no m...
5,499,786
5,500,089
Hello! a beginner with C++ Programming& I need help
Okay! I really need your help or some tips I need a program that I will recieve a raise on my previous years salary. I need to calculate and display the amount of annual raises for the next three years. I want to use the rates o 3% 4% 5% and 6%. This is what I have so far but its not working #include <iostream> #inclu...
What you want to do is this: int beginSalary; do { cout << "Beginning Salary (negative number or 0 to end): "; cin >> beginSalary; if (beginSalary <= 0) break; for (int percent = 3; percent <= 6; percent++) { cout << endl << "Raise for " << percent << "% for the next three years: " << endl;...
5,499,812
5,499,851
Problem with function template without <>
Is there anyway I can do this without writing func2<int>(); int func() { return 5; } template<class T> T func2() { return func(); } int main() { auto k = func2(); //auto k = func2<int>(); return 0; }
No, because the template argument can not be deduced. You need to specify it, how else would the compiler know what to substitute it with? int? double? A user-defined type? Edit If you're already using C++0x (I assume so because of auto), you can use the new trailing return type function style: auto func2() -> decltype...
5,499,919
5,500,077
Using sed to convert text file to a C string
I would like to use sed to replace newlines, tabs, quotes and backslashes in a text file to use it as char constant in C, but I'm lost at the start. It would be nice to maintain the newlines also in the output, adding a '\n', then a double quote to close the text line, a crlf, and another double quote to reopen the lin...
Try this as a sed command file: s/\\/\\\\/g s/"/\\"/g s/ /\\t/g s/^/"/ s/$/\\n"/ NB: there's an embedded tab in the third line, if using vi insert by pressing ^v <tab> s/\\/\\\\/g - escape back slashes s/"/\\"/g - escape quotes s/ /\\t/g - convert tabs s/^/"/ - prepend quote s/$/\\n"/ - append \n and quote...
5,499,967
5,499,999
Gamma distributed random variables in C++
What is the easiest way to get a gamma distributed random variable in C++? Boost seems to have this functionality, but it is not clear for me how to use it.
It’s pretty straightforward: boost::mt19937 rng; boost::gamma_distribution<> pdf(alpha); boost::variate_generator<boost::mt19937&, boost::gamma_distribution<> > generator(rng, pdf); Constructs a random number generator and a gamma distribution and glues them together into a usable generator. Now you can create ran...
5,500,461
5,500,651
create a boost::posix_time::ptime instance for X number of milliseconds
boost::interprocess::scoped_lock<boost::interprocess::named_recursive_mutex> when creating an instance, i need to use the scoped_lock(mutex_type & m, const boost::posix_time::ptime & abs_time); constructor. how can i create a scoped_lock for X number of miliseconds ?
If X is milliseconds you want to spend while waiting for lock acquirance then this snippet should help you: boost::posix_time::ptime till = boost::posix_time::microsec_clock::local_time() + boost::posix_time::milliseconds(X); ... { boost::interprocess::scoped_lock(some_mutex, till); ... }
5,500,522
5,500,837
How to prepend to a file (add at the top)
Imagine you have a file sink("example.txt") data.frame(a = runif(10), b = runif(10), c = runif(10)) sink() and would want to add some header information, like /* created on 31.3.2011 */ /* author */ /* other redundant information */ How would I add this "header"? Doing it manually seems trivial. Hit a few Enters, c...
in R there is no need to work with an extra file. You can just do : writeLines(c(header,readLines(File)),File) Yet, using the linux shell seems the most optimal solution, as R is not famous for performant file reading and writing. Especially not since you have to read in the complete file first. Example : Lines <- c( ...
5,500,719
5,500,841
Problems compiling boost signal2
Why does this simple example not compile, and how can I get around the problem? #include <iostream> #include <boost/signals2/signal.hpp> struct HelloWorld { HelloWorld() { i = 0; } void operator()() { std::cout << "I is: " << i++ << std::endl; } void setup () { sig.connect...
You are trying to connect to a pointer, which isn't possible. Instead you need to connect to a reference to your object: void setup () { sig.connect(boost::ref(*this)); }
5,500,902
5,500,962
Operator Precedence Puzzle
I have variables with their initial value defined as: x = 10, y = 4, z = 1 and what's those variable values in y>>=x&0x2&&z ? I would do: y >>= ((Fun1) && z) Fun1 = x&0x2, that is the bit operation of 1010 & 0010 = 0010, or 2 in decimal; Fun1 && z returns 1, or 0001 in binary Then my question is what is the operation...
y >>= 1 is the same as y = y >> 1 So it should effectively integer-divide y by 2.
5,500,952
5,970,854
Convert type into python
I'm using boost python. I've exported some function which takes class CL_DomElement in arguments. Now, when I run app I have: TypeError: No to_python (by-value) converter found for C++ type: CL_DomElement So what about code. I've exported function which takes function-pointer in arguments. Here is the code: typedef bo...
Boost.Python call by reference : TypeError: No to_python (by-value) converter found for C++ type:
5,500,971
5,501,151
Need help with (an attempt of) a quicksort algorithm in c++
I've tried a bunch of different ways to write this, but mostly i get stuck in an endless loop. This version of the code just doesn't sort it at all and i don't know what the problem is. void quickSort(int unsorted[], int left, int right) { int i = left, j = right; int pivot = (left + right) / 2; whil...
You didn't test your function on an array of length 1. Get that to work, then try an array of length 2. Once that's working, there's a good chance it'll work when you give it an array of length 3. EDIT: Kudos for including a reproducible example. This code fails before recursion. The first step is to choose a pivot ele...
5,501,010
5,501,336
Problem with Unicode in C++ exe (MSVC++2010)
I have a strange problem which I don't know where it came from. I might have changed some settings in the MSVC++2010 project but it all looks good to me. I'm currently experimenting with the VSHADOW.EXE 3.0 tool included with Windows SDK 6.1. This is a sort of backup program written in C++ and the strings in it are com...
Problem solved, I changed wmain to main for a test and forgot to change it back.
5,501,090
5,523,239
In a directx application, find z (terrain) with known location
My english knowlage is not good enought to tell my problems. and i am using stackoverflow second time. i am hooking a directx application, i just can wrote something to screen and get input from screen and other things. This game has a terrain, and a lot of players. I can directly edit the player location (x, z, y). Bu...
It works on Knight OnLine. its a wrapper to CN3Terrain::GetHeight(float x, float z). float getY(float x, float z) { __asm { PUSH 0 PUSH z PUSH x MOV ECX,DWORD PTR DS:[0x0C26C20] MOV ECX,DWORD PTR DS:[ECX+1Ch] MOV EDX,DWORD PTR DS:[ECX] CALL DWORD PTR DS:[EDX+34h] }}
5,501,496
5,502,083
read from file and convert to double in C++
i have a problem with reading from a file, and converting content to double. I have read the solutions from stackoverflow but nothing works. i have this input file: 1291.23 291.493 558.089 309.266 513.656 491.44 429.234 851.345 589.192 535.873 802.469 713.604 1002.42 997.973 513.656 313.709 407.018 624.738 460.337 526....
As a quick sanity check, try just copying the entire file to standard output, something like this: #include <iostream> #include <iterator> #include <algorithm> int main() { std::ifstream in("mr1.txt"); std::copy(std::istream_iterator<double>(in), std::istream_iterator<double>(), ...
5,501,924
5,501,969
Incrementing a streampos Object
I'm trying to do something like this: for (std::streampos Position = 0; Position < 123; Position++) { // Use Position to access something... } However, it appears that std::streampos does not have operator++ overloaded. Trying to use Position = (Position + 1) results in the following error: ISO C++ says that these...
Try a std::streamoff, which represents an offset in a stream. It supports both pre- and post increment/decrement operators. The underlying type is implementation defined, but must be able to be consistently converted to both streamsize and fpos (thus, to streampos too) Edit to Maxpm's comment: You can apply the strea...
5,501,948
5,501,981
C++: static vars not persisting between files
I have a config.h file with a bunch of constants. in main.cpp, it sets one of the constants to some value, and then calls a function in util.cpp. util.cpp also has config.h included, but the variable set by main.cpp does not have the same value. Code: config.h: static int MAX_NUMBER_OF_TRAINING_DATA = 1000; main.cpp (...
Each translation unit receives its own copy of static data. The easiest way to verify this is to print the address of MAX_NUMBER_OF_TRAINING_DATA in both units - it will be different. To avoid it, declare it extern in the header and define it once in one unit, for example in main.cpp. Apart from that is it evil to hav...
5,501,959
5,503,690
Why does C++11's lambda require "mutable" keyword for capture-by-value, by default?
Short example: #include <iostream> int main() { int n; [&](){n = 10;}(); // OK [=]() mutable {n = 20;}(); // OK // [=](){n = 10;}(); // Error: a by-value capture cannot be modified in a non-mutable lambda std::cout << n << "\n"; // "10" } The question: Why do we need ...
It requires mutable because by default, a function object should produce the same result every time it's called. This is the difference between an object orientated function and a function using a global variable, effectively.
5,502,213
5,502,456
C++ STD::MAP Complex Key Search
I have limited access to libraries so although using boost::multi_index would solve my issue it is something that I cannot use. My current map setup is: The structure contains a fair amount of information in it such as an INT that I will also need to search by. What I was hoping was a structure such as so that I can ...
I'm a little confused. You seem to be saying that you have a construct like this: (psudocode) struct Gizmo { Gizmo(int foo, string bar) : foo_(foo), bar_(bar) {}; int foo_; string bar_; }; Gizmo make_gizmo(int foo, string bar) { return Gizmo(foo,bar); } std::map<string, Gizmo> my_gizmos; my_gizmos["aaa"] = make...
5,502,320
5,502,508
Is typedef good for improving extendability
#include <iostream> using namespace std; typedef int num; int main() { num a, b; cin >> a >> b; cout << a + b; return 0; } In this way if I have to change this to float or a complex number by only changing one line of code. Is this a good practice to do?
I wouldn't say that this style is useful typedef int num; Because num doesn't really mean much more and isn't imparting more information. However, what you do see is segregating of types, like for instance typedef long time_t In this case, in the standard library, instead of using a long to represent a number of s...
5,502,368
5,502,656
C++, how to tokenize this string?
How can I get string like "Ac milan" and "Real Madryt" if they are separated with whitespace? Here is my attempt: string linia = "Ac milan ; Real Madryt ; 0 ; 2"; str = new char [linia.size()+1]; strcpy(str, linia.c_str()); sscanf(str, "%s ; %s ; %d ; %d", a, b, &c, &d); but it doesn't work; I have: a= Ac; b = (null);...
Yes, sscanf can do what you're asking for, using a scanset conversion: #include <stdio.h> #include <iostream> #include <string> int main(){ char a[20], b[20]; int c=0, d=0; std::string linia("Ac milan ; Real Madryt ; 0 ; 2"); sscanf(linia.c_str(), " %19[^;]; %19[^;] ;%d ;%d", a, b, &c, &d); std:...
5,502,602
5,502,736
ICC segfaulting with variable length arrays
So, when compiled with the basic icc bob.cpp -o bob and run, the following code segfaults: #include <string> int foo () { return 6; } int main() { std::string t[foo()]; } The following two similar programs, however, seem to run fine. #include <string> int foo () { return 6; } int main() { int f = foo(); ...
Well, while it is true that C++ has no variable-length arrays (C99 does though), apparently ICC does support them as an extension, since your code actually compiles (and since your second snippet actually runs without crashing). If the first version crashes, then it must be a bug in ICC's implementation of that non-sta...
5,502,787
5,502,815
connecting c/c++ and python
What I am trying to do is that I want to read a file using python, and then with the data in the file, create a variable in c/c++(I don't want to read var from the file :) ). Is this possible? If this is possible, then how would you do it? Thank you guys!
Yes. Open the first file in Python, process it and save the results to a second file. Then open the second file in your C or C++ program and use the data.
5,502,914
5,503,403
Converting legacy app to current VS and Windows-7
I have limited knowledge of C++ (so far). Done some modifications on existing software, but that's it for now. Usually I am working with other programming languages. My task is to take a legacy app written in C++ / Win32 / MFC / Visual Studio 2003 and get it "up to date". "Up to date" means: it should be Windows-7 co...
MS works very hard to be backward compatible from what I know. Try check if it doesn't just work - if code was written correctly (i.e. did not depend on quirks, undocumented functions etc.) it should work. Well - from your post I assume it doesn't so goto 2. If it does not work. Try compile. Remove any warning and/or ...
5,502,916
5,506,601
Explain Morris inorder tree traversal without using stacks or recursion
Can someone please help me understand the following Morris inorder tree traversal algorithm without using stacks or recursion ? I was trying to understand how it works, but its just escaping me. 1. Initialize current as root 2. While current is not NULL If current does not have left child a. Print current’s...
If I am reading the algorithm right, this should be an example of how it works: X / \ Y Z / \ / \ A B C D First, X is the root, so it is initialized as current. X has a left child, so X is made the rightmost right child of X's left subtree -- the immediate predecessor to X in an inorder traversa...
5,502,994
5,503,085
Diamond shaped polymorphic Inheritance: sizeof Most derived Class
I understand that the Diamond shaped inheritance causes ambiguity and it can be avoided by using inheritance through virtual Base Classes, the question is not about it. The question is about sizeof the most derived class in a diamond shaped hierarchy when the classes are polymorphic. Here is a sample code and the sampl...
Yes, Derived3 has two vtable pointers. If you're accessing it by value, it uses the Derived3 version, or picks a function from a parent, or denotes that it's ambiguous if it can't decide. In the case of a child, it uses the vtable corresponding to the parent 1/2 that's being used polymorphically. Note that you didn't u...
5,503,009
5,505,014
Netbeans 6.9.1 problem finding library on Ubuntu
I am on a time crunch, and I can't seem to get Netbeans (6.9.1) to find a library I need to incorporate a memory allocator form libcds, I have coded what I believe to be a correct incorporation of the ~/cds-0.8.0/cds/memory/michael/allocator.h file. The problem I have is that in my Netbeans project, it can't find the l...
To anyone else wanting to use this library here is the general guide: First Make Sure you know if your system is 32 bits or 64, do not assume, since it is a 6 core, 8gb of Memory beast that it is running 64, like i did. 1) In the cds-0.8.0/build/sample, copy the script that best suites your os (I have no suggestions fo...
5,503,183
5,503,556
Windows API StartService ... localized service name
I want to start the Volume Shadow Copy service with a C++ program. This involves getting a handle to the service control manager (OpenSCManager), using this to obtain a service handle (OpenService) and then starting the service (StartService). However, I have to pass the service name as a string to the OpenService func...
Are you absolutely sure that Volumeschattenkopie is the service name on German Vista? It is definitely the service display name, but OpenService is looking for the name that was used during CreateService, which may not be localized. To locate the original service name, go into the services control panel, bring up the p...
5,503,350
5,503,397
(C++) Can't get deque insert() to work, what am I doing wrong?
I'm getting an error on the insert() part here, and I dunno what I am doing wrong. I've tried different parameters and number of parameters but nothing seems to work. m_oGameObjectList is a deque of IGameObjects (base class). m_sPosition is a struct with 3 ints (X, Y, Z). gameObject is the reference to an object derive...
insert takes an iterator. Use: m_oGameObjectList.insert(m_oGameObjectList.begin() + i, gameObject); You'll also need to use pointers in your deque, right now you're slicing - inserting a copy of the IGameObject part of gameObject
5,503,352
5,503,442
Const before or const after?
To start you probably know that const can be used to make either an object's data or a pointer not modifiable or both. const Object* obj; // can't change data Object* const obj; // can't change pointer const Object* const obj; // can't change data or pointer However you can also use the syntax: Object const *obj; // s...
why is there two correct ways of specifying const data and in what situation would you prefer or need one over the other if any? Essentially, the reason that the position of const within specifiers prior to an asterisk does not matter is that the C grammar was defined that way by Kernighan and Ritchie. The reason the...
5,503,363
5,503,875
Can you translate this debugging macro from C++ to python?
I use this very helpful macro when developing in C++: #define DD(a) std::cout << #a " = [ " << a << " ]" << std::endl;std::cout.flush(); Could you help me implement the same idea in python? I don't know how the #a could be implemented with a python function...
You could inspect the stack trace and "parse" it. Since you know the name of your function (dd in this case) it becomes fairly easy to find the call and extract the name of the variable. import inspect import re def dd(value): calling_frame_record = inspect.stack()[1] frame = inspect.getfr...
5,503,438
5,503,482
C++ Operator () parenthesis overloading
I recently asked a question about removing items from a vector. Well, the solution I got works, but I don't understand it - and I cannot find any documentation explaining it. struct RemoveBlockedHost { RemoveBlockedHost(const std::string& s): blockedHost(s) {} // right here, I can find no documentation on over...
It's called a functor in C++ This answer has a good example etc C++ Functors - and their uses
5,503,473
5,503,492
How to return array of strings?
I have function: int read_file() { ifstream file("plik"); if(!file.is_open()) { throw -1; } int i = 0; string line[MAXSIZE]; while(getline(plik, line[i])) { cout<<line[i]<<endl; i++; } return i; } But i want to return array of strings: line[] How can I do this?
Don't. Arrays are not copyable. Use a std::vector<std::string> instead.
5,503,561
5,504,078
Program crashes after call to push_back() for vector of pointers despite previous ok usage
I have a situation where i'm creating objects with new and storing a pointer to these objects in a vector. I later copy the pointer across to another vector and delete it from the original vector. In a seperate test program I have been able to do this with no trouble at all. When added to a larger program I end up with...
Shouldn't your node copy be: closedSet.push_back(openset[element]); openSet.erase(openset.begin()+element); In your copy code think about what happens when element is 0. Basically you are not deleting the right node pointer from openSet when copying which will result in both leaked memory and double-freed pointers whe...
5,503,605
5,503,705
Instantiating a function definition in a template that uses decltype only in certain circumstances
As an exercise in understanding C++0x, I am trying to create a C++ class that wraps a pointer of some template-ized type: template <typename T> class Wrapper { T *t; /* ... */ }; Inside of the Wrapper class, I would like to expose any overloaded operators that T may implement through the Wrapper class. The wr...
You can declare the operator as a non-member template: template <typename T> auto operator++(Wrapper<T>& arg) -> decltype(++*arg.t) { return ++*arg.t; }
5,503,618
5,510,698
CUDA convolution - non separable kernels
I need to implement an efficient version of an image convolution with non-separable kernels (so CUDA's sdk is useful just for the FFT example, but it is clearly stated that it works great only for big kernel sizes) Aside from implementing it from scratch as comes to my mind, my need is to operate on priori-unknown-size...
My suggestion with the gpu: First make it right. Get confortable with the algorithm that you want to implement on the GPU first on the CPU. You will have to deal with so many more low level details, so is important that you know what the output must be. Make it fast. FFT approach is the fastest one if you ...
5,503,714
5,504,287
Check if a ptr belongs to a virtual class?
My code was acting wonky and i was able to mini reproduce it with the code below. (codepad link) From http://www.cppreference.com/wiki/keywords/dynamic_cast If you attempt to cast to a pointer type, and that type is not an actual type of the argument object, then the result of the cast will be NULL. From my un...
The issue is that dynamic_cast expects either: a null pointer a valid pointer Here you can only offer it garbage, so it is useless, and not the cast you want. If you are getting a void*, then you can use reinterpret_cast (better than a C-cast, because more visible) to cast it into another type: void* p = 0x123; Dummy...
5,503,863
5,503,952
Removing Characters from a File
How can arbitrary characters be removed (not replaced by something) in a file? #include <fstream> int main() { std::fstream FileStream("MyFile.txt", ios_base::in | ios_base::out | ios_base::binary); // For the sake of argument, MyFile.txt already has stuff in it. FileStream.seekg(5); FileStream.remove...
You have two options: Read the entire file in the memory, then save it to the file excluding unwanted parts. Copy the source file to newly created file excluding unwanted parts, remove the source file, then rename second file.
5,503,901
5,504,296
How to correctly reference a function in an anonymous namespace
Consider this fragment of C++ code: namespace { void f() { } class A { void f() { ::f(); // VC++: error C2039: 'f' : is not a member of '`global namespace'' } }; } GCC compiles this just fine. Visual C++ 2008 fails to compile spitting out the C2039 error. ...
VC++ 2008 is wrong here. According to the c++03 standard 3.4.3.4: A name prefixed by the unary scope operator :: (5.1) is looked up in global scope, in the translation unit where it is used. The name shall be declared in global namespace scope or shall be a name whose declaration is visible in global sc...
5,503,937
5,511,601
making boost::python::range accepting... a boost::range
I have a c++ class which exposes collections by providing functions returning ranges, using boost::range. In order to export this class to python with boost::python, I use the function boost::python::range, which can accept two parameters: the member functions of the class returning the begin and end iterators of the c...
The solution was to use the more general form a range with four template parameters: create begin/end accessors as boost::bind'ed objects, and then specify the Target template parameter of range. For const iterators, this code fulfills my needs: namespace py = boost::python template <class T, class Return> struct range...
5,504,027
5,504,153
There's a strlen, and a wcslen, but is there a template function like strlen<char> or strlen<wchar_t>?
There's a strlen, and a wcslen function, but is there a templated character array length function so you can do something like strlen<char> or strlen<wchar_t>? If not, then I guess I'll write my own.
You have the char_traits helper used by std::string. It provides char_traits<char>::length and char_traits<wchar_t>::length.
5,504,401
5,505,406
How to instantiate with other than defaulted parameters in a template template parameter
I'm trying to cement my understanding of template template parameters. In C++ Templates the Complete Guide (Vandervoorde, Josuttis), they have an example on page 52 that I want to use as indicated in this image: (I'm also trying to learn how to use images from Picasa on stackoverflow so if the above doesn't work, here...
The parameter definitions inside CONT are actually not used by the compiler. The template-template parameter CONT is actually similar to a function, which takes 2 types input and return a new type: // pseudo code type Stack(type T, type(*CONT)(type ELEM, type ALLOC = etc)) { return CONT(T); } and like the normal f...
5,504,514
5,504,606
Forward declaration causing VC++ errors, not sure how to resolve
I've looked around for a while, tried quite a few different approaches to this issue, but still cannot seem to get past errors occurring from forward declaration in a program with 3 codependent classes. Here's a abstracted view of my current code's structure, split into 6 files + 1 main program file: File x.h: #ifndef ...
This isn't a forward declaration problem. Main.c can see the full declaration of class z. It must be that z has no constructor, at least of the proper shape, or maybe it is private.
5,504,708
5,504,720
Is this function guaranteed to be expanded inline
I was going through some code at work and I found this inline FLAGS get_flags(void) { FLAGS res; memset(&res, 0, sizeof(res)); return res } This is declared in a header file included in the program. I realize it would be a very bad thing if it was not inlined as this is allocated on the stack. We have never ...
No, it is not guaranteed to be expanded inline. inline is merely a hint to the compiler. That said, while res does indeed exist on the stack, you return a copy of it. It won't be "a very bad thing" if inline expansion doesn't occur.
5,504,725
5,504,741
How can identically named namespaces at different hierarchy levels be addressed without conflict?
(The problem I'm solving involves a 3rd party lib that I cannot change) #include <list> //Third party lib namespace namespace foo { typedef int SomeType; } //my namespace namespace mycompany { namespace groo { typedef std::list<foo::SomeType> SomeTypeList; } namespace foo { ty...
When the compiler is confused about scope, you can always address a namespace absolutely. The global scope is :: so foo::SomeType's absolute scope name is ::foo::SomeType I'm not really sure why the compiler doesn't automatically search the shallower namespace when it doesn't find the symbol in the deeper one though......
5,504,768
5,505,397
How to use a color LUT in Qt QImage
I have some legacy code that was writing to a NITF file to display some images. In the legacy code, it appears as if there was a LUT being used, and there was a section of code that wrote out a row at a time to the NITF file , and the values of that row were calculated like so: // convert RGB to LUT values unsigned cha...
The qRgb constructor looks like this: qRgb(int r, int g, int b) You're passing in the same value (lutData[i*imwidth + j]) for all three colors, so you'll end up with a greyscale image. Now, qRgb is just a typedefed unsigned int, so if you store your colors in that format (RGB32 / ARGB32), you can just call: qi->setPix...
5,504,774
5,504,893
Using C++ std::equal on a container of shared_ptr
I have a container of std::shared_ptr. I want to compare two containers using std::equal. The class A has operator== defined. I want equal to compare if each element is equivalent using its operator==, not the one defined in shared_ptr. Do I need to make a function or function object to pass to equal? Or is there s...
You will need a function or a function object or a lambda expression (since you're able to use std::shared_ptr, you have some part of C++0x already enabled). There is nothing in <functional> to help you, but there is something in boost: the indirect iterator #include <iostream> #include <vector> #include <algorithm> #i...
5,504,856
5,504,921
Algorithms and Data Structures
I'm currently halfway through my first algorithm and data structures class. Unfortunately, my teacher is not very good, and the online book we use is incredibly vague in its descriptions (http://people.cs.vt.edu/~shaffer/Book/) I've manage to maintain an A thus far, mostly due to luck and common sense, but it's startin...
This course is great: http://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-046j-introduction-to-algorithms-sma-5503-fall-2005/video-lectures/ There are data structure, algorithm and more
5,505,221
5,505,232
Converting QString to char*
Possible Duplicate: QString to char conversion I have a function (fopen in STL) that gives a char* argument as a path in my computer, but I must use QString in that place so it doesn't work. How can I convert QString to char* to solve this problem?
See here at How can I convert a QString to char* and vice versa? In order to convert a QString to a char*, then you first need to get a latin1 representation of the string by calling toLatin1() on it which will return a QByteArray. Then call data() on the QByteArray to get a pointer to the data stored in t...
5,505,289
5,505,571
C++ Bitset array, accessing values
I've got the task to create a graph's adjacency matrix from a list of adjacent nodes, stored in a file (don't need the weights) into a bitset array in C++. I successfully read the adjacent nodes from the file, but when I try to store it in the bitset array the outcome is not right. My function is the following: bitse...
With the pointer to a local array problem fixed, your code runs for me and prints what's expected (except mirrored). But wouldn't it be easier to use C++ I/O in this case? #include <vector> #include <bitset> #include <iterator> #include <fstream> #include <sstream> #include <iostream> const int N=6; std::vector<std::bi...
5,505,533
5,506,240
QList of user templated defined structs
Can I define a QList such that it holds a collection of templated structs, with each struct defined on different type ?? Consider: template<typename T>struct AA { T value; } Can I declare a QList such that it holds different instances of AA ?? something like: struct<int> myIntStruct; myIntStruct.value = 10; struct<d...
Why you would want a container to have dissimilar objects is probably a design flaw. However some languages support this such as Smalltalk which has the concept of a Bag Collection that can contain a mix of different object types. Qt may have some sort of bag container class already but I am unaware of it's existence...
5,505,706
5,506,052
Using mmsystem.h in VisualStudio 2008
I'm trying do create a 64bit dll which sets a global hook. As I read it can't be done with CLR (I even tried), so I created a Win32 project and I will build it for 64bit platform. Will it work this way? My main question is how to use mmsystem.h in this project. I need to use multimedia timer and when I use timeBeginPer...
You have to link with winmm.lib, it isn't one of the default libraries that gets linked. A simple way is to put the link instruction in your source code: #include <windows.h> #include <mmsystem.h> #pragma comment(lib, "winmm.lib")
5,505,725
5,506,015
Alexandrescus smart assert with return value
I'm using Andrei Alexandrescus smart assert technique for my assert facility, basically the interface is: ASSERT( foo == bar, "Foo doesn't equal bar!" )( foo )( bar ); As it turns out, often when the assert doesn't hold one wants to do an early exit, which leads me to the following overload: ASSERT( foo == bar, "Foo ...
Though not quite satisfactorily, I post this just in case this can be a hint for you: #define ASSERT3( expr, msg, ret, ... ) \ if( (expr) ); \ else { \ Make...
5,505,965
5,506,223
Fast string splitting with multiple delimiters
I investigated some time here on StackOverflow to find good algorithms to split strings with multiple delimiters into a vector< string >. I also found some methods: The Boost way: boost::split(vector, string, boost::is_any_of(" \t")); the getline method: std::stringstream ss(string); std::string item; while(std::getli...
Two things come to mind: Use string views instead of strings as the split result, saves a lot of allocations. If you know you're only going to be working with chars (in the [0,255] range), try using a bitset to test membership instead of finding into the delimiter characters. Here's a quick attempt at applying these ...
5,506,021
5,507,285
Sorting strings in C++ using operator <
The following array is given in C++ code: char strings[105][105]; What is the correct way to write operator< to sort the strings using STL sort function and is it possible at all?
You can't overload operator< for pointers, but you don't need to, since std::sort can accept any comparison function (or functor). Another problem is that the sort algorithm cannot swap arrays, because they are not assignable. But you can sort an array of pointers into the two-dimensional array (leaving the original ar...
5,506,340
5,515,290
What is the best way to store a relation in main memory?
I am working on an application which is a mini DBMS design for evaluating SPJ queries. The program is being implemented in C++. When I have to process a query for joins and group-by, I need to maintain a set of records in the main memory. Thus, I have to maintain temporary tables in main memory for executing the querie...
A Relation is a Set of Tuples (and in SQL, a Table is a Bag of Rows). Both in Relational Theory and in SQL, all tuples (/rows) in a relation (/table) "comply to the heading". So it is interesting to make an object to store relations (/tables) consist of two components: an object of type "Heading" and a Set (/Bag) obje...
5,506,343
5,506,375
In Qt QwebKit how can I delete all cookies when starting?
I implemented the cookies jar as shown in the web, and I can receive all the cookies values; but how can I delete all cookies I don't understand? Here is my code where can I trigger the delete all cookies and how? #include <QNetworkCookieJar> class QNetworkCookieJarEx : public QNetworkCookieJar { public: QNetw...
Pass an empty list to QNetworkCookieJar::setAllCookies()
5,506,645
5,506,657
How to read / write a struct in Binary Files?
I am facing a small problem. I have a struct, which has a vector. Note that the vector is dynamic per every iteration. Now, in a particular iteration, how do I store the struct which contains a vector of size n to a binary file? Also, when retrieving, assume that I know how the size of the vector, how to I retrieve fro...
You should have a look at Boost Serialization. If you can't use 3rd party libraries, you must know that C++ doesn't support serialization directly. This means you'll have to do it yourself. This article shows a nice way of serializing a custom object to the disk and retrieving it back. And this tutorial shows you how t...
5,507,377
5,507,497
Template type deduction for a pointer to member function
I have a very similar problem to that presented by Morpheus, in the following question: Overloaded member function pointer to template The solution proposed by Richard Corden requires the user to explicitly specify the function parameter type, to distinguish it among the overloads. However, this solution does not seem ...
For a.connect<double> (&GApp::foo), both the foo(double) and foo(double, double) will match the overload of connect with one, and with two template parameters respectively (in the case of the two parameter version, the second template argument will be deduced, the first argument was provided by you explicitly). If you...
5,507,469
5,512,385
Basic QT in C++ - Having trouble comprehending
I'm having trouble understanding how QT works. Can somebody show me an example, where you have a frame with a button named "button1" and when that button is pushed, do something, maybe a cout << "hi"; I can't seem to understand how to setup the slot for a QPushButton.
See this: Signals & Slots
5,507,499
5,507,528
String Arrays/Char Arrays
This is what I have to do: A teacher has asked all her students to line up single file according to their first name. For example, in one class Amy will be at the front of the line and Yolanda will be at the end. Write a program that prompts the user to enter the number of students in the class, then loops to read in ...
You cannot create such an array because its length has to be known at compile time (i.e., it cannot be the result of an expression such as StudentNum + 1). You can solve this issue because by the problem definition you know an upper bound for the array size, so you can use that as a compile time constant. However, this...
5,507,545
5,507,561
c++ how to write a constructor?
I'm not used to c++ and I'm having a problem writing a constructor. See this example, is a short version of the code I'm working on: class B { public: B(int x); } class A { public: B b; A(){ // here I have to initialize b } } That throws a compiler error since I need to initialize b in A's constructor bec...
You can invoke functions in your constructor initializer list class B { public: B(int x); }; // note semicolon class A { public: B b; A() :b(calculateValue()) { // here I have to initialize b } static int calculateValue() { /* ... */ } }; // note semicolon Note that in the initializer list, th...
5,507,875
16,260,210
How to adapt a visitor interface to an iterator interface?
I'm wondering whether there is a good design pattern or idiom to realize the following: You have an existing class that provides only a visitor interface, as follows class Visitor { public: virtual ~Visitor() { } virtual void visit(Node *n) = 0; }; class Tree { public: void accept(Visitor *v); }; And you want ...
I had this problem in a real-world setting with an R-tree implementation that provided a visitor interface, whereas I needed an iterator interface. The suggestion by Jerry above works only if you can accept storing all the results in a collection. That may result in high memory consumption if your result set is huge an...
5,507,879
5,519,984
Strange Case of the missing method: SXS and Controls.Add results in "object doesn't support this property or method"?
I have a project written in VB6 that uses a UserControl, The project runs fine when the OCX is registered, but if I run the same project with a side by side manifest it results in an error. I can use the Control with no problem as long as it's loaded statically (added before on the form) but if I add a dynamic control ...
The short answer: This is a known problem with VB6. The "Controls.Add" statement does not work with side-by-side. Try using a "Load" statement instead. The long answer: VB6 compiles the CLSID of the control into the executable even though you use a ProgID to create the control. Execution of "Control.Add" verifies that ...
5,507,895
5,507,918
Sorting alphabetically
Here is my code...What would be the best way to sort names alphabetically? #include <iostream> #include <iomanip> #include <string> using namespace std; int main() { int StudentNum; cout << "How many student are in the class?\n"; cin >> StudentNum; string sname[25]; if (StudentNum < 1 || Student...
The standard way is to use std::sort: #include <algorithm> // ... std::sort(sname, sname + StudentNum); std::sort uses operator< by default, which actually does an alphabetical comparison for strings. EDIT: Indeed, it should be StudentNum instead of 25.
5,507,924
5,507,951
C++ Passing ostream as parameter
I'm working on a homework project for a virtual rolodex that has called for a main class, a rolodex class, and a card class. To output the contents of all of the "cards" to the console, the assignment says that main() should call a show(...) function in the rolodex class, passing it an ostream and show(...) then iterat...
What I don't understand is why an ostream would/should be passed anywhere. This is often used for things like testing. Say you want console output normally, so you'd pass around a reference to std::cout. But sometimes you want to do testing, e.g. unit or acceptance testing, and you want to store the output in memory ...
5,508,110
5,508,168
Why is this program erroneously rejected by three C++ compilers?
I am having some difficulty compiling a C++ program that I've written. This program is very simple and, to the best of my knowledge, conforms to all the rules set forth in the C++ Standard. I've read over the entirety of ISO/IEC 14882:2003 twice to be sure. The program is as follows: Here is the output I received whe...
In the standard, §2.1/1 specifies: Physical source file characters are mapped, in an implementation-defined manner, to the basic source character set (introducing new-line characters for end-of-line indicators) if necessary. Your compiler doesn't support that format (aka cannot map it to the basic source character se...
5,508,122
5,508,377
C-like procedures in C++?
Does the C++ correct programming style demand writing all your code with classes or are C-like procedures allowed ? If I were to give some code to someone else, would it be accepted as C++ just because it has std::vector and std::string (instead of char *) inside, or everything has to be a class? eg: int number = 204; ...
C++ is a multi-paradigm language, where OO, procedural, generic/generative and - to a lesser (but increasing with C++0x) extent functional - are among the paradigms. You should use whichever is the best fit for the problem: you want the code to be easy to get and keep right, and hard to stuff up. The utility of classe...
5,508,182
5,508,201
"static const int" causes linking error (undefined-reference)
I am baffled by the linker error when using the following code: // static_const.cpp -- complete code #include <vector> struct Elem { static const int value = 0; }; int main(int argc, char *argv[]) { std::vector<Elem> v(1); std::vector<Elem>::iterator it; it = v.begin(); return it->value; } Howev...
If you want to initialize it inside the struct, you can do it too: struct Elem { static const int value = 0; }; const int Elem::value;
5,508,540
5,508,721
From Memory Address to Source Line of Code
I'm using WinDBG and have the following stack trace: ntdll!NtTerminateProcess+0xa KERNELBASE!TerminateProcess+0x2f MSVCR90!_invoke_watson+0x11c [f:\dd\vctools\crt_bld\self_64_amd64\crt\src\invarg.c @ 234] MSVCR90!_invalid_parameter+0x70 [f:\dd\vctools\crt_bld\self_64_amd64\crt\src\invarg.c @ 115] MSVCR90!fgetpos+0x33 [...
It can do this, just not from any window. It works from Call Stack window (Alt+6) -- double click on the frame that has mapped to the line of code and it will get you to the line in source file. It opens the file if it is not currently opened in WinDbg.
5,508,746
5,508,839
How can I refer to the type in a nested template for a parameter argument?
Suppose I have the following definitions template <class T> class Sequence { } E.g Sequence<string> might be an array of strings, similar to vector<string> // Now define iterator template template <class T> class SequenceIterator { } The idea here of course is to be able to create an iterator over some sequence E.g. ...
There are three ways: change the definition of Sequence to include typedef T type; or, change the template parameters for SequenceIterator to explicitly recognize that Sequence is a template itself template< template < class > class Seq, class T > class SequenceIterator< Seq< T > > and while the instantiation of Sequ...
5,508,848
5,508,912
Pointer Variable Sizes
Would a constant-size array int x[20] be smaller than a dynamic array int * x = new int[20], since the dynamic array is a pointer, which takes up space? Or is the constant-sized array a pointer too? Why or why not? Another question: Something I've never been 100% sure about is, on a 32-bit machine, are pointers 32 bits...
The dynamic one will use more memory; how much more depends on the size of pointers and the size of the memory allocator's metadata. On any modern machine, as @Jonathan says, 32-bit machines use 32-bit pointers and there is no significant difference (aside from stack vs. heap) in how pointers are handled vs. data. Old...
5,508,922
5,509,085
What's the usual way of controlling frame rate?
I'm new to graphics, so I don't know how people usually control the frame rate for rendering things. I mean, how can you set you application to render at, say, 30fps? There's probably lots of APIs that offers such thing, but I need to code it from scratch.
There are two "usual" ways of "controlling" framerate, and neither is quite that simple. The first and more controlling of the two, and something that is usually optional, is VSync. This forces the video card to only push out a new frame when the monitor is done refreshing. Many monitors refresh at 60 Hz, so you tend t...
5,508,990
5,509,179
Ensuring a widget has a container?
Here is my problem: In the game gui I'm developing, the "desktop" is a class I call WidgetManager. In order for me to communicate certain things, like focus, between the gui and a widget, every widget must have a pointer to the widget manager. The problem is, the user can add children to a widget which is not yet part ...
If every Widget is created by a WidgetManager, you can pass that in during creation. I think, however, your problem comes from combining the functions of the WidgetManager (perhaps better referred to as WidgetFactory) and the top-level Widget. I can think of two potential solutions to work with, both with pros and cons...
5,509,001
5,509,161
for loop iterations in c++
I'm building a simple list using a dynamically allocated array in C++. I have a function remove(int item) that should remove all occurrences of item in the list. However, if I make a loop that iterates from 0 to length in the array, I'm worried I will exceed the boundaries of my array because length changes as I delete...
Another solution would be to search the reverse. Only keep those which are not equal to the item to be removed. void List::remove(int item) { int insert = 0; for (int i = 0; i < length; i++) { if (data[i] != item) data[insert++] = data[i]; } length = insert; }
5,509,091
5,509,964
How to update display in OpenGL during processing?
It's been over a year since I last used OpenGL so I'm rusty on the topic. I have an image that I'm doing some processing on, colour clustering to be specific, and I want to update the image after every loop iteration so I can see the changes as they happen rather than in the end when processing is complete. This is wha...
To solve the issue I explicitly called my display callback function at the end of each iteration rather than letting glut decide when the best time is to call the display callback. In pseudo code, the solution looks something like this. colourClustering() { loop { image processing code } display...
5,509,395
5,509,740
Deleting user-defined elements in the middle of a vector
I'm coding a program where I want to draw a card, and then delete so that it doesn't get drawn again. I have a vector of Cards (class containing 2 structs that define Suit and Value) called deck and I don't really know how to use iterators very well, here a code snippet: void Player::discardCard(CardDeck masterDeck) { ...
My bet is that getDeck returns the vector by value. It causes itr to point to and erase to operate on different copies of the vector. Thus you get the error. You should return the vector by reference. Change getDeck signature to this one: vector<Card>& getDeck()
5,509,482
5,509,620
Cannot open include file: 'log4cxx\logger.h': No such file or directory
Is there any API for log4cxx?if so specify the location to download? Thanks
Here it is - http://logging.apache.org/log4cxx/download.html
5,509,756
5,509,794
Acessing derived members from vector of base type
Say I have some situation like this: class Vertex { public: Position position; Normal normal; Texcoord texcoord; int boneID; }; class VertexSkinned: public Vertex { public: float boneWeights[3]; int boneIDs[3]; }; class VertexMorphed: public Vertex { public: Position posTargets[3]...
I don't see any other option other than storing the pointers and dynamic_cast later to get the derived object. If you want to do something like, can't you have 3 different vectors each with its own type. In that case, there is no need of the pointer business.
5,509,796
5,632,011
CUDA - linking errors with convolution example
I'm trying to compile the following code by Joe Stam (convolutionapproaches, project with vs2005, I am using VS2010 but compiling with 9.0 engine) 1>ConvolutionCudaFunctions.obj : error LNK2019: unresolved external symbol _cudaEventDestroy@4 referenced in function "float _cdecl NaiveGlobalConvolution(unsigned ch...
There was a problem with 32/64 bit sdks, I solved by linking with the 32 bit
5,510,168
5,510,279
Which Qt widget (not webkit) that can display html image link (like item list)
i like to display image from server without downloading it , sure i can use qwebkit. but i like to be able to display the image in some kind of list . what option do i have ?
I know that QTextEdit supports img tags, and I use them in lists. However, I don't know if it actually supports full URLs for those images, I just use images from the resource file. You could however give it a try. Use setHTML() to set the HTML source code, setText() assumes plain-text.
5,510,230
5,510,313
example of point-based gravity in c++
I am trying to figure out how to implement gravity into my application i'm creating. I have a sphere in Opengl and im wanting to give it gravity like a planet. so any small objects near it will "fall" to the surface of it. Im wondering if anyone could point me in the direction of a example in c++.
You need to write a function that implements the gravity formula, for example: const float g = 9.81f; // Gravity of Earth in m/s² float gravity(Vec3 p1_pos, Vec3 p2_pos, float p1_mass, float p2_mass) { float distance = (p2_pos - p1_pos).length(); return g * p1_mass * p1_mass / (distance*distance); } Multiply ...
5,510,292
5,510,426
Naming convention for Object Ownership in Methods
Is there a way to code into the signature of a method, whether the object owner-ship changes or not? In Getter() and Setter() which take or return pointers, you never know if the object ownership changes or not. What do you think about: // Uses pConfiguration or creates its own copy - the ownership is un-touched void C...
The best way of identifying in an interface that ownership is not changed is by not using pointers. Prefer references to pointers: // Does not take ownership void ContainerClass::SetConfiguration( const Configuration& config ) {} // Does not release ownership const Configuration& ContainerClass::getConfiguration() con...
5,510,628
5,975,787
c++ googlemocks : Getting a stack trace of an uninitialized call
Mock class looks like this : struct MockClass { MOCK_METHOD0( foo, void () ); }; If I forget to set an expected calls on a mock object, I get something like this : GMOCK WARNING: Uninteresting mock function call - returning directly. Function call: foo() Stack trace: and the stack trace is empty. So, what has to...
This is described here : You can control how much Google Mock tells you using the --gmock_verbose=LEVEL command-line flag, where LEVEL is a string with three possible values: 1. info: Google Mock will print all informational messages, warnings, and errors (most verbose). At this setting, Google Mock will a...