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,743,459
3,743,477
Why do I get "Expected ;" error and "Variable not declared in scope" error?
i have following code #include <iostream> #include <set> #include <string> using namespace std; template<class Container> void print(const Container &c) { Container::const_iterator itr; for (itr=c.begin();itr!=c.end();itr++){ cout<<*itr<< '\n'; } } int main(){ set<string,greater<string>>s; s.ins...
You need typename Container::const_iterator instead of Container::const_iterator. At the point the compiler is reading your code, it doesn't know that Container has such a type (it is a so-called dependent name).
3,743,630
3,743,635
"Invalid conversion" error with conditional operator
I'm getting compile error in this line: cout << (MenuItems[i].Checkbox ? (MenuItems[i].Value ? txt::mn_yes : txt::mn_no) : MenuItems[i].Value) Error: menu.cpp|68|error: invalid conversion from 'int' to 'const char*' menu.cpp|68|error: initializing argument 1 of 'std::basic_string<_CharT, _Traits, _Alloc>::basic_stri...
The two possible conditional values have to be convertible to a common type. The problem is that the left of the outer conditional: (MenuItems[i].Value ? txt::mn_yes : txt::mn_no) is always a string, but the right: MenuItems[i].Value is an int. It tries to find a way by going const char *->string, but then it won't...
3,743,693
3,743,847
Macro detect KDE or GNOME in qt4
I have a problem to detect when used in GNOME or KDE operating system that runs the application. The program I am doing QT4, and I have trouble feeling of look- in the systray, so I pass it to KDE, but which is not macro to do so. PD: I use KDE and C / C. I search in web and I see this: Creating executable for Windows ...
Qt does not provide this kind of defines based on the desktop environment. If you need to know the desktop environment at compilation time, then your best bet would be to modify your build system to pass the necessary defines to the compiler. The desktop environment can be concluded by different prerequisites such as e...
3,743,732
3,743,780
Template function specialization for specific interface
I have the following piece of code: class ICookable { public: virtual void CookMe () = 0; virtual ~ICookable () {}; }; class Egg : public ICookable { public: virtual void CookMe () {cout << "Egg cooked!" << endl;} }; template <class T> void Cook (T&) { cout << "Item Uncookable!" << endl; } template <...
Compile-time dispatch through boost::is_base_of and class template partial specialization: template<class T, class _> struct CookDetail { static void cook(T& obj) { cout << "uncookable\n"; } }; template<class T> struct CookDetail<T, boost::true_type> { static void cook(ICookable& obj) { obj.CookMe(); } ...
3,743,764
3,743,802
place a value in the sorted position immediately
I have a question for a c++ lab assignment I have. The task is to implement some function for adding values, remove values from an array and so on. I have done most of it now, however I have some problem with the insert function. The assignment requires me to insert float values to this array without using any algorith...
You have to shift all elements to make room for the new element. This is an O(n) operation. Since you can't do better than O(n) I think it is reasonable to use this simple O(n) algorithm: Set i to the index of the last element in the array If the element to insert is larger then a[i] then insert the element at index i...
3,743,985
3,759,102
Boost threads: is it possible to limit the run time of a thread before moving to another thread
I have a program with a main thread and a diagnostics thread. The main thread is basically a while(1) loop that performs various tasks. One of these tasks is to provide a diagnostics engine with information about the system and then check back later (i.e. in the next loop) to see if there are any problems that should...
If you run multiple threads they will indeed consume CPU time. If you only have a single processor, and one thread is doing processor intensive work then that thread will slow down the work done on other threads. If you use OS-specific facilities to change the thread priority then you can make the diagnostic thread hav...
3,743,991
3,744,264
Variable Argument lists with boost?
I wanted to write a function with a variable argument list. I want to explore my options. I'm pretty sure I came accross a boost template class that was designed for this purpose, but I can't think of the name of it? Can anyone tell me? or did I dream this up! Thanks
If you only need to accept a variable count of arguments of the same type, taking a container would be the common thing to do. Creation of the container however can be eased using Boost.Assign: void f(const std::vector<int>& vec) {} f(boost::assign::list_of(1)(2)(3)(4)); Alternatively you can go for operator overloadi...
3,744,023
3,744,352
Detecting C++0x mode on Intel C++?
Does Intel C++ predefine some macro when compiling with Qstd=c++0x? Something like __GXX_EXPERIMENTAL_CXX0X__ in GCC? __cplusplus is still 199711. Any way to detect C++0x compilation?
The Intel documentation indicates that it does define __GXX_EXPERIMENTAL_CXX0X__ on Linux, but does not define any macro on Windows.
3,744,247
3,751,434
Python: Passing unicode string to C++ module
I'm working with an existing module at the moment that provides a C++ interface and does a few operations with strings. I needed to use Unicode strings and the module unfortunately didn't have any support for a Unicode interface, so I wrote an extra function to add to the interface: void SomeUnicodeFunction(const wchar...
For Linux you don't have to change your API, just do: SomeModule.SomeFunction(str(s.encode('utf-8'))) On Windows all Unicode APIs are using UTF-16 LE (Little Endian) so you have to encode it this way: SomeModule.SomeFunctionW(str(s.encode('utf-16-le'))) Good to know: wchar_t can have different sizes on different plat...
3,744,400
3,744,745
trailing return type using decltype with a variadic template function
I want to write a simple adder (for giggles) that adds up every argument and returns a sum with appropriate type. Currently, I've got this: #include <iostream> using namespace std; template <class T> T sum(const T& in) { return in; } template <class T, class... P> auto sum(const T& t, const P&... p) -> decltype(t ...
I think the problem is that the variadic function template is only considered declared after you specified its return type so that sum in decltype can never refer to the variadic function template itself. But I'm not sure whether this is a GCC bug or C++0x simply doesn't allow this. My guess is that C++0x doesn't allow...
3,744,635
3,744,644
Is it a good idea to always return references for member variable getters?
If I have a class that has many int, float, and enum member variables, is it considered efficient and/or good practice to return them as references rather than copies, and return constant references where no changes should be made? Or is there a reason I should return them as copies?
There is no reason to return primitive types such as int and float by reference, unless you want to allow them to be changed. Returning them by reference is actually less efficient because it saves nothing (ints and pointers are usually the same size) while the dereferencing actually adds overhead.
3,744,675
3,744,690
Size of references in 64bit environments
Came across this one while browsing the response to another question on SO (References Vs Variable Gets). My question is that for all 64bit environments is it guaranteed that a reference to a variable will be of 64 bits even if the original had a lesser size? As in char references in 64bit environment would be >sizeof(...
The Standard (ISO C++-03) says the following thing about references It is unspecified whether or not a reference requires storage (3.7). Please someone correct me if I am wrong or if I have not understood his question correctly. EDIT: My question is sizeof(c2) > sizeof(c1) in 64bit machines? No, as @Chubsdad noticed ...
3,744,710
3,751,718
How to profile the time of calling initializer functions when dyld loads an image?
I am now trying to optimize the launch time of an application, and currently want to reduce the time spent by the OS image loader. From dyld(1), I found two environment variables: DYLD_PRINT_STATISTICS and DYLD_PRINT_INITIALIZERS. DYLD_PRINT_STATISTICS causes dyld to print statistics about how dyld spent its time. This...
Can you use this technique? I've seen slow startup of a large app, which was loading a lot of dlls and doing a lot of initializing. Sampling will tell what's going on, that you can fix, and it will probably surprise you. For example, what I never would have guessed is the amount of time spent setting up internationaliz...
3,744,852
3,745,438
Undefined reference to ClassName::ClassName
I'm using Code::Blocks to build my project, which contains three files: main.cpp, TimeSeries.cpp, TimeSeries.h. TimeSeries.h provides declarations for the TimeSeries class as follows: template<class XType, class YType> class TimeSeries { public: TimeSeries(void); ~TimeSeries(void); }; Then TimeSeries.cpp conta...
The reason for splitting code into header- and source-files is so that the declaration and the implementation are separated. The compiler can translate the source-file (compilation unit) into an object file, and other compilation-units that want to use the classes and functions just include the header-file, and link th...
3,744,857
3,744,876
how to make pointer to non-member-function?
if i have for example class A which contains the functions: //this is in A.h friend const A operator+ (const A& a,const A& b); friend const A operator* (const A& a,const A& b); which is a global (for my understanding). this function implemented in A.cpp. now, i have class B which also contains the functions, and the ...
Overloaded functions are usually resolved based on the types of their arguments. When you make a pointer to a function this isn't possible so you have to use the address-of operator in a context that is unambiguous. A cast is one way to achieve this. static_cast<funcP>(&operator+)
3,744,984
3,745,092
Performance when exceptions are not thrown (C++)
I have already read a lot about C++ exceptions and what i see, that especially exceptions performance is a hard topic. I even tried to look under the g++'s hood to see how exceptions are represented in assembly. I'm a C programmer, because I prefer low level languages. Some time ago I decided to use C++ over C because ...
Please see my detailed response to a similar question here. Exception handling overhead is platform specific and depends on the OS, the compiler, and the CPU architecture you're running on. For Visual Studio, Windows, and x86, there is a cost even when exceptions are not thrown. The compiler generates additional code ...
3,745,021
3,745,036
Splitting classes out into DLLs using VS2008 C++
I've got a VS2008 C++ solution containing one project which is a Win32 console application. I have developed a few classes that I want to re-use in another project. Apart from copying the source files into new projects, what's the correct way to turn my classes into some sort of reusable component? Should I be using a ...
You say that you were spoiled that in C# you can just drop the files in the new project. You can do the same for C++. For small stuff, this is what I prefer because of the simplicity. Otherwise you have the option of a static library (.lib) or a DLL, both of which have their own sets of nuances and complications that n...
3,745,194
3,745,202
how to implement minheap using template
I need to create a minheap template which includes nodes in it. The problem I have is that I don't know if I need to create a node template class as well, or should it be included inside the heap template class as a struct?
Min heaps aren’t usually (never?) implemented using explicit nodes – since a heap is always left-filled (“complete”) and thus has a well-defined structure, that would be unnecessarily inefficient since the handling of nodes and node links introduces quite a bit of overhead, not to mention destroying locality of referen...
3,745,348
3,746,110
OpenCV Kalman filter
I have three gyroscope values, pitch, roll and yaw. I would like to add Kalman filter to get more accurate values. I found the opencv library, which implements a Kalman filter, but I can't understand it how is it really work. Could you give me any help which can help me? I didn't find any related topics on the internet...
It seems like you are giving too high values to the covariance matrices. kalman->process_noise_cov is the 'process noise covariance matrix' and it is often referred in the Kalman literature as Q. The result will be smoother with lower values. kalman->measurement_noise_cov is the 'measurement noise covariance matrix' an...
3,745,412
3,745,437
How to write a template?
i need to write a template with Nodes containing data with 2 data structures : a map and a minimum heap, both got the same nodes in it and every 2 same nodes are connected. the problem is that i need the heap to know the node fields for the heapify for example, and i don't know what's the right way to do so, friends? p...
Well, a linked list might be laid out like this: namespace my_namespace { namespace detail { template <class T> struct Node { T value; Node* previous; Node* next; //constructors and other things that might help }; } template <class T> class LinkedList { private: detail::Node<T>* head; public: ...
3,745,504
3,746,017
How to overwrite an operator inside a template
hello i am building a template in c++ ,and i need to overwrite the operator "<" inside the template for being able to compare between items inside my data structure. could anyone please tell me how to overwrite it ... should i send a pointer to a function inside the constructor of the template? I got two templates, the...
Will this do? I have purposely provided 'operator <' in the namespace scope so that it is more generic, though it is shown in comments how to do so. template<class T> struct A; template<class T, class U> // Remove U and modify accordingly, if f and s // have to be of the same type. b...
3,745,861
3,745,914
How to remove last character put to std::cout?
Is it possible on Windows without using WinAPI?
You may not remove last character. But you can get the similar effect by overwriting the last character. For that, you need to move the console cursor backwards by outputting a '\b' (backspace) character like shown below. #include<iostream> using namespace std; int main() { cout<<"Hi"; cout<<'\b'; //Cursor mov...
3,745,864
3,745,909
Opening a file from a Qt URL
I'm coding a small and basic error tracker with Qt. The whole application is in a QTable. Each error is linked to a file ; so, one of the columns of my table deals with that. I have a QLabel and a button next to it ; you click on the button to select a file, and then, the label displays the name of the file. What I'd ...
You can use html in QLabel's text, so lets use that. Then set the QLabel to automatically open the link: ui->label->setText("<a href=\"file:///C:/yourfile.doc\">Link to file</a>"); ui->label->setOpenExternalLinks(true);
3,745,919
3,745,966
inpou32.dll doesn't work on my computer
I've tried to run the following code on my PC. With PORT 0x378 (LPT1 data) it works fine. But with PORT 0x379 (LPT1 status) it always returns 126 no matter what I output in the previous line. 0x37A works too. I have Windows XP #define PORT 0x379 #define DATA 255 int main(int argc, char *argv[]) { Input input; O...
Port 0x379 is an input port. You cannot change the value it reports in software, you actually have to put a voltage on pin 10, 11, 12, 13 or 15. Respectively the Ack, *Busy, PaperOut, Select and Error signals.
3,746,012
3,746,043
c++: How to transform a map iterator which point to pair into a "regular" pair pointer
those are the maps: multimap<SortKey,T> firstMap; multimap<SearchKey,pair<SortKey,T>*> secondMap; template <class T,class SortKey, class SearchKey> bool GarageDataBase<T,SortKey,SearchKey>::Add(T data,SortKey key1, SearchKey key2) { multimap<SortKey,T>::iterator it; it=(firstMap.insert(pair<SortKey,T>(key1,data)))...
pair<SortKey,T> is not the same as multimap<SortKey,T>::value_type. The latter is pair<const SortKey,T> since the key is not supposed to change. And since pair<SortKey,T> and pair<const SortKey,T> are not reference-related but two distinct types, the compiler doesn't accept the code. If you account for the const key it...
3,746,026
3,746,332
Stubs and main program
I have to design and implement a program to accomplish drum stick matching (not the eating one). There are two parameters I have to check i.e Weight and Pitch (acoustical property) for the two different drumstick and find pair of matching drumstick. I created three classes i.e Bin, Sorter and Stick and in project descr...
I suggest you create yourself a minimal test case without most of the infrastructure, just concentrating on why the my_sorter = new Sorter(); statement fails. #include <Sorter.h> void dummy(void) { Sorter *my_sorter = new Sorter(); delete my_sorter; } Does this compile? If not, fix it. If so, complicate it: ...
3,746,067
3,746,105
C++: multiple keyed map
I am searching for a (multi)map where there values are associated by different key types. Basically what was asked here for Java but for C++. Is there something like this already or do I have to implement it myself? Another, more simple case (the above case would solve this already but there may be a more simple solut...
If you want to be able to search both by key and by value use boost.bimap. If you need multiple keys use boost.multi-index.
3,746,203
7,556,790
bayesian network library for iphone?
i m looking for a bayesian network library that work on the iphone. any tip ?
I've never used it, but there's one on Github called BayesianKit: https://github.com/lok/BayesianKit
3,746,235
3,746,469
C++ LNK2019 ( between project classes )
I have an very strange error: when I want to use the SocialServer::Client class from my SocialServer::Server class, the linker threw me two LNK2019 errors : Error 1 error LNK2019: unresolved external symbol "public: void __thiscall SocialServer::Client::Handle(void)" (?Handle@Client@SocialServer@@QAEXXZ) referenced in ...
i've found the solution. In a function that's used by _beginthreadex() (with unsigned __stdcall) , always add a return at the end.
3,746,238
3,746,390
C++ global initialization order ignores dependencies?
I think my problem is best described in code: #include <stdio.h> struct Foo; extern Foo globalFoo; struct Foo { Foo() { printf("Foo::Foo()\n"); } void add() { printf("Foo::add()\n"); } static int addToGlobal() { printf("Foo::addToGlobal() START\n"); globalFoo.ad...
On the order of initialization, read the answer here. On how to solve the initialization issue, you can push the global to be a static local variable in a function. There standard guarantees that the static local variable will be initialized in the first call to the function: class Foo { public: static Foo& singleto...
3,746,282
3,746,324
Is it possible to write one program with three programming languages?
Is it possible to make one program, written in Java, C++ and D?
So you want to write, say, a game that compiles both in Java, C++ and D ? No can do. But you can e.g. create a library (in C) with common logic and use that from Java (via JNI), C++ and D. Still, there's not much point in doing so except if you need to target platform where you don't have influence on the environment (...
3,746,335
3,746,350
C++ overloading typecast operator for pointers
I have a conversion like this: Class1 *p1; Class2 *p2 = new Class2(); p1 = (Class1 *) p2; Can I override the typecast operator above to return a custom Class1 object pointer? If yes how? EDIT: My exact problem is that I have code like this: if (*$1 == ArrayType(AnyType())) { $$ = ((ArrayType *) $1)->getElementsTyp...
No, you cannot overload conversion operators of non-class types. What is the actual problem you want to solve? You might want to consider providing conversion operators in the actual classes.
3,746,376
3,747,328
OpenGL 3.2 Core Profile Guide
Can anyone suggest a guide for learning the OpenGL 3.2 core profile? The SDK is hard to read, and most of the guides I have seen only taught the old method.
I don't know any good guide but I can make you a quick summary I'll assume that you are already familiar with the basics of shaders, vertex buffers, etc. If you don't, I suggest you read a guide about shaders first instead, because all OpenGL 3 is based on the usage of shaders On initialisation: Create and fill vertex...
3,746,377
3,746,381
C++: error "... is not derived from type ..."
template<typename T1, typename T2> class Bimap { public: class Data; typedef Data* DataP; typedef std::multimap<T1, DataP> T1Map; typedef std::multimap<T2, DataP> T2Map; class Data { private: Bimap& bimap; T1Map::iterator it1; /*...*/ }; }; This gives me this co...
make it: typename T1Map::iterator it1; http://www.parashift.com/c++-faq-lite/templates.html#faq-35.18
3,746,392
3,746,408
How to change implementation of returned object base class's function when object is returned C++
I have an existing application in C++ with a custom ArrayBase class that manages storage and access to a contiguously allocated region of memory. I have a separate ItrBase class that is used to access data in that ArrayBase. ArrayBase has a createItr() function that currently returns an ItrBase object. I need to exte...
Sure, if you're allowed to rewrite ItrBase, then you can use delegation to pass all function calls through to an implementation class, which you hold by pointer or reference so that polymorphism is in effect. This would look a lot like pimpl. And the callers would not have to be written at all, only recompiled. EDIT:...
3,746,419
3,746,433
C++: error "explicit specialization in non-namespace scope"
template<typename T1, typename T2> class Bimap { public: class Data { private: template<typename T> Data& set(T); template<> Data& set<T1>(typename T1 v) { /*...*/ } }; }; That gives me the error: error: explicit specialization in non-namespace scope 'class Bimap<T1, T2>::Data' I understand...
One way forget templates, overload: Data& set(T1 v) { /*...*/ } but here is a trick which I use sometimes you can specialize class template within class: class { template<typename T> struct function_ { static void apply(T); }; template<> struct function_<int> { ... }; temp...
3,746,462
3,746,483
how to Override operator <
I'm trying to override operator < as the following : inside Node : bool operator <(const Node* other) { return *(this->GetData()) < *(other->GetData()); } inside vehicle : bool operator <(const Vehicle &other) { return this->GetKilometersLeft() < other.GetKilometersLeft(); } invoking the operator : while (inde...
this is because you are comparing pointers, You have to make it: *m_heapVector[index] < *m_heapVector[parent(index)] and adjust operator accordingly bool operator<(const Node &other) const;
3,746,484
3,746,500
Why am I getting this redefinition of class error?
Apologies for the code dump: gameObject.cpp: #include "gameObject.h" class gameObject { private: int x; int y; public: gameObject() { x = 0; y = 0; } gameObject(int inx, int iny) { x = inx; y = iny; } ~gameObject() { // } int add() ...
You're defining the class in the header file, include the header file into a *.cpp file and define the class a second time because the first definition is dragged into the translation unit by the header file. But only one gameObject class definition is allowed per translation unit. You actually don't need to define the...
3,746,532
3,746,549
Local class template
We can have a local class defined inside a function but this class cannot be a template which is bit annoying and inconsistent. Is there any update on that in C++0x standard?
Yes. Actually this rule change is what makes Lambda expressions possible since a Lambda expression creates a local unnamed type. Sorry, I misread your question. I thought you were talking about using a local class as template parameter. This wasn't allowed in C++98 and C++03 but it will work in C++0x. As for your actua...
3,746,703
3,746,821
concurrent queue in C++
I am trying to design a queue which could be simultaneously accessed by multiple read/write threads. I prefer using 2 mutexes, one apiece for read and write. Doing write is simple enough, lock the write mutex, append data, unlock and you are done. The issue is with read. If there's no data in the in queue I'd like my ...
Example 12-3 of this C++ threading blog post should give you a reference implementation, but I think you're dangerously close to success on your own. Addressing your specific concerns: It is not illegal to signal when there are no waiters. It's totally legitimate, and you can leverage that fact. (Where did you read th...
3,746,728
3,746,744
C++: using function pointers as template arguments
I have the following code: template<typename Parent, typename T, void (Parent::*Setter)(T), T (Parent::*Getter)()> struct Property { Parent& obj; Property(Parent& _obj) : obj(_obj) {} Property& operator=(T v) { (obj.*Setter)(v); return *this; } operator T() { return (obj.*Getter)(); } }; template<typename T1, type...
You want Property<Entry, T1, &Entry::set1, &Entry::get1>
3,746,742
3,746,763
Trying to count instances of deriving classes, type_id doesn't work
I want to count all the instances of derivers from my class, I'm trying to do it like so: .h file: #ifndef _Parant #define _Parant #include<map> class Parant { public: Parant(); virtual ~Parant(); static void PrintInstances(); private: static void AddInstance(const char* typeName); static std::ma...
typeid(*this) in a constructor just yields the constructor's class (you had it typeid(this) but that's wrong anyway since it will just give you the type_info of a pointer). That's considered the dynamic type of the object during construction. Another difference there is that virtual functions called during construction...
3,746,811
3,746,847
copy smaller array into larger array
I have two arrays of chars, allocated as follows: unsigned char *arr1 = (unsigned char *)malloc((1024*1024) * sizeof(char)); unsigned char *arr2 = (unsigned char *)malloc((768*768) * sizeof(char)); I would like to copy arr2 into arr1, but preserve the row/column structure. This means that only the first 768 bytes o...
maybe get rid of the multiplications size_t bigindex = 0, smallindex = 0; for (int x = 0; x < 768; x++) //copy each row { memcpy(arr1 + bigindex, arr2 + smallindex, nc); bigindex += 1024; smallindex += 768; } Edit d'oh! use the pointers! unsigned char *a1 = arr1; unsigned char *a2 = arr2; for (int x = 0; ...
3,746,822
3,746,877
why use virtual destructor in inheritance
Possible Duplicate: When to use virtual destructors? let's say i have an abstract class Animal class Animal { public: Animal(const std::string &name) : _name(name) { } virtual void Print() const = 0; virtual ~Animal() {} protected: std::string _name; }; and i have Dog and Cat that inherit th...
When you have something like this: class Dog : public Animal { public: Dog() { data = new char[100000]; } ~Dog() { delete data; } private: char* data; }; Animal* dog = new Dog; delete dog; Without virtual destructor, compiler use destructor from Animal class. And memory allocated in Dog cl...
3,746,970
3,747,024
Initializing 2 dimensional array of structs in C++
I am trying to initialize a 2D array of structs in C++, but am getting an error. Can someone please tell me what am I doing wrong? I have rechecked the braces and they seem to be fine. My code: struct CornerRotationInfo { bool does_breed; int breed_slope; bool self_inversion; int self_slope; inline CornerRot...
When you are trying to use aggregate initializer to initialize an array of objects with used-declared constructor, the syntax you can use depends significantly on how many parameters the individual element's constructor has. If the constructor has (read: accepts) only one parameter, you can use "normal" aggregate init...
3,747,014
3,747,048
Changing the current directory in Linux using C++
I have the following code: #include <iostream> #include <string> #include <unistd.h> using namespace std; int main() { // Variables string sDirectory; // Ask the user for a directory to move into cout << "Please enter a directory..." << endl; cin >> sDirectory; cin.get(); // Navigate to ...
int chdir(sDirectory); isn't the correct syntax to call the chdir function. It is a declaration of an int called chdir with an invalid string initializer (`sDirectory). To call the function you just have to do: chdir(sDirectory.c_str()); Note that chdir takes a const char*, not a std::string so you have to use .c_str(...
3,747,066
3,749,251
C++ cannot convert from base A to derived type B via virtual base A
I have four classes: class A {}; class B : virtual public A {}; class C : virtual public A {}; class D: public B, public C {}; Attempting a static cast from A* to B* I get the below error: cannot convert from base A to derived type B via virtual base A
In order to understand the cast system, you need to dive into the object model. The classic representation of a simple hierarchy model is containment: if B derives from A then the B object will, in fact, contain an A subobject alongside its own attributes. With this model downcasting is a simple pointer manipulation by...
3,747,147
3,747,190
How to specify a preprocessor directive in eclipse?
How are preprocessor directives specified in eclipse for different configurations? For instance if I have multiple mains that should be run in different configurations and specify #ifdef Problem1 //main func #endif /*Problem1*/ Note that this is with managed makefiles
The documentation points to "C/C++ Project Properties" → "Paths and Symbols" → "Symbols". However, usually it is better to use different source files for different configurations/architectures/... instead of extensive preprocessor usage.
3,747,308
3,747,333
drawing a simple triangle with a while loop
Back learning after silly life issues derailed me! I decided to switch my learning material and I'm now working through Accelerated C++. Chapter 2, Exercise 5: Write a set of "*" characters so that they form a square, a rectangle, and a triangle. I tried but just couldn't get the triangle down exactly. A quick google ...
In the nested while loop, inside the else clause: else { if (col == height + row) cout << '*'; // This draws the right side else cout << ' '; } The trick is that the while loop doesn't quit until the column reaches height + row, which is the position of the right side. It prints the left side ...
3,747,408
3,747,418
C++ program to count number of objects in a particular Linux directory
I'm attempting to write a program in Linux using C++ that counts the number of files and folders in a user specified directory, but the more I read, the more confused I get. I'm new to C++ and to programming in general, and I understand that I have a big hurdle to vault at the start, but I'm not entirely sure where to ...
With C++ Boost.FileSystem gives you convenient tools to achieve what you want. If you want to learn the basic C APIs, take a look at File System Interface in the GNU C library manual.
3,747,508
3,747,548
c++. compile error. am trying to add friend template function with enum template parameter
Please help with the next code: typedef enum {a1, a2, a3} E; template<E e> int foo() { return static_cast<int>(e); } class A { A() {}; friend int foo<E e>(); }; The compiler says: error C2146: syntax erorr: missing "," before identifier "e" I would be glad if someone could explain my mistake. Thanks.
If you want class A to befriend the function template foo(), you need to use: template <E> friend int foo(); You can also befriend a particular instantiation of the function template foo(): friend int foo<a1>();
3,747,528
3,747,535
What does const denote here?
What does const denote in the following C++ code? What is the equivalent of this in C#? I code in C# and I am trying to learn C++. template <class T> class MaximumPQ { public: virtual ~MaximumPQ () {} virtual bool IsEmpty () const = 0; virtual void Push(const T&) = 0; virtual void Pop () = 0; };
The first one informs the compiler that the method will not change any member variables of the object it is called on, and will also only make calls to other const methods. Basically, it guarantees that the method is side-effect free. The second one specifies that the object referred to by the passed reference will not...
3,747,691
3,747,706
std::vector iterator invalidation
There have been a few questions regarding this issue before; my understanding is that calling std::vector::erase will only invalidate iterators which are at a position after the erased element. However, after erasing an element, is the iterator at that position still valid (provided, of course, that it doesn't point t...
after erasing an element, is the iterator at that position still valid No; all of the iterators at or after the iterator(s) passed to erase are invalidated. However, erase returns a new iterator that points to the element immediately after the element(s) that were erased (or to the end if there is no such element). ...
3,747,938
3,747,951
Confusion over C++ pointer and reference topic
What is the difference between the following parameter passing mechanisms in C++? void foo(int &x) void foo(int *x) void foo(int **x) void foo(int *&x) I'd like to know in which case the parameter is being passed by value or passed by reference.
void foo(int &x) passes a reference to an integer. This is an input/output parameter and can be used like a regular integer in the function. Value gets passed back to the caller. void food(int *x) passes a pointer to an integer. This is an input/output parameter but it's used like a pointer and has to be derefere...
3,748,127
3,748,177
How to get information about network adapters in c++?
How to get information about all network adapters in system? Name, Manufacturer, Location(PCI, slot2), Driver Version. Actually i retrieved Name and Manufacturer with WMI but i can't find Location and Driver version. I need only c++ solutions not MFC/clr. winapi function? wmi (missing something)? Also i need to retrie...
In reference to your second request: 'i need to retrieve .NET version on system' This can be done via the Unmanaged Hosting API. If you are using .NET 4.0 then you can use the new ICLRMetaHost interface. The EnumerateInstalledRuntimes() function will give you all currently installed .NET runtimes. You could also do t...
3,748,159
3,748,167
Is it OK to use C++ for business and Objective-C for presentation?
We have a program developed for Windows, the business layer is in pure C++ without any Windows related stuff(e.g CString) and we plan to migrate it to IPhone. What I'm thinking is that we can use the exisiting code (with little changes if needed) and use Object-C to develop a UI. Is this idea possible? Best regards, Za...
Oh yes, this is entirely possible. You'd be using Objective-C++, which is merely a different file extension. (You'd save your .cpp files as .mm files).
3,748,415
3,748,523
QAbstractItemModel for QMetaObject, do I have to write it myself?
A suite of data models built on top of Qt's reflection system seems like a natural synergy, but I haven't found such a beast in the Qt library itself or from a 3rd party. Does anyone know if such a thing exists? I'm look for data models for editing and displaying a collection of QObjects QMetaObject properties. I can k...
If you are representing a tree of QObjects then QStandardItemModel will probably suit your needs. If not, you would probably subclass that instead of QAbstractItemModel.
3,748,439
3,748,468
error: expected unqualified-id before ‘public’
I have read a few posts but cannot figure out what is wrong.My Code is a s follows #include <iostream> using namespace std; /* compiles with command line gcc xlibtest2.c -lX11 -lm -L/usr/X11R6/lib */ #include <X11/Xlib.h> #include <X11/Xutil.h> #include <X11/Xos.h> #include <X11/Xatom.h> #include <stdio....
Change your Java like syntax to : class Point //access modifiers cannot be applied to classes while defining them { int x; int y; public : //Note a colon here Point() :x(),y() //member initialization list { //`this` is not a reference in C++ } }; //Notice the semicolon ...
3,748,511
3,748,541
How to debug uninitialized variables in VC++
How to debug uninitialized variables in release mode in C++.
Uninitialized variables are a nasty bug to find. Some static checkers would probably be able to find your uninitialized variable. There are open source ones. You might be able to get a trial version of commercial version as well.
3,748,606
3,748,644
Where are all the esoteric collection template libraries?
Edit: What I'm really thinking of is a C++ equivalent to the Contrib libraries other languages enjoy, like CPAN/PyPI/Ruby Gems Suppose I want a collection type that isn't really supported by anything in the STL or by BOOST, like a spacial index or a fibonacci tree (if i think that might be useful on my really big datas...
Sometimes Vault has useful things. maybe you can find something there.
3,748,749
3,748,776
Rounding off floats with ostringstream
I have an issue regarding conversion from float to c++ string using ostringstream. Here is my line: void doSomething(float t) { ostringstream stream; stream << t; cout << stream.str(); } when t has value -0.89999 it is round off to -0.9, but when it's value is 0.0999 or lesser than this say 1.754e-7, it j...
You need to set the precision for ostringstream using precision e.g stream.precision(3); stream<<fixed; // for fixed point notation //cout.precision(3); // display only stream << t; cout<<stream.str();
3,748,823
3,748,868
C++ static initialization
what should be the behavior in the following case: class C { boost::mutex mutex_; std::map<...> data_; }; C& get() { static C c; return c; } int main() { get(); // is compiler free to optimize out the call? .... } is compiler allowed to optimize out the call to get()? the idea was to touch s...
The C and C++ standards operate under a rather simple principle generally known as the "as-if rule" -- basically, that the compiler is free to do almost anything as long as no conforming code can discern the difference between what it did and what was officially required. I don't see a way for conforming code to discer...
3,748,936
3,751,192
Creating RightClick Menu for Explorer
If some one can provide some sample articles on how to create Right Click Menu for Drives. Here is what needed: The right click menu will contain two additional things, i.e: Connect and Disconnect. Can we make it conditional? I mean for some condition The drive will make the Connect enabled(Ideally when not connected) ...
Here is all the relevant documentation. Basically you want to create a COM object that implements IShellExtInit and IContextMenu. To register it for drives you would add an entry for it under HKEY_CLASSES_ROOT\Drive. If the MSDN documentation is a bit dense there is a detailed walkthrough on CodeProject.
3,749,098
3,810,206
Query regarding overflow function of streambuf
Going thorugh overflow function documentation. I found overflow has following as return values. Return Value: A value different than EOF (or traits::eof() for other traits) signals success. If the function fails, either EOF (or traits::eof() for other traits) is returned or an exception is thrown. source :"http://www.c...
In my problematic scenario it was faling because it was not jumping the next address(setp calls was incrementating by 0) so retrying to use the same memory region and was giving segmentation fault.
3,749,099
3,749,115
Why should the implementation and the declaration of a template class be in the same header file?
Why should the implementation and the declaration of a template class be in the same header file? Could any of you explain it by example?
The compiler needs to have access to the entire template definition (not just the signature) in order to generate code for each instantiation of the template, so you need to move the definitions of the functions to your header. For more details read about The Inclusion Model.
3,749,196
3,749,242
Templates :Name resolution -->can any one tell an other example for this statement...please
This is the statement from ISO C++ Standard 14.6/8: When looking for the declaration of a name used in a template definition, the usual lookup rules are used for nondependent names. The lookup of names dependent on the template parameters is postponed until the actual template argument is known (14.6.2). Example: ...
Looking only at the template, can you tell me what the type of p[i] is? No. The type of p[i] in Set<int> will be int ; the type of p[i] in Set<std::string> will be std::string. Hence, the lookup of operator<< has to be delayed until the template is instantiated and the type of p[i] is known. You'd have a similar issue ...
3,749,233
3,749,293
An efficient data structure to hold structure variable with sorting capability
I have a structure struct dbdetails { int id; string val; }; I need a data structure in C++ that can hold structure variable with a sort capability. Is it possible? I was looking at vector, which can hold structure variable, but I will not be able to sort it based on id, because it is a structure member. Any ...
You need a custom functor for comparing your tries. This should do the trick: #include <algorithm> #include <vector> // try is a keyword. renamed struct sorthelper : public std::binary_function<try_, try_, bool> { inline bool operator()(const try_& left, const try_& right) { return left.id < right.id; } }; ...
3,749,303
3,751,986
Qt Drag&Drop with own widgets?
I created a little widget on my own, including a QProgressBar and a QLabel in a QVBoxLayout. It has also a function which returns the text of the label (self-created). Now in my MainWindow I have two other QHBoxLayouts and I want to drag and drop my widget from one to another. It also works when I click on the little f...
QWidget::childAt(int,int) returns the child widget, not the parent widget. In your case, it returns the QProgressBar. You then try to cast into a MyWidget, which it is not. What you are looking for is for the parent of the QProgressBar (or QLabel). static_cast does not verify the type of the object you are trying to ca...
3,749,390
3,749,553
Unable to link afx_msg in BEGIN_MESSAGE_MAP
I'm trying to hook into the OnSysCommand function but I'm getting a confusing error. In the header, I am declaring the function like: afx_msg void OnSysCommand(UINT nID, LPARAM lParam ); And in the cpp the code is: BEGIN_MESSAGE_MAP(CMFCTest1App, CWinAppEx) ON_COMMAND(ID_APP_ABOUT, &CMFCTest1App::OnAppAbout) // Stan...
Move the handlers out of your app class and into your window or frame class. These messages are meant to be handled in a window class (derived from CWnd) and not in your app class (derived from CWinApp).
3,749,660
3,749,667
How to resize array in C++?
I need to do the equivalent of the following C# code in C++ Array.Resize(ref A, A.Length - 1); How to achieve this in C++?
The size of an array is static in C++. You cannot dynamically resize it. That's what std::vector is for: std::vector<int> v; // size of the vector starts at 0 v.push_back(10); // v now has 1 element v.push_back(20); // v now has 2 elements v.push_back(30); // v now has 3 elements v.pop_back(); // removes the 30 and ...
3,749,668
3,749,733
How to query the thread count of a process using the regular Windows C/C++ APIs
Is there a way to query the number of threads that are currently running for a specific process using the standard Windows C/C++ APIs? I already prowled through the MSDN docs but the only thing that comes near is BOOL WINAPI GetProcessHandleCount( __in HANDLE hProcess, __inout PDWORD pdwHandleCount ); which q...
See this example: http://msdn.microsoft.com/en-us/library/ms686852(v=VS.85).aspx
3,749,782
3,749,822
C++ Failure on MSVCR80.dll using Microsoft.SqlServer.Management
I am trying to run test on my server but it fails due to some C++ error coming from MSVCR80.dll. On my machine it runs smoothly but on the server, I do not find a way to make it work. Here is the error I have when running my tests (sorry it is in italian but it could be easily understood, I guess, everybody speaks ital...
Instead of just downloading a single DLL (possibly missing other dependencies), have you tried downloading and installing the Microsoft Visual C++ 2005 SP1 Redistributable? Edit, as for running your solution in Visual Studio: Well, the error location was pretty much already obvious, given the stack trace. Since this is...
3,750,085
3,750,642
How to define an iterator in a template?
I'm trying to define an iterator to iterate my map to erase it (destructor) I'm getting an error : incompatible iterator. My destructor looks like this : Consortium<S,T>::~Consortium() { map<const S, Node<T>*>::iterator deleteIterator; for (m_consortiumMap.begin() ; deleteIterator != m_consortiumMap.e...
Your immediate problem is that map<const S, Node<T>*>::iterator is a so-called dependent name: it is depends on the template arguments and, in theory, there could be a specialization of std::map for some S, T which defines iterator to be a static data member, the name of a member function or whatever. What it is, the c...
3,750,160
3,750,353
Programmatically extracting .deb packages
I have .deb package whose contents I need to extract in a programmatic way. However, I am not able to find any resources on the topic, such as .deb package format specification, which would give me some more idea how to approach the problem without going and reverse engineering the whole thing. Any ideas?
If you don't find a library for this (I didn't, either), and cannot resort to running system commands, you can always implement your own to read ar archives. The ar file format isn't terribly complicated.
3,750,177
3,754,908
Which State Machine execution frameworks for C++ implement UML semantics?
I'm looking for a framework that provides execution of hierarchical state machines (HSMs). These are the requirements for the framework: Conforms to UML state machine semantics (as much as possible) Supports at least run-to-completion semantics hierarchical states entry and exit actions transition actions guards eve...
Check out the Quantum Platform. I've used it on several embedded projects (from very tiny to very large), and it supports all of the bullet items you require, and more. The web page for the QP does a much better job of explaining itself than I can do here. Be aware, the QP does not implement 100% of the functionality s...
3,750,200
3,750,211
C++ cannot instantiate abstract class
I am new to C++. Could you pls help me get rid of the errors: error C2259: 'MinHeap' : cannot instantiate abstract class IntelliSense: return type is not identical to nor covariant with return type "const int &" of overridden virtual function function template <class T> class DataStructure { public: virtua...
The problem is with const T& Top() vs. int Top(). The latter is different from the former, and thus not an override. Instead it hides the base class function. You need to return exactly the same as in the base class version: const int& Top() const. The same problem exists for Push(), BTW.
3,750,475
3,750,647
Exporting member function of a static library
Is it possible (or relevant at all) to export member functions of a static library? When I "dumpbin /EXPORTS" my .lib file I don't see any of my defined class members. Linking to this lib file succeeds, but I use an external tool that fails to read non-exported symbols. Also tried adding a .def file with no results.
A static library is just a collection of .o files. This is then linked into your executable in exactly the same way as .o files so whatever works for .o files will work for static libraries.
3,750,483
3,750,511
Indexing: Implementing Tree data structures with Arrays/Vectors
I have been implementing a heap in C++ using a vector. Since I have to access the children of a node (2n, 2n+1) easily, I had to start at index 1. Is it the right way? As per my implementation, there is always a dummy element at zeroth location.
Your way works. Alternatively you can have root at index 0 and have children at 2n+1 and 2n+2
3,750,671
3,750,796
How to treat a double 3.14567 as a 3.14 (i.e with a given percision)
I was wondering if there is any way in c++ to treat a double with a given precision. for example, the number 3.1345 will be considered as 3.13 and the number 0.009 will be considered as 0 (precision of 2 after the dot). I need that it will be applied on mathematical operations. for example: double a = 0.009; double b =...
The easiest way: int a100 = int(a*100); int b100 = int(b*100); int c100 = a100 * b100; // Will be 0 int d100 = a100 + b100; // Will be 312
3,750,727
3,750,808
How to erase the last n elements in the C++ map?
Is there a nice and simple way to find nth element in C++ std::map? Particularly I'm looking for an algorithm to erase the last k elements from the map. That would make sense to retrieve the iterator to the nth element and call std::map::erase. The requirement is that complexity doesn't suffer - that should be possible...
Maps don't provide better-than-linear access to elements by index, like vector or deque. You can do this using std::advance, but it takes time that is proportional to k. If k is small, it will often be fast enough - it basically involves following k pointers. Here's an example: template<typename Map> void erase_last_el...
3,750,831
3,750,901
How to include all source files from a folder?
I have put each function in own file. How do I include all those functions at once without repeating #include for each file manually? I don't care at which order the functions are included. All the functions from hundreds of different files belongs to the same group. Actually each file has 4 functions.
You add all the files containing the function definitions (function bodies) to your project You write one header file that contains a declaration for your functions. You include that header where needed.
3,750,911
3,751,562
MFC Controls are getting disappeared after scrolling
I am working on dialog based MFC application in WinCE. I created few controls in a dialog and scrolled down. When i scroll up again, the controls in the first screen got disappeared. Controls getting created in OnInitDialog() like below at coordinates (50,10) test->Create(_T("Title"), WS_CHILD|WS_VISIBLE, CRect(50,10,...
I have the following code that works fine. I hope it will help you. LRESULT CMyWindow::OnVScroll( UINT code, UINT position ) { SCROLLINFO info = { sizeof( SCROLLINFO ), SIF_ALL }; GetScrollInfo( m_wnd, SB_VERT, &info ); int previous_pos = info.nPos; switch( code ) { case SB_TOP: info.nPo...
3,751,178
3,751,347
Flickering while redrawing in MFC
I'm writing a tetris game using C++ and MFC. I have a timer and OnTimer handler. Handler looks like this: ... do some game-only logic ... this->RedrawWindow(); And in OnPaint handler I draw blocks, map(with bitmap background), score etc. For drawing i use bitmaps and BitBlt function. Everything is drawn from scratch, ...
Try Double Buffering. “Double buffering” refers to the technique of writing into a memory DC and then BitBlt-ing the memory DC to the screen. In connection with Windows, this technique can be used to handle WM_PAINT messages. Your OnDraw function calls BitBlt to copy the memory DC into the screen DC. The memory DC is ...
3,751,274
3,751,309
ADO and exception handling
I have the following function that was written by someone else, however I am rewriting this application and I was just wondering if there isn't any better way to do exception handling, besides just returning what was originally passed to the function? CComVariant GetFldVar(ADO_RsPtr rs, long nIndex, CComVariant def) { ...
Def appears to be the default, i.e. the function tries to get column n out of the current row (rs) and if it fails, it returns the default. I don't think this is an error rather a particular use case. It's a fairly stanard pattern to allow the caller to avoid checking for missing values esp. from the db, and to specif...
3,751,331
3,751,396
matrix operations on large matrices on limited memory
I need to do some matrix operations on my computer. These matrices are large 1000000x1000000 and more, some operations requiring TB of memory. Obviously these cannot be directly loaded into memory and computed. What approaches can I use to solve these matrices on my computer? Assuming that the matrices cannot be reduce...
Two suggestions: Use the mmap2 system call to map the files containing both the input and output data. This allows you to map files up to 2^44 bytes and treat them as if they were already in memory. I.e. you just use a standard pointer syntax to access the data and the OS takes care of either reading or writing it fr...
3,751,357
3,751,677
C++: How to create an array using boost::property_tree?
I don't see a way to create an array using boost::property tree. The following code ... #include <boost/property_tree/ptree.hpp> #include <boost/property_tree/json_parser.hpp> #include <iostream> int main() { try { boost::property_tree::ptree props; props.push_back(std::make_pair("foo", "bar")); props.p...
If you have a sub-tree whose only nodes have empty keys, then it will be serialized as an array: boost::property_tree::ptree array; array.push_back(std::make_pair("", "bar")); array.push_back(std::make_pair("", "baz")); boost::property_tree::ptree props; props.push_back(std::make_pair("array", array)); boost::propert...
3,751,387
3,751,426
What is wrong with this boost c++ regex code?
include #include <fstream> #include <string> #include<string> #include<boost/algorithm/string.hpp> #include<boost/regex.hpp> #include <boost/algorithm/string/trim.hpp> using namespace std; using namespace boost; int main() { string robotsfile="User-Agent: *" "Disallow: /"; regex exrp( "^Disallow...
string robotsfile = "User-Agent: *" "Disallow: /"; The string literals above are merged into "User-Agent: *Disallow: /" and there is no newline as you might have thought. Since your regular expression states that string must start with "Disallow" word, it does not match. The logically correct code would be somethi...
3,751,522
3,751,648
C++, workaround for macro using 'this' in static member functions
I've overridden new so that I can track memory allocations. Additional parameters such as __FILE__, __LINE__, module name etc are added in the #define. However I want to add the address of the calling object to the parameters so that I can backtrack up allocations when hunting down problems. The easiest way is to add '...
You definitely cannot determine if a #define macro is inside a static method or not. You even shouldn't be using #define new as it violates the standard (even though all compilers support it). Your macro will also cause trouble to those who want to overload operator new for their class. Generally, I would suggest not u...
3,751,768
3,751,936
how should to implement correctly a constructor of a class with stls inside
hey I i am writing a Program in C++ and for some reason the compiler finds errors , and cant find my constructor: here is my class: (inside a h file) class Adjutancy { private: vector<Vehicale*,CompareCatId>* m_vehicalesVector; map<const string,Base*>* m_baseMap; map<const int,City*>* m_citiesMap; vector<vector<Dis...
I suppose you mean this setup: // file adjutancy.h // ... includes for all classes used below // forward declarations are OK for pointers and references class Adjutancy { public: Adjutancy(vector<Vehicale*,CompareCatId>* vehicalesVector , map<const string,Base*>* baseMap , map<const int,City*>* citiesMap , vector<v...
3,751,797
3,751,937
Can I call memcpy() and memmove() with "number of bytes" set to zero?
Do I need to treat cases when I actully have nothing to move/copy with memmove()/memcpy() as edge cases int numberOfBytes = ... if( numberOfBytes != 0 ) { memmove( dest, source, numberOfBytes ); } or should I just call the function without checking int numberOfBytes = ... memmove( dest, source, numberOfBytes ); I...
From the C99 standard (7.21.1/2): Where an argument declared as size_t n specifies the length of the array for a function, n can have the value zero on a call to that function. Unless explicitly stated otherwise in the description of a particular function in this subclause, pointer arguments on such a call shall...
3,752,019
3,752,089
How to get the index of a value in a vector using for_each?
I have the following code (compiler: MSVC++ 10): std::vector<float> data; data.push_back(1.0f); data.push_back(1.0f); data.push_back(2.0f); // lambda expression std::for_each(data.begin(), data.end(), [](int value) { // Can I get here index of the value too? }); What I want in the above code snippet is to get th...
I don't think you can capture the index, but you can use an outer variable to do the indexing, capturing it into the lambda: int j = 0; std::for_each(data.begin(), data.end(), [&j](float const& value) { j++; }); std::cout << j << std::endl; This prints 3, as expected, and j holds the value of the index. If...
3,752,251
3,752,281
problems using a class template
i created a template that contains a map. when i try to create an instance of that template i encounter a linking problem with the constructor and destructor. also, when i try to create an instance in main it skips the line while debugging, and doesn't even show it in the locals list. it doesn't compile "DataBase db;" ...
Add the implementation of template classes (and functions) directly in the header file: template <class keyVal,class searchVal, class T> class DataBase { private: map<keyVal,pair<searchVal,T*>*> DB; public : DataBase() {}; virtual ~DataBase() {}; };
3,752,374
3,753,523
how commenting the following lines of code, can change the behviour of the previous ones?
NOTE: I do believe that this is not an openCV related problem but since the error occurred using this library it might be a point of interest. In the following code, by giving the wrong parameter as cascade_name, the load function throws an exception which is expected. The interesting point is that by commenting the tw...
It depends on the circumstances/assumptions about the program in general: it's possible, given the right set of circumstances. For example: You are running this function from multiple threads, and inside the openCV library the FileStorage object interacts (shares variables, etc.) with the CascadeClassifier object. The ...
3,752,409
3,752,448
how to define a vector with a functor
hey, i implemented the following functor: struct CompareCatId : public std::binary_function<Vehicle*, Vehicle*, bool> { bool operator()(Vehicle* x, Vehicle* y) const { if(x->GetVehicleType() > y->GetVehicleType()) return true; else if (x->GetVehicleType() == y->GetVehicleType() &&...
vector does not take a functor, so you can't. vector has two template parameters: the type of object to be stored and the allocator to be used (the allocator is optional; by default it will use std::allocator<T>). The ordered associative containers (e.g., map and set) allow you to specify a comparison function becau...
3,752,425
3,752,509
Show Windows Users Dialog
How do you (programatically) show the windows local users/groups dialog? In Vista it's usually under Control Panel - Administrative Tools - Computer Management - Local Users and Groups. Similar kind of dialog with the same functionalities (add/remove users/groups) is also acceptable, as long as supported by Windows Xp ...
Seems like you are looking for lusrmgr.msc applet. You can execute it from command line, Delphi code example: uses ShellAPI; procedure TForm1.Button1Click(Sender: TObject); begin ShellExecute(Handle, 'open', 'lusrmgr.msc', nil, nil, SW_SHOWNORMAL) ; end;
3,752,444
3,752,681
QByteArray to char*, sending with libcurl
I'm having trouble with saving a QPixmap to QByteArray, then writing it to char*. For example i'm trying to write to a file with ofstream. QByteArray bytes; QBuffer buff(&bytes); buff.open(QIODevice::ReadOnly); pixmap.save(&buff, "PNG"); ...
You encounter a null-byte. You'll need something like write(), because the << operator doesn't allow you to tell how long the string is and stops writing at the first null byte: const QByteArray array = str.toAscii(); myfile.write(array.constData(), array.size());
3,752,473
3,752,544
Strong guarantee method calling strong guarantee methods
When I have a method that calls a set of methods that offer strong guarantee, I often have a problem on rolling back changes in order to also have a strong guarantee method too. Let's use an example: // Would like this to offer strong guarantee void MacroMethod() throw(...) { int i = 0; try { for(i = 0; i < 1...
A good pattern to try to achieve this is to make your method work on a copy of the object that you want to modify. When all modifications are done, you swap the objects (swap should be guaranteed not to throw). This only makes sense if copy and swap can be implemented efficiently. This method has the advantage that you...
3,752,638
3,752,914
C++ matrix-vector multiplication
When working with 3d graphics, sample shaders USUALLY use the following operation for vector position transformation: result = mul(matrix, vector); This obviously means the same as: result = mul(vector, matrix_transposed); Also, just to mention, most linear algebra libraries prefer to only leave the vector * matrix m...
The convention in mathematics (and thus in programming) is that you multiply the vector by a linear transformation from the right: matrix * vector == transformed vector. So I don't understand you complain. The matrix is already set to the right one. If you want to multiply the vector from the left then you need to tran...
3,752,742
3,753,182
How do I create a pause/wait function using Qt?
I'm playing around with Qt, and I want to create a simple pause between two commands. However it won't seem to let me use Sleep(int mili);, and I can't find any obvious wait functions. I am basically just making a console application to test some class code which will later be included in a proper Qt GUI, so for now I'...
This previous question mentions using qSleep() which is in the QtTest module. To avoid the overhead linking in the QtTest module, looking at the source for that function you could just make your own copy and call it. It uses defines to call either Windows Sleep() or Linux nanosleep(). #ifdef Q_OS_WIN #include <windows....
3,753,005
3,753,064
How to put NULL in all cells of a matrix vector?
i'm trying to initialize all cells of a matrix with NULL values, but something is wrong here. the code : vector<vector<Distance*> > distanceMatrix; for (int i = 0; i < 7 ; i++) for (int j = 0; j < 7 ; j++) distanceMatrix[i][j].push_back(NULL); i bet it's something stupid, thanks for the h...
From the std::vector reference page: Vectors can be constructed with some values in them. You may try: vector<vector<Distance*> > distanceMatrix(7, vector<Distance*>(7, NULL)); Also, regarding your problem: vector<vector<Distance*> > distanceMatrix; for (int i = 0; i < 7 ; i++) for (int j = 0; j < 7 ; j...