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
7,831,539
7,831,553
Strange rounding of numbers when reading in from text file C++
I have a text line containing only the following lines. 0.01180994648909809 0.0118339243907452 0.01153905217670122 0.0376759911531237 0.03771224865527065 0.03765957194275842 I used the following code to read this data and output it to terminal using namespace std; int main(int argc, char *argv[]) { i...
EDIT: Moving the proposed solution at top of the relevant information. You can use set::precision to see the proper precision. Apart from the answer above, It is important to note that Whenever, You use float and decimal numbers Rounding Errors & Precision are an definite factor. What is an Precision Error? The preci...
7,831,546
7,832,331
Comparing two values of different types
I have an if statement with two data types that I am comparing with each other. rowCount3 is a SQLINTEGER and chval1[128] is a SQLCHAR. I've tried several different typecasts; none succeeded. I've tried: if((SQLCHAR)rowcount3 >= (SQLCHAR)chval1) This only works sometimes. When I do a printf() to check the return val...
Both types are defined as following in <sqltypes.h> typedef int SQLINTEGER; typedef unsigned char SQLCHAR; If you have defined your variables like: SQLINTEGER rowCount3; SQLCHAR chval1[128]; are incompatible types. You must use a conversion like a normal atoi() conversion like this and compare: int var ...
7,831,568
8,378,576
rendering SDL_TTF text onto openGL Red Square instead of text
I've been attempting to render text onto an openGL window using SDL and the SDL_TTF library on windows XP, VS2010. Versions: SDL version 1.2.14 SDL TTF devel 1.2.10 openGL (version is at least 2-3 years old). I have successfully created an openGL window using SDL / SDL_image and can render lines / polygons onto it with...
I think the problem is in the glEnable(GL_TEXTURE_2D) and glDisable(GL_TEXTURE_2D) functions which must be called every time the text is painted on the screen.And maybe also the color conversion between the SDL and GL surface is not right. I have combined create_texture and drawText into a single function that displays...
7,831,753
7,832,656
How to signal an event to several threads
How can I send an event to several running threads of my application? For example: My main thread wants to signal all running threads that the application will exit. I'm a little confused which of those possibilities leads to an easy and reliable solution: condition_variable with notify_all from boost CONDITION_VARIAB...
Given you want to "signal all running threads that the application will exit" a manual reset even would do the trick. You need to have each thread check the event occasionally and exit if the event has been signalled. You then simply signal the event and wait for the threads to complete if you need to. It's more compl...
7,831,994
7,832,045
What's the restriction on distance between pointers of certain type in C++?
Suppose I have two pointers to type T: T* first = ...// whatever T* second = ... //whatever else Can I be sure that the distance between those two pointers can never exceed: ((size_t)(-1))/sizeof(T)?
You can only compute the distance between two pointers (subtract one pointer from another) if both pointers point to elements in the same array, or to one-past-the-end of the same array. If the two pointers meet that constraint, then yes, the absolute value of the difference between the two pointers cannot exceed ((siz...
7,832,175
7,887,456
Vim taglist plugin displays C++ tags twice
I'm using vim's "taglist" plugin to navigate source files in my project, but I've come across an issue peculiar to working with C++ files (as opposed to C; this may happen with other languages such as Java). For each function in a file, it will display two tags: one fully qualified, the other not, ie: initialise [()] C...
The answer was staring me in the face! I hadn't realised taglist was actually running its own ctags every time, not just using my tags file. All I needed to do was explicitly disable those C++ specific settings in taglist's ctags command thus: let Tlist_Ctags_Cmd = 'ctags --extra=-q --c++-kinds=-p' Hopefully this post...
7,832,249
7,832,286
an assignment has two Equal sign
following code we always use and is alright, while(int c=getchar() != 'q'); but if change the ints to pointers like below, compile will rise an error. #include <stdio.h> int main(){ int* c=0; if(int* a =c !=0) printf("ok"); } error: cannot convert `bool' to `int*' in assignment what had happened here? seems...
No, operator precedence hasn't changed between the two code snippets. The following: while(int c=getchar() != 'q') is equivalent to: while(int c = (getchar() != 'q')) Here, getchar() is called, its return value is compared to 'q', and the result of the comparison is stored in the int variable c. In other words, c do...
7,832,412
7,832,531
Boost.flyweight and Boost.MPL
I have a question regarding flyweight options, given the definition below, based on http://www.boost.org/doc/libs/1_40_0/libs/flyweight/test/test_basic.cpp typedef boost::flyweights::flyweight< std::string, boost::flyweights::tag<int>, boost::flyweights::static_holder_class<boost::mpl::_1>, b...
boost::mpl::_1 and boost::mpl::_2 are placeholders; they can be used as template parameters to differ the binding to an actual argument to a later time. With this, you can do partial application (transforming a metafunction having an n-arity to a function having a (n-m)-arity), lambda expressions (creating a metafuncti...
7,832,478
17,164,096
Excel RTD Server Development in C++
I want to write an excel RTD server in C++ but have not yet had any luck finding and complete tutorials on how to do so aside from this http://weblogs.asp.net/kennykerr/archive/2008/12/02/Rtd5.aspx. However, as I am new to this stuff, I think I need something more complete. Can any of you point me in the direction of ...
This Guide-to-Writing-Custom-Functions-in-Excel-Part-II details the process in full
7,832,657
7,832,678
C++: Friend method not accessing nested class
I have the following: using namespace std; template<class T> class olsm; template<class T> istream& operator>>(istream& in, olsm<T>& x); template<class T> ostream& operator<<(ostream& out, olsm<T>& x); template <class T> class olsm { friend istream& ...
olsm<T>::node* is a dependent name (it depends on a template parameter). You need to write typename olsm<T>::node* to tell the compiler that it refers to a type (by default, the compiler will assume it refers to a member). See this question for a more detailed explanation.
7,832,952
7,833,027
C++ mutable multitype array
I am quite new to C++ but am familiar with a few other languages. I would like to use a data type similar to a Java ArrayList, an Objective-c NSMutableArray or a Python array, but in C++. The characteristics I am looking for are the possibility to initialize the array without a capacity (thus to be able to add items gr...
You may use structure or class to store (named) multiple data types together, such as: class Record { bool _error; vector<string> _v1; vector<string> _v2; }; vector<Record> vec; or std::tuple to store (unnamed) multiple data types, e.g. vector<tuple<bool, vector<string>, vector<string> > > vec;
7,833,106
7,848,279
run tests automatically after sources changed
I use Cxxtest for unit-testing my C++ code. I would like that each time I change and save my code, tests are run (simply, by make tests). I know that for Python there is Nosy that enables that. Is there some generic program that would allow this for Cxxtest or any other testing unit? Simply, I just need running a sing...
Annoyed that there is no ready and simple solution, i just created a simple tool: changerun to run commands when files' change. I hope someone will find it useful : )
7,833,124
7,895,243
Old style cast warnings with sys/select.h macros
I am working on a project that uses select from C++ code. The code uses the macros FD_ZERO, FD_SET, FD_ISSET etc. Unfortunately These macros use 'C' casts, ergo they generate compiler warnings when the code is compiled with -Wold-style-cast. What is the best way for disabling -Wold-style-cast just for these macros? The...
I use select and those macros in C++ code with -Wall and get no warnings, though I do not use -Wold-style-cast. I think a better approach would be to take a step back and reconsider why it is important to not use C-style casts. I think, for interfacing with C standard library functions, it is entirely appropriate. The ...
7,833,196
7,833,269
Static member reclaiming memory and recovering from an exception
This is my assignment question Create a class with its own operator new. This operator should allocate 5 objects, and on 5th 'run out of memory' and throw an exception. Also add a static member function that reclaims this memory. Now create a main () with try block and catch clause that calls the memory-restor...
Sounds like you would need something like a static list of addresses in your class. Whenever new is called you store the address of the memory block in that list. Then in your release method you go through the static list and free the memory plus throw the exception.
7,833,224
7,833,281
Pointers arguments in copy constructor
I have a problem where I want to clone of a object pointer when doing a deep copy. like I have T* t1 and I want to create a new object pointer T* t2 in a way that *t1.x= *t2.x. Is it a good Idea to write a copy constructor which will work like: T(const T* cpy) { m_var = (*cpy).m_var; } T* t1 = new T; T* t2(t1); wh...
To do this you should write a normal copy-constructor and use it like this: T(const T& cpy) : m_var(cpy.m_var) // prefer initialization-list, thanks to @Loki Astari {} T* t1 = new T; T* t2 = new T(*t1); In the code you show, T* t2(t1); would never call the constructor you have declared (which, by the way, is not a co...
7,833,330
7,833,455
C++ distinguishing structurally identical classes
I have several types that share common behaviour and with same constructors and operators. Some look like this: class NumberOfFingers { public: void operator=(int t) { this->value = t; } operator int() const { return this->value; } private: int value; }; NumberOfToes is identical. Each class has different...
Yes, you are correct in that it would involve templates :) enum {FINGERS, TOES...}; ... template<unsigned Type> //maybe template<enum Type> but I havent compiled this. class NumberOfType { public: void operator=(int t) { this->value = t; } operator int() const { return this->value; } private: int value; }; ...
7,833,486
7,833,525
Executing C++ program on multiple processor machine
I developed a program in C++ for research purpose. It takes several days to complete. Now i executing it on our lab 8core server machine to get results quickly, but i see machine assigns only one processor to my program and it remains at 13% processor usage(even i set process priority at high level and affinity for 8 c...
Partition your code into chunks you can execute in parallel. You need to go read about data parallelism and task parallelism. Then you can use OpenMP or MPI to break up your program.
7,833,567
7,834,180
Printing an expression tree
I am able to print my expression tree in inorder. But I need to be able to print it in inorder with parenthesis. for example postorder 53+ should output (5+3) I currently have: void printTree(struct TreeNode *tree) { if (tree != NULL) { if (isalpha(tree->info) || isdigit(tree->info)) cout << "("; ...
You need to distinguish between leaf nodes and non-leaf nodes. Only non-leaf nodes are enclosed in parantheses. bool isLeaf(struct TreeNode* tree) { return tree->left == 0 && tree->right == 0; } void printTree(struct TreeNode* tree) { if (tree != NULL) { // this test could be omitted if the printed tree is not...
7,833,570
7,836,298
Problems with implementing QRCodeReader (ZXing)
So I've followed the steps mentioned here: http://zxing.googlecode.com/svn/trunk/iphone/README And I made sure everything is alright but yet my QRCodeReader isn't being recognized in myVC.mm file. This is what's the situation: The project is put into my own project as described in the link. I've imported the #import "...
The straight C++ code (not Objective C++) uses C++ namespaces. You need to either say zxing::qrcode::QRCodeReader or use using statements like using namespace zxing; using namespace zxing::qrcode; Update: The code above does bring in the C++ class but there's actually a widget class of the same name which I forgot...
7,833,665
7,833,823
Getting the char integer value from a std::string & std::wstring
I am attempting to convert a string into a number by summing the int value of each letter together in C++ WinAPI. So in ASCII; the std::string "AA" would equal 130 (65+65) The string can either be a std::string or an std::wstring. Why does the following function always return the value of zero no matter what letter I p...
the *toi family of functions converts a string representation to integer representation, that is, "10" becomes 10. What you actually want to do is no conversion at all. Change it to: printf("TEST a: %d \n", _T('a')); printf("TEST A: %d \n", _T('A')); printf("TEST b: %d \n", _T('b')); As for unicode, the underlying re...
7,833,833
7,836,231
Does Visual Studio 2005/08/10 replace Embedded Visual C++ 4.0?
In particular we are developing for Intermec CK30/CK31 running Windows CE. We have an existing C++ project that also targets newer devices (running Windows Mobile 5/6). The guy who has left this with us, just used to use both environments to develop the one set of source. But I would rather ditch one and develop for al...
You should be able to use VS2008 for all your development. You'll need to install the platform SDKs for the Intermec and WM versions (WM 4.2 and 5.0 standard should be there by default). VS2010 doesn't yet support Windows Mobile/CE development.
7,833,904
7,833,998
Avoid calling constructor of member variable
I have the following C++-class: // Header-File class A { public: A(); private: B m_B; C m_C; }; // cpp-File A::A() : m_B(1) { m_B.doSomething(); m_B.doMore(); m_C = C(m_B.getSomeValue()); } I now would like to avoid the class A to call any constructor of C m_C. Because on the last lin...
What you ask is forbidden - and correctly so. This ensures that every member is correctly initialized. Do not try to work around it - try to structure your classes that they work with it. Idea: C has a constructor that does nothing C has an initialization method that makes the class usable C tracks whether it has been...
7,833,941
7,834,555
putting function definitions in header files
If you want to put function definitions in header files, it appears there are three different solutions: mark the function as inline mark the function as static put the function in an anonymous namespace (Until recently, I wasn't even aware of #1.) So what are the differences to these solutions, and when I should I p...
The static and unnamed namespace versions end up being the same: each Translation Unit will contain it's own version of the function, and that means that given a static function f, the pointer &f will be different in each translation unit, and the program will contain N different versions of f (more code in the binary)...
7,833,992
7,836,450
How can I undeclare DECLARE_HANDLE?
I'm porting a piece of code from VC6 to VS2008. The code typedefs HSPRITE as int. But Windows SDK 6.1 already declared HSPRITE through DECLARE_HANDLE. I don't want to rename HSPRITE in my code since it will consume a lot of time to rename it in .cpp files. So, how can I undeclare HSPRITE?
Best is what @ybungalobill says. If you absolutely cannot use his answer, you can also trick windows.h into not declaring it, like this: #define HSPRITE DeletedWinapi_HSPRITE// prevent windows.h from defining it #include <windows.h> #undef HSPRITE typedef int HSPRITE;
7,834,103
7,834,184
Count the number of digits in a hexadecimal number
I am trying to count the number of digits that are available in a hexadecimal number. For example: 0x00000001 should return the count as 8. Could anyone suggest as to what is the most efficient way of doing this? I have tried converting it to a CString and get the length using 'GetLength()' but that doesn't seem to wor...
Since each byte contains two hexadecimal digits, try for a variable nof integral type sizeof(n)*CHAR_BIT/4
7,834,226
7,835,073
detecting typedef at compile time (template metaprogramming)
I am currently doing some template metaprogramming. In my case I can handle any "iteratable" type, i.e. any type for which a typedef foo const_iterator exists in the same manner. I was trying to use the new C++11 template metaprogramming for this, however I could not find a method to detect if a certain type is missing...
If you simply want if a given type contains const_iterator then following is a simplified version of your code: template<typename T> struct void_ { typedef void type; }; template<typename T, typename = void> struct Foo {}; template<typename T> struct Foo <T, typename void_<typename T::const_iterator>::type> { v...
7,834,372
7,834,570
Looking C++ code example resources
I am Newbie to C++ and Looking for some book/URL which has lot of C++ code related questions/examples like - What is output of this program or what is bug in this program?? Want to read lot of C++ code(Least/moderate complexity first).
The Bug of the Month - if you really want to find the bug.
7,835,138
7,835,219
C++ Refactoring: Initialization Ordering In Constructors
Suppose I need to call a free GlobalInitializer() before my constructor initializes any member variables. For example: class Foo { public: Foo() : bar_() { // calling GlobalInitializer() here is too late } Bar bar_; }; Calling GlobalInitializer() in Foo is too late because I need to call it befo...
class Foo { private: struct Initializer { Initializer() { GlobalInitializer(); } }; Initializer initializer__; // declare before bar__ to ensure it is constructed first public: Foo() : bar_() { } Bar bar_; };
7,835,371
7,835,564
Overloading operator help?
as ever I'm fairly new to C++ and I'm not exactly up with the lingo yet either so I apologize for sounding vague in advance! My problem is I'm struggling to see why my while loop seems to stop the rest of my methods in my overloaded operator function; #include "sample.h" #include <iostream> #include <vector> #include...
You have to obey the standard stream idioms: every stream is implicitly convertible to a bool (or void pointer) to allow a check like if (in >> n) to see if the operation succeeded. So first of all you have to make sure that your operator conforms to this (by ensuring that the stream is "good" if the extraction succeed...
7,835,656
7,835,701
Pointers in stl::map
I have query regarding std::map. if I have a std::map like: std::map <T1, T2*> my_map; T1 t; T2* tt = new T2; my_map[t]=tt; who is responsible to clean this container, Will destructor of T2 will take care of it (T2* tt). Also if I want to retain this container throughout the program, where should I clean it. Thanks
The map destroys the objects stored in the map. The map stores some T1 objects, which will be destroyed, and it stores some T2 pointers, which will be destroyed. But it does not store actual T2 objects. So no T2 objects will be destroyed. Raw pointers do not have ownership of the objects they point to. So when a pointe...
7,835,806
7,835,828
scanf from data buffer in C/C++
I'm working with a closed piece of hardware and I want to load a text file. I only have the following function to access secondary memory: bool load_file(const char *filename, int **buf, int *size) This means I would end up with all the data in buf and the size of it in size. How could I extract strings, integers or f...
You can use sscanf to scan memory blocks instead of files, similar to the way you can use sprintf to printf into memory. The prototype is: int sscanf (const char *str, const char *format, ...); In other words, the same as scanf but with a pointer added. That's for turning character data into other types. If you have r...
7,835,820
7,836,336
Confusion understanding Virtual function call and dependent base class
I am reading from ebook Templates complete guide and question which i'm gonna ask might be stupid to you but.. There is section in that 9.4.2 Dependent Base Classes which i am unable to understand. Here is the partial text from it: http://tinypaste.com/633f0 // Variation 2: template<typename T> class DD2 : public Ba...
If the qualified name ( basefield ) is a virtual function, then the qualification inhibits the virtual call. It's very much the same as if you have: struct Base { virtual void vCall() { } }; struct Derived : public Base { virtual void vCall() { } }; int main() { Derived d; Base* inst = &d; inst->Base::vCall...
7,835,874
7,836,612
C++ Wrapper of .lib implemented in Pascal
I've a C++ Builder project that uses this library http://www.torry.net/authorsmore.php?id=1881 (Cipher). Source files are included (.hpp / .pas) .lib file is included Seems to be that it is a C++ Builder library but I want to write a wrapper in C++ in order to use it in C++ programs and C# programs (simply said, make...
You will need to match up API calls and that gets redundant and boring. However, it seems to me, that the work is justified because your DLL can be used pretty much from anywhere at this point. The goal would be to wrap the C++ Builder project because it is compiling the .pas files which compiler friendly outside of a ...
7,835,904
7,836,113
uint4 variable value printing in c
In my program I have uint4 x variable. I have to print its value to stdout. How can I implement it using printf? Thank you in advance Note:uint4 x a structure of 4 unsigned integers
uint4 is no standard type and there's no common definition. I know of projects where uint4 refers to any of these: a 32-bit unsigned integer type (1) a 4-bit unsigned integer type, realized as a bitfield (2) a structure of 4 unsigned integers (3) You'd print them like this: // case (1) #include <inttypes.h> typedef ...
7,835,932
7,835,995
Size allocated for parameters sent to a method
Is there a way to know what is size of the allocated space for the parameters sent to a function if I know its frame pointer and return address? (preferably without using debug symbols)
In general, no. For a start, you don't know the calling convention so you have no idea how the parameters were passed and who is supposed to clean them up. Even if you do know the calling convention I don't believe there is a fool proof way to determine what you ask for.
7,836,064
7,836,187
Vector won't store correct datatype (wchar_t instead of uint16_t)
I have some code from the net reading hyperspectral data (image, so lots of integers giving pixel intensity) into a vector. I used the code with success on a Linux system, but now I need the same on a windows system. I use Visual Studio 2008. Reading the data in Linux I get a vector full of integers. On windows I get t...
Actually, it is working fine. Microsoft just wants to facilitate inspecting wchar_t values (which are short ints and represent utf16 coded characters on windows), so their debugger shows short ints as wchar_ts. It's just a matter of interpretation. If you had used chars for your data, you would encounter the same pheno...
7,836,106
7,836,348
C++ operator technique
It was mentioned on stack overflow by a programmer that if you declare one class function, for example: operator++() That for user-interface purposes (as the user naturally assumes its opposite should work), you should declare the other: operator--() Is there a link to an article that supports this? I wish to be able...
One hard thing about C++ and operator overloading is that it can be sort of a pun. Overloading assignment created a bit of a pickle with auto_ptr, because code that tried to take "assignment" for granted was being surprised by assigning A to B and then finding immediately afterward that A != B. http://hostilefork.com/...
7,836,134
10,750,648
Get 3D coordinates from 2D image pixel if extrinsic and intrinsic parameters are known
I am doing camera calibration from tsai algo. I got intrensic and extrinsic matrix, but how can I reconstruct the 3D coordinates from that inormation? 1) I can use Gaussian Elimination for find X,Y,Z,W and then points will be X/W , Y/W , Z/W as homogeneous system. 2) I can use the OpenCV documentation approach: as ...
If you got extrinsic parameters then you got everything. That means that you can have Homography from the extrinsics (also called CameraPose). Pose is a 3x4 matrix, homography is a 3x3 matrix, H defined as H = K*[r1, r2, t], //eqn 8.1, Hartley and Zisserman with K being the camera intrinsic m...
7,836,490
7,836,619
Detecting Multi-Byte Character Encodings
What C/C++ Libraries are there for detecting the multi-byte character encoding (UTF-8, UTF-16, etc) of character array (char*). A bonus would be to also detect when the matcher halted, that is detect prefix match ranges of a given set of a possible encodings.
ICU does character set detection. You must note that, as the ICU documentation states: This is, at best, an imprecise operation using statistics and heuristics. Because of this, detection works best if you supply at least a few hundred bytes of character data that's mostly in a single language.
7,836,651
7,837,944
Trouble with adding C++ objects to Objective C collections (NSSet)
I'm busy implementing ZXing with a QRCodeReader into my project. QRCodeReader is mainly C++ and my project objective-C. I have managed to implement it properly so I can use the QRCodeReader objects into my objective-C implementation (.mm file). But now I need to pass this C++ object to the zxWidController.reader proper...
A C++ type is not an Objective C type. You cannot send it messages, in particular retain and release, which NSSet does. There's an Objective C type of the same name that you want to use. (I'll update my other answer).
7,836,705
7,836,795
memory-allocation breakpoint does not stop execution
I have a piece of JNI code with a mem leak: Detected memory leaks! Dumping objects -> {76} normal block at 0x277522F8, 52 bytes long. Data: < "u' "u' "u' > F8 22 75 27 F8 22 75 27 F8 22 75 27 CD CD CD CD Object dump complete. So, I set a breakpoint ont the specified memory allocation number (76 in this case). _crt...
One possibility would be that memory allocation 76 occurs during the static initialization of a global variable. In that case, you may be setting _crtBreakAlloc too late to catch the allocation.
7,836,863
7,836,914
Is there a way to get std:string's buffer
Is there a way to get the "raw" buffer o a std::string? I'm thinking of something similar to CString::GetBuffer(). For example, with CString I would do: CString myPath; ::GetCurrentDirectory(MAX_PATH+1, myPath.GetBuffer(MAX_PATH)); myPath.ReleaseBuffer(); So, does std::string have something similar?
Use std::vector<char> if you want a real buffer. #include <vector> #include <string> int main(){ std::vector<char> buff(MAX_PATH+1); ::GetCurrentDirectory(MAX_PATH+1, &buff[0]); std::string path(buff.begin(), buff.end()); } Example on Ideone.
7,836,867
44,177,439
C++, variable declaration in 'if' expression
What's going on here? if(int a = Func1()) { // Works. } if((int a = Func1())) { // Fails to compile. } if((int a = Func1()) && (int b = Func2())) ) { // Do stuff with a and b. // This is what I'd really like to be able to do. } Section 6.4.3 in the 2003 standard explains how variables declared in...
As of C++17 what you were trying to do is finally possible: if (int a = Func1(), b = Func2(); a && b) { // Do stuff with a and b. } Note the use of ; of instead of , to separate the declaration and the actual condition.
7,837,190
7,837,369
C/C++ global vs static global
Possible Duplicate: Static vs global I'm confused about the differences between global and static global variables. If static means that this variable is global only for the same file then why in two different files same name cause a name collisions? Can someone explain this?
Global variables (not static) are there when you create the .o file available to the linker for use in other files. Therefore, if you have two files like this, you get name collision on a: a.c: #include <stdio.h> int a; int compute(void); int main() { a = 1; printf("%d %d\n", a, compute()); return 0; } ...
7,837,481
7,838,161
running code at exact times, a la crond/atd
Suppose I'm implementing a clock, and I want to minmise the number of wakeups per unit time. So, I'd like to be woken up on full minutes only (when I need to update the display). What's the best way to do this (portably, preferably) in C (or C++)?
The C++03 and C07 standards don't really provide any portable way to do this. If you can't depend on a newer compiler, nearly your only reasonably portable choice is probably POSIX threads (about which more below). Under C++11, you can create a thread, and use std::sleep_until, or (if you prefer, for some reason) std::...
7,837,515
7,838,757
random access to buffer optimisation
I have colorBuffer Color[width*height] (most likely 800*600) and during rasterization I call: void setPixel(int x, int y, Color & color) { colorBuffer[y * width + x] = color; } It turns out that this random access to color buffer is really ineffective and slows my application down. I think that it is caused the wa...
Yes, you should try to be cache-friendly, but the first thing I would do is find out what's taking time. It's simple enough. Just pause it several times and see what it's doing. If it's mostly in calculate next point, you should see what it's doing in there, because that's where the time is going. (I assume you underst...
7,837,537
7,837,856
Find the best interval match result
I have two sets of data in this form: x | y | z x1 | y1 | z1 ab1 | 1 | 2 ab1 | 1 | 2 ab1 | 2 | 3 ab1 | 1.8 | 2 ab2 | 2 | 3 ab1 | 1.8 | 2 The number of columns can change between 1 to 30. The number of rows of the two sets is likely to be different. The...
It can be cast as a graph theory problem. Let X be a set that contains one node for each row in your first set. Let Y be another set which contains one node for each row in your second set. The edges in the graph are defined by: for a given x in X and a given y in Y, there is an edge (x,y) if the row corresponding to x...
7,837,579
7,837,614
mingw compiler errors
First attempt at compiling some code without using Visual Studio. Installed mingw and set the environment path variable. Then tried to compile this code: #include <iostream> #include <vector> int main() { typedef std::vector<int> Container; typedef std::vector<int>size_type size; typedef std::vector<int>iterator iter;...
typedef std::vector<int>size_type size; typedef std::vector<int>iterator iter; Turn it into: typedef std::vector<int>::size_type size; typedef std::vector<int>::iterator iter;
7,837,615
7,837,842
in OO programming, what are some negative runtime impacts of inheritance?
I know there is some positive aspects of inheritance, but I don't know negative runtime impacts of inheritance? Can anybody tell me about that, thanks!
Large inheritance based systems usually uses more memory and have worse data layout than composition based systems, this has a runtime cost in terms of speed due to how the cache behaves ( you want everything related to be as tightly packed as possible ). Virtual function calls requires a trip to a virtual function ta...
7,837,618
7,837,812
enable_if : case of templated method of a template base inherited several times
If I have a template base class with a template method : template <typename T> class S { public: template <typename U> void f(U p, typename enable_if<is_same<T, U> >::type*dummy = 0) { std::cout << p << std::endl; } }; For the example, I simplify the method : it must "exists" only if T == U If...
Try this: a.S<int>::f(i); ...or alternatively inject the function into A, e.g. class A : public S<int>, public S<double> { public: using S<int>::f; using S<double>::f; };
7,837,642
7,837,713
Provide thread private preallocated buffer to a parallelized for() loop?
My program contains a for() loop that processes some raw image data, line by line, which I want to parallelize using OpenMP like this: ... #if defined(_OPENMP) int const threads = 8; omp_set_num_threads( threads ); omp_set_dynamic( threads ); #endif int line = 0; #pragma omp parallel pr...
I may be understanding you wrong, but I think this should do it: #pragma omp parallel { unsigned char buffer[1024]; // private // while letting each thread process exactly one line in a single run #pragma omp for // ... etc for(int line = 0; line < max; ++line ) { //... } } If you reall...
7,837,736
7,838,535
Is ISO/IEC 14882:2011 the final draft?
Sorry but I just want to be sure, since I'm thinking about buying it at some point. Is this it? Will there be any subsequent changes to C++11, or is that standard now, officially, the C++ language? (Not counting the eventual C++18, C++2x, etc. of course.) Wikipedia says C++11 was published as "ISO/IEC 14882:2011"[4...
The version you see now is the finished ratified specification. It is no longer a draft. They published in the finished spec September 2011" referred to in Wikipedia is when they published the finished spec, and also when it was formally given the name "C++11". Prior to that, when it was still a draft, it was referred ...
7,838,487
7,885,428
Executing cv::warpPerspective for a fake deskewing on a set of cv::Point
I'm trying to do a perspective transformation of a set of points in order to achieve a deskewing effect: http://nuigroup.com/?ACT=28&fid=27&aid=1892_H6eNAaign4Mrnn30Au8d I'm using the image below for tests, and the green rectangle display the area of interest. I was wondering if it's possible to achieve the effect I'm...
So, first problem is corner order. They must be in the same order in both vectors. So, if in the first vector your order is:(top-left, bottom-left, bottom-right, top-right) , they MUST be in the same order in the other vector. Second, to have the resulting image contain only the object of interest, you must set its w...
7,838,497
7,838,524
What is the cost of sizeof?
What is the cost of sizeof? I would expect: sizeof(someclass) can be known at compile time sizeof(someStaticArray) can be known at compile time sizeof(someDynamicArray) can not be known at compile time So how does that last case work?
The sizeof construct in C is a completely compile time construct. There is no runtime cost. There is at least one exception to this rule: variable length arrays. The size of these arrays are computed at runtime and that size is reused for any sizeof operators applied to them. Please note there is a difference bet...
7,839,170
7,839,285
Passing parameters to C++ CORBA method implementation
I'm new to using CORBA and I'm struggling with correctly passing the parameters to a method that I want to invoke. The method has the IDL signature void addUpdateListener(out OpStatus opStatus, in IPlanningUpdateListener listener); OpStatus is a struct defined as struct OpStatus { EComponent EComp; EStatus Sta...
In the client change OpStatus to a _var. OpStatus_var opStatus; myClass->addUpdateListener(opStatus, listener); The implementation will create a new struct to return. void addUpdateListener(OpStatus_out opStatus, _objref_IPlanningUpdateListener* listener) { opStats = new OpStatus; ... }
7,839,486
7,839,780
Library, which helps packing structures with good performance
Days ago I heard (maybe I've even seen it!) about library, that helps with packing structures. Unfortunately - I can't recall it's name. In my program I have to keep large amount of data, therefore I need to pack them and avoid loosing bits on gaps. For example: I have to keep many numbers from range 1...5. If I would ...
As Tomalak Garet'kal already mentioned, this is a feature of ANSI C, called bit-fields. The wikipedia article is quite useful. Typically you declare them as structs. For your example: as you mentioned you have one number in the range of 0..5 you can use 3 bits on this number, which leaves you 5 bits of use: struct s { ...
7,839,505
7,839,575
Undefined reference to static function pointer member in c++, what am I doing wrong?
please consider these files: p.h: #ifndef _p_h_ #define _p_h_ class p{ public: static void set_func(int(*)()); private: static int (*sf)(); }; #endif p.cpp: #include "p.h" #include <cstdio> int (p::*sf)() = NULL; //defining the function pointer void p::set_func(int(*f)()){ sf = f; } main.cpp: ...
Your attempt at defining p::sf is incorrect – yours is a definition of a global variable named sf that is of type int (p::*)(), i.e. a pointer to a member function. Consequently p::sf remains undefined, hence the linker error. Try this instead: int (*p::sf)() = 0; // or, typedef int (*p_sf_t)(); p_sf_t p::sf = 0;
7,839,713
7,839,908
Is there any way to reset static variables in 3rd party DLL to their original values?
We have to use 3rd party DLL in our development process, unfortunately we can't modify it or specify how library have to work. Original library developers introduced state mechanic in their methods via static variables. E.g.: void foo() { static int a = 1; if (a == 1) { /* some init logic */ a = 2; } } Somet...
Your current solution is the cleanest solution. The only alternative is to work out where the variable is stored in the DLL and modify it directly. But that's a gross hack that is incredibly brittle. For example, if the 3rd party DLL changes then your hack may stop working with unpredictable effects.
7,839,795
8,557,810
pjsip building for arm7 / iOS 4.3 - symbols not found in mips_test.o
I actually posted this question to pjsip mailing list, but did not get any response yet. So I thought it would try my luck here. This is a pretty simple issue I assume, I am trying to compile pjsip (latest from trunk) for iPhone sdk 4.3 on mac 10.6.2 I am following this instruction http://trac.pjsip.org/repos/wiki/Get...
codec g722 is disabled for iPhoneOS build. But unfortunately they have forgotten to exclude g722_encode_decode() from the build. You can simple edit mips_test.c and surround g722_encode_decode() and create_stream_g722() with # if PJMEDIA_HAS_G722_CODEC .. #endif Hope this helps.
7,839,925
7,841,251
Using AVX CPU instructions: Poor performance without "/arch:AVX"
My C++ code uses SSE and now I want to improve it to support AVX when it is available. So I detect when AVX is available and call a function that uses AVX commands. I use Win7 SP1 + VS2010 SP1 and a CPU with AVX. To use AVX, it is necessary to include this: #include "immintrin.h" and then you can use intrinsics AVX fu...
2021 update: Modern versions of MSVC don't need manual use of _mm256_zeroupper() even when compiling AVX intrinsics without /arch:AVX. VS2010 did. The behavior that you are seeing is the result of expensive state-switching. See page 102 of Agner Fog's manual: http://www.agner.org/optimize/microarchitecture.pdf Every ...
7,839,989
7,840,057
Create a Windows GDI Bitmap from memory
How can I load a bitmap (correctly built with every necessary header, stored in memory) from memory itself, and associating a HBITMAP with it?
You'll have to use CreateDIBSection to make a new buffer, then copy your bits into it....like so: std::ifstream is; is.open("Image.bmp", std::ios::binary); is.seekg (0, std::ios::end); length = is.tellg(); is.seekg (0, std::ios::beg); pBuffer = new char [length]; is.read (pBuffer,length); is.close(); tagBITMAPFILEHEAD...
7,840,089
7,884,390
Google channel api for c/c++ client
Is there a c/c++ client for google channel api?
No. The only official client is witten in Javascript.
7,840,203
7,840,420
error C2733 second C linkage of overloaded function 'function' not allowed
I am trying to compile old cpp MFC project in Visual Studio 2010 pro. It uses dll which is compiled using Labview, and I am adding this information because I don't know what is causing the error message.. The error messages show up on multiple functions, all same error type. error C2733: second C linkage of overloaded ...
I have no experience with MFC, anyway i'll try to answer. Such error message appears when an extern "C" function is declared with a different set of parameters. For example: extern "C" int myfunc(int); extern "C" int myfunc(char); In your case, the two declarations are probably related to char*: extern "C" char* StrCa...
7,840,315
7,840,637
Getting the Kinect SDK to work with visual studio 2010 in c++
I've been following the guide microsoft have made for setting up the Kinect SDK with c++. The steps they have created are as follows. Include windows.h in your source code. To use the NUI API, include MSR_NuiApi.h. Location: Program Files\Microsoft Research KinectSDK\inc To use the Kinect Audio API, include MSRKinectA...
2.To use the NUI API, include MSR_NuiApi.h. Location: Program Files\Microsoft Research KinectSDK\inc To do this, you probably want to add that path to your project Right-click on your project, properties, VC++ directories Add ;C:\Program Files\Microsoft Research KinectSDK\inc to the end of the include paths Add ;C:\...
7,840,405
7,841,478
flickering while rendering a 3D object (.obj file) using OpenGL
While attempting to render a 3D object using OpenGL (and the GLFW library), the model experiences lots of flickering. Im reading the .obj file using a library that I've written on my own. Written below is my render function: Unfortunately, in order to understand how faces and vertices are being inputted, I will have to...
Here's the problem gluPerspective(90, win_aspect, 0, 100.0); You cannot set 0 as your nearclip, set it to something larger like 0.1, or 1.0. gluPerspective(90, win_aspect, 1.0, 100.0); With nearclip at 0, all of your depths get mapped to z = 1, and you get z fighting. EDIT : if you're interested, here's some theory o...
7,840,692
7,840,717
C++ static class member - syntax error
I have this code:(BITMAPS is a free name) class BITMAPS{ public: static ALLEGRO_BITMAP *cursor; static void load_bitmaps(); static void unload_bitmaps(); }; and I'm trying to use it like this:(the lines with the errors) line 9: BITMAPS.load_bitmaps(); line 23: BITMAPS.unload_bitmaps(); line 36: BITMAP...
You need to use the Scope Resolution:: operator to refer to them, and not the syntax you are using. BITMAPS::load_bitmaps(); BITMAPS::unload_bitmaps(); BITMAPS::cursor; EDIT: To answer your updated Q You just declared the static member cursor, You also need to define it,in your source(cpp) file. like: ALLEGRO_BITMA...
7,840,714
7,840,771
on enum and bitwise operation
Maybe the question is so simple... There is an enum definition: enum uop_flags_enum { FICOMP = 0x001, FLCOMP = 0x002, FFCOMP = 0x004, FMEM = 0x008, FLOAD = 0x010, FSTORE = 0x020, FCTRL = 0x040, FCALL = 0x080, FRET = 0x100...
Ultimately, this code is checking if a single bit (the FCTRL flag) is turned on in the uop->flags variable. But here's some explanation: Implicitly, the code if(X) checks for X being a "true" value. For integers, 0 is the only "false" value and everything else is "true". Therefore your code is equivalent to: if (0 != (...
7,840,797
7,840,863
String prototype in header requires iostream?
So in my header i made a string: string s; The compiler freaks out at this. I know that string is part of iostream::std. Do I have to include it in the header instead of in the .cpp file then? If so is it bad if other files that use the header include iostream? How do I deal with that? Edit: Also for vector since it se...
string and vector are separate from iostream, and all three are part of the std namespace. You just have to properly qualify them in your header files. Assignment.h #include <string> #include <vector> // no need to #include <iostream> struct Obj { // fully qualified with std:: std::string s_; // sam...
7,840,824
8,009,299
MongoDB: how do I store binary array in a BSON in C++?
What's the syntax for adding binary array to a BSON with C++ driver? I'm sure it's somewhere in the docs, but can't find it.
From http://groups.google.com/group/mongodb-user/browse_thread/thread/b836032ad24dc00d To create a BSONObj in C++ that stores binary data, you can do something like: BSONObjBuilder builder; b.appendBinData ("fieldname", datasize, BinDataGeneral, data); BSONObj obj = builder.obj(); Documentation here: http://api.mongod...
7,840,874
7,840,894
What does it mean when a class declaration appears to have two names?
I'm trying to understand some C++ code which has the following class syntax: class Q_MONKEY_EXPORT BasePlugin : public QObject { // some code comes here }; I cannot understand the syntax class Q_MONKEY_EXPORT BasePlugin. To me it looks like if there are two names for the class. What exactly does this kind of synta...
Q_MONKEY_EXPORT is most likely a #define somewhere. Defines like that are sometimes required, for example when the class is in a library and needs to be exported when the header file is included from somewhere else. In that case, the define resolves to something like __declspec(dllexport) (the exact syntax will depen...
7,840,972
7,841,043
C++ Fail without Operator Definition
I'm currently porting a C++ application to a slightly restricted environment. The application uses the STL, string and stream classes. I'm rewriting simplified versions of these that will play nicely in my environment. What I'm concerned about is that my application is compiling even without all the necessary operator ...
It's impossible to be certain without seeing the rest of your code, but in this case it's probably not too hard to guess either. You almost certainly have a constructor for your string that takes a char const * as its parameter, so what's happening is that the compiler is using that ctor to convert the char const * to ...
7,841,293
7,842,202
What's the difference between QXml and QDom?
In Qt there are a number of different ways to work with XML. To keep this simple I only want to look at the QXml* classes and the QDom* classes. I'm trying to figure out which one to use but they both look to have similar functionality. What's are the main differences between QXml and QDom? Hypothetical example: Does o...
In short, QXml* classes implement SAX (Simple API for XML) XML parser while QDom* implement DOM (Document Object Model) XML parser. The main difference is that SAX is a sequential access parser, so it parses the document as it reads it, and makes first chunks of parsed data available almost instantly. DOM needs to load...
7,841,545
7,841,603
Does VS2010 SP1 support only part of the AVX instruction set?
Microsoft states VS2010 supports the full set of AVX instructions: http://blogs.msdn.com/b/vcblog/archive/2009/11/02/visual-c-code-generation-in-visual-studio-2010.aspx ... In VS2010 release, all AVX features and instructions are fully supported via intrinsic and /arch:AVX. ... But I cannot find any Intrinsics for Fus...
The Fused-Multiply Add intrinsics aren't part of AVX. Intel got rid of it in their later revisions for AVX. So FMA is separate instruction set. Even worse, there will be two of them FMA3 (Intel - Haswell), FMA4 (AMD - Bulldozer). VS2010 SP1 supports FMA4 - AMD's version of it. Neither processor line has been released y...
7,841,571
7,841,621
Qt namespace duplicate id error
I hope is not a question too specific... But I will be really thankfull if you could help! when I build my application I get this error, do you know why?: ld: duplicate symbol colors::white in mainwindow.o and main.o collect2: ld returned 1 exit status Here is the definition of the main: #include <QtGui/QApplicat...
Objects defined in a header file will be duplicated in every compilation unit that includes that header, leading to duplicate definition errors. These should either be extern (and defined elsewhere), or (my preference) made into free functions: Colors.h namespace color { const Color& white(); const Color& blac...
7,841,788
7,841,853
What is a guard block for a header file in C++?
I'm trying to make a C++ class using the Code::Blocks IDE and there is a field called "Guard block." I've done a search and haven't been able to find any useful information. What is this field for? Thanks.
Guard blocks are used to protect against the inclusion of a header file multiple times by the same compilation unit (c++ file). They look something like this: // Foo.h #ifndef INCLUDE_FILE_NAME_HERE_H_ #define INCLUDE_FILE_NAME_HERE_H_ class Foo { }; #endif If you include the same file multiple files, you will end ...
7,841,796
7,842,252
Optimization Help in OpenCV / C++
I am creating a simple image processing application using OpenCV / Qt and I am looking for a way to optimize the code that I have created (https://github.com/krslynx/ImageProcessingApplication). Currently, each time a slider is moved in the application the respective method is called which alters the image, for example...
Make a separate function that updates the image based on the sliders' values. For example have a function like this void MainWiondow::generic_sliderMoved() { cv::Mat result = this->image; result = setBrightness(result, ui->brightnessSlider->value()); result = setContrast(result, ui->contrastSlider->value()...
7,841,903
7,842,027
Read large txt file in c++
I'd like to read a file of about 5MB in memory ... the file has this format (it is a text file) ID 3: 0 itemId.1 0 itemId.2 0 itemId.5 1 itemId.7 ........................ 20 itemId.500 ID 50: 0 itemId.31 0 itemId.2 0 itemId.4 2 itemId.70 ........................ 20 itemId.2120 ..... how can I do this efficiently in ...
Reading a file line by line: ifstream fin ("file.txt"); string myStr; while(getline(fin, myStr)) // Always put the read in the while condition. { // Then you only enter the loop if there is data to //use myStr data // processes. Otherwise you need to read and then } ...
7,841,920
7,841,968
How do static libraries do linking to dependencies?
Say I have libA. It depends on, for example, libSomething for the simple fact that a non-inline method of libA makes a call to a method in libSomething.h. How does the dependency link up in this case? Does libA have to statically link to libSomething when it is compiled, or will a user of libA (an application using lib...
Static linking is just copying the whole items (functions, constants, etc) into the resulting executable. If a static library's code contains references to some shared library items, these references will become dependencies in the resulting executable. The same holds if you link a library instead of executable. This t...
7,842,053
7,842,115
Implementation layout of object model
Does the standard standardize the implementation detail of object? what i have heard that it is different on some compilers. Even if it is, Is it worth it to get 'inside the c++ object model' by lippman and how?
I cannot talk about the book, because I have not read it personally, but it is a common recommendation, so it will not hurt. As of the standard, it does not mandate a particular object layout, but only places constraints on the behavior of the program, but understanding even one implementation will help you understand...
7,842,331
7,842,361
Conversion from a derived class pointer to a base class pointer is not working when files are split into .cpp and .h files
Shape.h #include"Circle.h" #include"Square.h" class Shape { public: virtual void Draw() = 0; static Shape* Create(std::string type); }; Shape.cpp #include "Shape.h" Shape* Shape::Create(string type) { if ( type == "circle" ) return new Circle(); if ( type == "square" ) return new Square(); ...
You need to remove #include "Square.h" and #include "Circle.h" from Shape.h. Square and Circle depend on a definition of Shape because they both inherit from Shape but Shape can - and must - be defined before Square and Circle are defined so including definitions of Circle and Square before you define Shape is incorrec...
7,842,363
7,842,537
c++ std::map of heterogeneous function pointers
Is it possible to store pointers to various heterogenous functions like: In the header: int functionA (int param1); void functionB (void); Basically this would the part I don't know how to write: typedef ??boost::function<void(void)>?? functionPointer; And afterwards: map<char*,functionPointer> _myMap; In the .cp...
Each of your functions has a different type, so you need some kind of type erasure. You could use the most generic of them: Boost.Any. You can have a map of boost::any, but you need to know the type of the function in order to get it back and call it. Alternatively, if you know your arguments ahead of time you can bind...
7,842,595
7,842,632
How can you sort a const vector?
If I have a const vector defined in my class, how can I go about sorting it? Attempting to sort a const vector will give errors since I'm changing the contents of a const vector.
You don't. If you need to modify it... well then it shouldn't be const. The two goals are in direct conflict with one another. Instead of asking for a solution to a problem that doesn't make sense, tell us what you are actually trying to accomplish here. Are you trying to return a vector from a method that you don't...
7,842,637
7,842,664
where in memory static variables are stored?
Possible Duplicate: Where are static variables stored (in C/C++)? I am wondering where global variables and static variables are stored in C/C++. as far as local variables are stored in stack when function is active we also request memory from heap but I have no clue about static and global variables. Could an...
When loading an executable, the operating system allocates memory for the global data of the program. Usually they are kept in the .data and .bss sections of the executable.
7,842,738
7,842,800
Is there a GCC extension for implict return values?
I had, and have since corrected, something like the following code: class SomeClass { public: static int AdjustValue(float input); static int DoSomethingWithAdjustedValue(int adjustedInput); static int DoSomethingWithNormalValue(float input) { DoSomethingWithAdjustedValue(AdjustValue(input);} }; So...
try: > g++ xa1.cpp -Wall xa1.cpp: In static member function ‘static int SomeClass::DoSomethingWithNormalValue(float)’: xa1.cpp:8: warning: no return statement in function returning non-void xa1.cpp:8: warning: control reaches end of non-void function The return code was being passed along because of a lucky/unlucky m...
7,842,956
7,843,012
Returning a value with recursion in c++
I had an interview and I could not answer this question. You have an binary tree and you are putting all the nodes into an array using in_order and you return the value for the size of the array. I was told that I could not use a helper function and add int i=0 for an array counter. The recursive function heading I h...
Guessing all the missing details I think you would do something like: int In_order(Struct_Node * node, int *array){ int count = 0; if (node->left) { count += In_order(node->left, array); } array[count++] = node->data; // whatever it is you're storing if (node->right) { count += In_order(node->...
7,843,023
7,843,112
Missing brackets? Where?
I'm getting an error along the lines of 'warning missing braces around initializer for room', while I do understand the meaning of the error, I don't understand why it's being said. Here's the code: //manager.h class mapManager { public: mapManager(); private: }; class room //how the map tiles will have a...
I've just realized that I just pretended a class was an integer. Thanks for everyone's comments though.
7,843,048
7,843,192
Finding the closest fibonacci numbers
I am trying to solve a bigger problem, and I think that an important part of the program is spent on inefficient computations. I need to compute for a given number N, the interval [P, Q], where P is the biggest fibonacci number that is <= to N, and Q is the smallest fibonacci number that is >= to N. Currently, I am usi...
The Fibonacci numbers are given by Binet's formula F(n) = ( phi^n - (1-phi)^n ) / \sqrt{5} where phi is the golden ratio, phi = (1 + \sqrt{5}) / 2. This can be implemented straightforwardly (Python example): <<fibonacci_binet.py>>= phi = (1 + 5**0.5) / 2 def fib(n): return int(round((phi**n - (1-phi)**n) / 5**0...
7,843,050
7,843,111
Ranking Strings Based on a Search String in Linear Time
I have an SQLite database that stores several hundred or thousand strings, I keep an array of these strings that I grow so I can easily search my database more quickly. However the user can search with a search string and I will rank the strings in my database for their closeness to the search string. For example lets ...
When you say you want the ranking to be in linear time, I guess you only want to analyse each string in the set once. One relatively simple way to do that would be to calculate a score based on some rules you define. Of course, the more rules you have the longer it will all take, but as long as you implement the analy...
7,843,418
7,844,515
How to call C++ constructor from Visual Basic
I'm having trouble calling a C++ constructor in my Visual Basic code. The DLL has been imported correctly but this line in particular is giving me trouble: Dim myobj As New MyObject("param1", "param2", "param3") And the corresponding C++ constructor: MyObject::MyObject(System::String ^ p1, System::String ^ p2, System:...
You can't. It's simply not supported this way. The easiest way of doing it is to just convert the constructor into a function (eg Initialize()).
7,843,676
7,843,706
Exporting pointer to class from library
__declspec(dllexport) ClassName *c; placed in the header getting me a lot of error messages (up to 10), such as: syntax error : missing ';' before '*' missing type specifier - int assumed not only in that header, but also around static functions in ClassName implementation, while doing __declspec(dllexport) int *c;...
You should mark it as extern. Also, make sure the definition of ClassName is visible.
7,843,753
7,843,861
Am I Incorrectly using the Windows Clipboard?
I have some code to copy and paste: void WinClipboard::copy( const std::string& input ) { LPWSTR lptstrCopy; HGLOBAL hglbCopy; std::wstring text; text = _winUTF8ToUTF16(input); // Open the clipboard, and empty it. if (!OpenClipboard(NULL)) return; ...
I see two problems in your paste() function: 1) it is calling GlobalUnlock() before assigning the clipboard data to your std::wstring variable. You need to reverse those operations - call GlobalUnlock() after copying the data, not before. 2) it is not calling CloseClipboard() if GetClipboardData() fails.
7,843,764
7,843,792
Recursion with boolean type
I'm trying to learn recursion on my own. I've done the following exercise which should return true or false, but for some reason it always returns false. May someone, please, tell me why my code always returns false and what I need to do in order to rectify this situation? /*The subset sum problem is an important and c...
I didn't run the code, but it looks like there may be a problem with how the true result from sumPermute (in some recursion level) will not be propagated by the level "above" back to the source. To fix this, you would need to test the return value of sumPermute and if true make sure that it propagates back immediately....
7,843,924
7,844,207
Super long arrays in C++
I have two sets A and B. Set A contains unique elements. Set B contains all elements. Each element in the B is a 10 by 10 matrix where all entries are either 1 or 0. I need to scan through set B and everytime i encounter a new matrix i will add it to set A. Therefore set A is a subset of B containing only unique matric...
Here is some code, maybe not very efficient : # include <vector> # include <bitset> # include <algorithm> // I assume your 10x10 boolean matrix is implemented as a bitset of 100 bits. // Comparison of bitsets template<size_t N> class bitset_comparator { public : bool operator () (const std::bitset<N> & a, c...
7,843,976
7,855,734
Passing address of iterator to function in STL::for_each
I have a function that I eventually want to parallelize. Currently, I call things in a for loop. double temp = 0; int y = 123; // is a value set by other code for(vector<double>::iterator i=data.begin(); i != data.end(); i++){ temp += doStuff(i, y); } doStuff needs to know how far down the list it is. So I use ...
If you want real parallelization here, use GCC with tree vectorization optimization on (-O3) and SIMD (e.g. -march=native to get SSE support). If the operation (dostuff) is non-trivial, you could opt to do it ahead of time (std::transform or std::for_each) and accumulate next (std::accumulate) since the accumulation w...
7,843,980
7,844,145
Error LNK 2019 unresolved external symbol from header file from my professor
So I'm pretty new to C++ programming and am taking a class on it but am having some trouble with an assignment because I am getting an error I can't seem to fix. The assignment is to create a composite class out of a number of classes using a string class the professor gave us. The problem I'm having is that I'm gettin...
If I were you I would just copy all the professor files to the project directory, and add both header and source files to it.
7,844,028
7,844,448
Indirection Operator and Pointers to Array
It seems the regular definition of the indirection operator doesn't apply when it is used on multi-dimensional arrays: int arr[10][10][10]; If you dereference arr, you'll get the same address: (void*)arr == (void*)*arr && (void*)*arr == (void*)**arr This makes sense though - a multi-dimensional array is just a contig...
Firstly, to fully understand this you must appreciate that C does not have multidimensional arrays - it has arrays of arrays. So, in your example, arr is "an array of 10 arrays of 10 arrays of 10 ints". Secondly, it's not the indirection operator that behaves differently, it's the behaviour of expressions with array t...
7,844,198
7,844,241
Invalid use of template-name ‘Matrix’ without an argument list
Here is my Matrix.cpp file. (there's a separate Matrix.h file) #include <iostream> #include <stdexcept> #include "Matrix.h" using namespace std; Matrix::Matrix<T>(int r, int c, T fill = 1) { if (r > maxLength || c > maxLength) { cerr << "Number of rows and columns should not exceed " << maxLen << endl; thr...
If your class is template then correct definition should be, template<class T> Matrix<T>::Matrix(int r, int c, T fill) // don't give default argument ... Also, don't forget to include this Cpp file where you use this class. Because in the case of templates, full body should be visible to all translation units. Edit: ...
7,844,317
7,844,328
Error: expected unqualified-id before & token
I'm very new to C++ and I am creating my first class. I have every error out of the way except one: error: expected unqualified-id before & token The assignment operator signature looks like this: Job::& operator = (const Job &v ) I've tried everything I can think of, removing the &, doing Job::Job & operator, removi...
When declaring inside the class definition: Job& operator = (const Job &v ) When defining outside the class definition: Job& Job::operator = (const Job &v )
7,844,378
7,844,392
Difference between Functions and Function Pointers as Arguments
This is a rather simple question that is making me a bit curious. Consider the following code snippet: #include <iostream> int three() { return 3; } void foo(int func(void)) { std::cout << func() << std::endl; } void bar(int (*func)(void)) { std::cout << func() << std::endl; } int main() { foo(three...
There is no difference: the types of foo and bar are the same: int(int(*)()). There is no such thing as a function-type parameter: when a parameter appears with the function type syntax (like int func(void)), it is transformed into the corresponding pointer-to-function type (like int (*func)(void)). The transformati...
7,844,381
7,844,405
Reading text from several files C++
I have some text files in a folder named foo1, foo2,...,foo5. I tried to write a C++ program to print out the contents of the files but the compiler is giving an error. Here is the program. int main(int argc, char *argv[]) { string common="foo"; for(int count=1;count<=5;++count) { //Convert count to an stri...
Replace: ifstream infile(filename); with ifstream infile(filename.c_str()); The error message that you posted shows you this. fstream is a typedef for basic_fstream<>. Your error message says, in essence, that there is no fstream constructor that takes a string&, but there is one that takes a char*.