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
2,276,840
2,388,351
easing c++ to objective-c/cocoa bridging via metaprogramming?
In a pure C++ world we can generate interfacing or glue code between different components or interfaces at compile time, using a combination of template-based compile-time and runtime-techniques (to e.g. mostly automatically marshall to/from calls using legacy types). When having to interface C++ applications with Ob...
I didn't find anything satisfactory and came up with a prototype that, given the following informal protocol: - (NSString*)concatString:(NSString*)s1 withString:(NSString*)s2; and this C++ code: struct CppClass { std::string concatStrings(const std::string& s1, const std::string& s2) const { return s1+s2; ...
2,276,901
2,277,010
Fully specialised templates and dllexport
Microsoft says: “Templates cannot be used with functions declared with __declspec (dllimport) or __declspec (dllexport).” (link). What does this mean? Can I export a function which has a fully specialized template class reference as an argument?
That isn't a dllexport/dllimport-specific problem, its a general issue with templates - only one compiler currently implements the means to export templates, see Comeaus template FAQ for details. Fully specialized templates however are distinct and concrete types and basically usable with the __declspec extension, but ...
2,277,015
2,277,177
Writing a C++ version of the algebra game 24
I am trying to write a C++ program that works like the game 24. For those who don't know how it is played, basically you try to find any way that 4 numbers can total 24 through the four algebraic operators of +, -, /, *, and parenthesis. As an example, say someone inputs 2,3,1,5 ((2+3)*5) - 1 = 24 It was relatively s...
So, the simple way is to permute through all possible combinations. This is slightly tricky, the order of the numbers can be important, and certainly the order of operations is. One observation is that you are trying to generate all possible expression trees with certain properties. One property is that the tree will...
2,277,018
2,277,729
Wrapping a pure virtual method with arguments using Boost::Python
I'm currently trying to expose a c++ Interface (pure virtual class) to Python using Boost::Python. The c++ interface is: Agent.hpp #include "Tab.hpp" class Agent { virtual void start(const Tab& t) = 0; virtual void stop() = 0; }; And, by reading the "official" tutorial, I managed to write and build the next Py...
The get_override functions returns an an object of type override which has a number of overloads for differing number of arguments. So you should be able to just do this: void start(const Tab& t) { this->get_override("start")(t); } Did you try this?
2,277,154
2,277,174
debugging loop c++ undefined variable, what type? Hoglund
I have been reading one of the Hoglund titles and I though, reading great, but can I make it work? Why do they provide non-working examples in books? #include "stdafx.h" #include <cstdio> #include <windows.h> #include <winbase.h> #include <tlhelp32.h> int _tmain(int argc, _TCHAR* argv[]) { HANDLE hProcess; DE...
Taking this from MSDN: BOOL WINAPI DebugSetProcessKillOnExit(__in BOOL KillOnExit); you can declare the function pointer as: BOOL (*fDebugSetProcessKillOnExit)(BOOL) = /* ... */; or ease your eyes by using typedef: typedef BOOL (*DebugKillPtr)(BOOL); DebugKillPtr fDebugSetProcessKillOnExit = /* ... */; Function poi...
2,277,224
2,277,270
C++ figure out CPU/Memory usage
I have a C++ app called ./blah (to which I have the source code) when I run ./blah I can run "top" and see how much memory & cpu "./blah" is using. Now, is there anyway for "./blah" to access that information itself? I.e. when I run ./blah, I want it to every second dump out it's CPU & Memory usage. What library should...
You want getrusage(). From the man page: int getrusage(int who, struct rusage *r_usage); getrusage() returns information describing the resources utilized by the current process, or all its terminated child processes. The who parameter is either RUSAGE_SELF or RUSAGE_CHILDREN. The buffer to which r_usage points wi...
2,277,252
2,279,672
How do I install hardware driver using C++ on Win32?
How do I install a hardware driver (inf file) using C++? Platform : Win32
The process is usually called pre-installation. (The normal install process is triggered by the arrival of an hardware device.) The relevant functions can be found in <DIFxAPI.h> from the DDK. You probably want to call DriverPackageInstall(). The expected return value is ERROR_NO_SUCH_DEVINST [sic] as there won't be s...
2,277,385
2,277,477
Why can I not define a member function in a class if that function is to be linked from another translation unit?
I am a bit of a newbie in C++, but I just stumbled on the following. If I have these files: myclass.hpp: class myclass { public: myclass(); void barf(); }; mymain.cpp: #include "myclass.hpp" int main() { myclass m; m.barf(); return 0; } And I use this implementation of myclass: myclassA.cpp: #include <ios...
standard that says that there must be a unique definition of a class, template, etc., is phrased in a somewhat more complicated and subtle manner. This rule is commonly referred to as ‘‘the one definition rule,’’ the ODR. That is, two definitions of a class, template, or inline function are accepted as examples of the ...
2,277,497
2,277,538
Struct with the function parameters
Can I suppose that, from the call stack point view, it's the same to call a function like function1 int function1(T1 t1, T2 t2); than to another like function2? struct parameters_t { Wide<T1>::type t1; Wide<T2>::type t2; } int function2(parameters_t p); Where, Wide template wide T to the processor word leng...
Question 1. No the two function calls aren't necessarily the same -- calling conventions that push parameters right to left and left to right are both in wide use. It sounds like you want to create a function that takes a variable number of a variable type of parameters. To do that, I'd have it take something like an s...
2,277,508
2,277,539
Some problem using pointers to enter a string
I'm a beginner and i need to ask a question.. I wrote this small code that accepts a string from the user and prints it..very simple. #include <iostream> using namespace std; int main() { int i; char *p = new char[1]; for(i = 0 ; *(p+i) ; i++) *(p+i) = getchar(); *(p+i) = 0; for(i = 0 ; *(p+i)...
There are several problems with this code. First, you have a buffer overflow, because char *p = new char[1] allocates only one character for storage. This is exceeded when i > 0. Next, your first loop will keep going until it reaches a point in unallocated memory (undefined behavior) that has a value of zero. This just...
2,277,658
2,277,682
Invalid use of incomplete type on g++
I have two classes that depend on each other: class Foo; //forward declaration template <typename T> class Bar { public: Foo* foo_ptr; void DoSomething() { foo_ptr->DoSomething(); } }; class Foo { public: Bar<Foo>* bar_ptr; void DoSomething() { bar_ptr->DoSomething(); } }; Whe...
Yes, just move the method definitions out of the class definition: class Foo; //forward declaration template <typename T> class Bar { public: Foo* foo_ptr; void DoSomething(); }; class Foo { public: Bar<Foo>* bar_ptr; void DoSomething() { bar_ptr->DoSomething(); } }; // Don't forget to ...
2,277,865
2,277,894
Are there any low-level languages that can be used in place of scripts?
I am a "high-level" scripting guy. All my code is Class-based PHP or JavaScript. However, I want to know if there is any form of useful interpreter projects for "low-level" compiled languages like C or C++ (strange sounding huh?). This all came about when I stumbled upon http://g-wan.com/ and was fascinated by the fact...
I recently stumbled upon something called BinaryPHP in which you code normally in php and then convert the script into C++ to be compiled on your favorite tool. That should be a nice learning curve for someone already in touch with php.
2,277,918
2,277,958
Simple Linked List Implementation in C++
I'm a programming student in my first C++ class, and recently we covered linked lists, and we were given an assignment to implement a simple one. I have coded everything but my pop_back() function, which is supossed to return a pointer to the Node that needs to be deleted in Main(). No Node deletion is to be done in th...
So if I understand this right you just want to run through your linked list until you get to the last node in the linked list and return the pointer to it? I'm pretty sure what you have there will do it except Node* List::pop_back() // this whole function may be wrong, this is just my attempt at it { Node* te...
2,277,937
2,277,983
Compare shared_ptr with object created on stack
I have a situation where I would like to compare an object encapsulated by a shared_ptr with the same type of object created on a stack. Currently, I'm getting the raw pointer and dereferencing it to do the comparison eg: Object A; std::shared_ptr<Object> B; // assume class Object has its comparison operators overload...
shared_ptr overloads operator*() so that it acts just like a pointer, so just write: if ( *B < A ) { docs: http://www.boost.org/doc/libs/1_42_0/libs/smart_ptr/shared_ptr.htm#indirection
2,277,986
2,278,072
Can I programatically deduce the calling convention used by a C++ dll?
Imagine you'd like to write a program that tests functions in a c++ dll file. You should enable the user to select a dll (we assume we are talking about c++ dlls). He should be able to obtain a list of all functions exported by the dll. Then, the user should be able to select a function name from the list, manually inp...
The answer is maybe. If the functions names are C++ decorated, then you can determine the argument count and types from the name decoration, this is your best case scenario, and fairly likely if MSVC was used to write the code in the first place. If the exported functions are stdcall calling convention (the default for...
2,278,003
2,278,037
SFML Releasing Resources
I've recently started using SFML and noticed that there aren't any kinds of "FreeResource" methods provided. For example, sf::Font has a function called LoadFromFile, but no functions to release the resource. I thought this was very odd. Am I missing something? Is my only option to create an sf::Font pointer and dynami...
sf::Font stores its font data in a std::map called myGlyphs (see the source). When Font's destructor is called, everything in that map will be freed automatically (by the std::map destructor).
2,278,006
2,282,389
Does Lazy C++ (lzz) play nice with Doxygen?
Has anyone tried embedding Doxygen comments within Lazy C++ source files? Any problems? Where do the Doxygen comments go after generating the header/source files?
I went ahead and downloaded Lazy C++ to try it out, and it seems that it does not play nice with Doxygen. My Doxygen comments did not appear at all in the generated header/source files. I then tried making Doxygen parse my lzz file, which had a special #hdr preprocessor command. Doxygen simply ignored that special prep...
2,278,228
2,278,331
OpenCV Image Processing -- C++ vs C vs Python
I was thinking of trying OpenCV for a project and noticed that it had C, C++ and Python. I am trying to figure out whether I should use C++, C or Python -- and would like to use whatever has the best OpenCV support. Just from looking at the index page for the various documentation it looks like the C++ bindings might...
The Python interface is still being developed whereas the C++ interface (especially with the new Mat class) is quite mature. If you're comfortable in C++, I would highly recommend using it - else, you can start using Python and contribute back any features you think OpenCV needs :)
2,278,274
2,278,290
Is it possible to treat datatypes as an input stream?
int main(int argc, char *argv[]) { Move move; ifstream inf("eof.txt"); inf >> move; return 0; } istream& operator>> (istream &is, Move &move) { is >> move.c; // c = char c[2]; cout << move.c << endl; return is; } eof.txt has lines of 2 chars, so if it had "9r", "9r" would be stored in move's data membe...
You can use a stringstream: #include <sstream> int main() { char foo[] = "1d"; std::stringstream ss(foo); Move move; ss >> move; return 0; }
2,278,275
2,278,423
When/why should heapmin be used?
A customer has some memory usage requirements of our application. They note that while our committed memory is reasonable, the reserved memory is high. They suspect this is because the CRT heap grows as we allocate memory, but the CRT isn't returning pages to the OS when the memory is deallocated. We are just using b...
As you are using the CRT memory manager there is no need to call it explicitly the OS will manage this.
2,278,291
2,278,312
Linker Errors - Unresolved external symbol
Howdy. I am working on a C++ assignment for my class. I am almost done but can't seem to figure out these errors: error LNK2001: unresolved external symbol "public: virtual void __thiscall HasQuarterState::dispense(void)const " (?dispense@HasQuarterState@@UBEXXZ) gumball.obj Gumball error LNK2001: unresolved external s...
You've declared dispense in HasQuarterState but have not defined it. The function has no body. Likewise with turnCrank in SoldState.
2,278,370
2,278,417
c++ singleton initialization order
I have class Foo class Bar Now, I want Foo* Foo::singleton = new Foo(); Bar* Bar::singleton = new Bar(); to both initialize before int main() is called. Furthermore, I want Foo::singleton to initialize before Bar::singleton Is there anyway I can ensure that? Thanks!
See also Static variables initialisation order For gcc use init_priority: http://gcc.gnu.org/onlinedocs/gcc/C_002b_002b-Attributes.html Works across different translation units. So your code would read: Foo* Foo::singleton __attribute__ ((init_priority (2000))) = new Foo(); Bar* Bar::singleton __attribute__ ((init_prio...
2,278,414
2,278,430
Rotating an image in C/C++
I need code for rotating an image in C++ which functions like imrotate function of matlab. Please suggest a good link. Or if someone can provide the code for imrotate. Or at least please explain the algorithm. Its not a homework. I need this code for my project. And we can use any external library or code.
OpenCV2.0 has several computer vision and image processing tools. Specifically warpAffine (by defining the rotation matrix) will solve your problem with rotating an image. The 2x3 transformation matrix mentioned in the documentation is as follows: where θ is the angle of rotation and tx and ty is the translation along...
2,278,490
2,278,510
Can somebody explain this C++ typedef?
I've just started working with C++ after not having worked with it for quite a while. While most of it makes sense, there are some bits that I'm finding a bit confuddling. For example, could somebody please explain what this line does: typedef bool (OptionManager::* OptionHandler)(const ABString& value);
It defines the type OptionHandler to be a pointer to a member function of the class OptionManager, and where this member function takes a parameter of type const ABString& and returns bool.
2,278,635
2,278,807
Using STL algorithms (specifically std::sort) from within a templated class
I've declared a template class MyContainer as bellow, then created an instance of it of type DataType1. The DataType1 class provides a friend function "DataSpecificComparison" which is used by std::sort to compare DataType1 objects. The program compiled and sorted correctly. I then defined a class called DataType2, ga...
You can use a temporary local function pointer variable of the required type to select the correct overload of DataSpecificComparison: void SortMyContainerObjects() { typedef bool (*comparer_t)(const T*, const T*); comparer_t cmp = &DataSpecificComparison; std::sort(m_vMyContainerObjects.begin(), m_vMyConta...
2,278,710
2,281,370
terminate called after thowing an instance of '__gnu_cxx::recursive_init'
I've googled for the error above; no use. This error comes form the following line of code: void Thread::join(void** status) { pthread_join(thread, status); } Anyone has any idea what it means? (Google brings up other ppl complainig about the error, but no explaingion of it).
Ref http://www.opensource.apple.com/source/libstdcxx/libstdcxx-5.1/libstdcxx/libstdc++-v3/libsupc++/guard.cc: namespace __gnu_cxx { // 6.7[stmt.dcl]/4: If control re-enters the declaration (recursively) // while the object is being initialized, the behavior is undefined. // Since we already have a library functi...
2,278,732
2,278,755
Unsticky a cout modifier?
cout << hex << 11 << endl; cout << 12 << endl; will print : a b If I cout 13, it will be printed as 'c'. How do I remove the hex modifier from now on so it would just print 13? This is probably simple but I tried looking for the answer elsewhere. Thanks.
Write in your code: cout << dec << 13
2,278,966
2,279,001
Adding boost::ptr_vector to deque, typeid mismatch
I'm trying to add a boost::ptr_vector to a std::deque, using push_back(). When I do, I get a BOOST::ASSERT for the typeid mismatch. In "boost_ptr_container_clone_allocator" T* res = new T( r ); BOOST_ASSERT( typeid(r) == typeid(*res) && "Default new_clone() sliced object!" ); return re...
You should specialize the new_clone and delete_clone functions as described in the documentation. Alternatively you could specify your own clone allocator as the second argument of ptr_vector: class Item { public: int my_val; Item() : my_val(1) { } Item* clone() const { Item* item = do_clone(); BOOST_A...
2,279,007
2,279,042
How do you "break" out of a function?
Given a function that returns a value, is it possible to exit the function given a certain condition without returning anything? If so, how can you accomplish this? Example: int getNumber () { . . . } So say you are in this function. Is there a way to exit it without it doing anything?
You have two options: return something or throw. int getNumber() { return 3; } int getNumber() { throw string("Some Var"); } If you throw, you have to catch the type you threw. int maint(int argc, char ** argc) { try { getNumber(); } catch(string std) { //Your ...
2,279,147
2,279,179
Calculate height of a tree
I am trying to calculate the height of a tree. I am doing it with the code written below. #include<iostream.h> struct tree { int data; struct tree * left; struct tree * right; }; typedef struct tree tree; class Tree { private: int n; int data; int l,r; public: tree * Root; Tree(int x)...
But isn't a postorder traversal precisely what you are doing? Assuming left and right are both non-null, you first do height(left), then height(right), and then some processing in the current node. That's postorder traversal according to me. But I would write it like this: int Tree::height(tree *node) { if (!node) ...
2,279,180
2,279,205
Does C++ have "with" keyword like Pascal?
with keyword in Pascal can be use to quick access the field of a record. Anybody knows if C++ has anything similar to that? Ex: I have a pointer with many fields and i don't want to type like this: if (pointer->field1) && (pointer->field2) && ... (pointer->fieldn) what I really want is something like this in C++: wit...
In C++, you can put code in a method of the class being reference by pointer. There you can directly reference the members without using the pointer. Make it inline and you pretty much get what you want.
2,279,436
2,279,528
c++ namespace export
Is there a way in C++ to create an anonymous namespace, and only export a single function out of it? I want something like: namespace { void Bar() {} void Foo() { Bar(); } } Now, I want to somehow access to Foo() yet make sure there's no way to touch Bar() Thanks!
Since you want Foo() to have external linkage, you should declare it in a header file: #ifndef FOO_H #define FOO_H void Foo(); #endif Now everyone can see and call Foo() But in Foo.cpp: #include "Foo.h" namespace { void Bar(){ } } void Foo(){ Bar(); } Now, as long as you control the source file Foo.cpp, no on...
2,279,603
2,279,834
Using STL inside ATL
I need to use tree structure inside a ATL COM server. I thought of using stl::map<> for this purpose as follows. BaseMap[k1,NextLevelMap[k2, NextLevelMap[k3, Value]]] But I need to know, whether using such a structure inside ATL is safe and possibility of debugging support with maps. Thank you
C++ standard library classes are safe to use with ATL - ATL even includes a couple of classes specifically designed to interface with containers following standard library conventions: ICollectionOnSTLImpl and CComEnumOnSTL. Debugging is also fine - the Visual Studio debugger hides the implementation of the standard c...
2,280,462
2,281,405
Linker fails to link my application (XXXX already defined in XXXX.obj)
When I try to build my application the linker gives loads of errors like this one: modlauch.obj : error LNK2005: "public: virtual __thiscall lolbutton::~lolbutton(void)" (??1lolbutton@@UAE@XZ) already defined in lolbutton.obj I suspect it has something to do with misconfigured compiler but I don't know how to...
You'll get the linker error when you wrote the class like this: lolbutton.h: class lolbutton { public: virtual ~lolbutton(); }; lolbutton::~lolbutton() { // something... } You won't get it when you write it like this: class lolbutton { public: virtual ~lolbutton() { // inlined something... } }; Fix t...
2,280,499
2,280,555
Vkontakte UserAPI examples on C++
Say me please, where i can find examples on C++ with using UserAPI Vkontakte?
libvkext on google code seems to be one, you can also try to search google codebase for more...
2,280,630
2,280,729
c++ threadsafe static constructor
Given: void getBlah() { static Blah* blah = new Blah(); return blah; } In a multi threaded setting, is it possible that new Blah() is called more than once? Thanks!
The C++ standard makes no guarantee about the thread safety of static initializations - you should treat the static initialization as requiring explicit synchronisation. The quote Alexander Gessler gives: If control enters the declaration concurrently while the object is being initialized, the concurrent execution...
2,280,639
2,280,687
Is .NET "all COM underneath"?
I've been an admirer of Juval Lowy's teaching and guidance in .NET development for a number of years. He's also written one of my favorite books: Programming .NET Components. However on a recent DotNet Rocks podcast (Jan 2010) in discussing WCF/COM and .NET, he made some comments that greatly surprised me: Juval Lö...
It's almost as if Löwy is intentionally attempting to be unclear in what he says. I've not listened to the podcast, but judging by the umlauts, I reckon English is not his first language. Some objects that you use in .NET really are wrappers for COM objects. And a .NET object you create does a lot of what COM is su...
2,280,688
2,281,928
Taking the address of a temporary object
§5.3.1 Unary operators, Section 3 The result of the unary & operator is a pointer to its operand. The operand shall be an lvalue or a qualified-id. What exactly does "shall be" mean in this context? Does it mean it's an error to take the address of a temporary? I was just wondering, because g++ only gives me a warnin...
The word "shall" in the standard language means a strict requirement. So, yes, your code is ill-formed (it is an error) because it attempts to apply address-of operator to a non-lvalue. However, the problem here is not an attempt of taking address of a temporary. The problem is, again, taking address of a non-lvalue. T...
2,280,965
2,280,996
how can i check file write permissions in C++ code?
In my C++ program, I want to make sure i can write info to a file. How can I perform this check?
You use the stat() system call, which the purists will tell you doesn't exist unless you change the tags on your question.
2,281,168
2,281,279
quick vector initialization c++
Possible Duplicates: C++: Easiest way to initialize an STL vector with hardcoded elements Using STL Allocator with STL Vectors out of curiosity i want to know quick ways of initializing vectors i only know this double inputar[]={1,0,0,0}; vector<double> input(inputar,inputar+4);
This is IMHO one of the failings of the current C++ standard. Vector makes a great replacement for C arrays, but initializing one is much more of a PITA. The best I have heard of is the Boost assignment package. According to the docs, you can do this with it: #include <boost/assign/std/vector.hpp> // for 'operator+=()'...
2,281,420
2,281,473
C++ Inserting a class into a map container
I have a map in C++ and I wish to input my class as the value, and a string as the key. When I try to, I get an error 'Scene_Branding' : illegal use of this type as an expression I get an illegal use of this type as an expression, and I can't seem to find out why. Here is some code. string CurrentScene = "Scene_Brandi...
First, don't store objects themselves in the map, store pointers to your objects. Second, you need to give an instance of Scene_Branding to std::make_pair, not the class itself. EDIT: Here's how you go about storing pointers: string CurrentScene = "Scene_Branding"; map<string, Scene*> Scenes; Scenes.insert(std::make...
2,281,425
2,281,457
Read and parse line in C/C++; put tokens in an array or vector or similar structure
I have to submit code to one of the problems in ACM IPC and, as you may know, the time counts a lot. So, I have to read efficiently an input like this: The first line will contain the sequence of integer values associated and the second line will contain the sequence of integer values associated with another sequence....
Read the lines using std::getline(). Then use a std::stringstream to parse each line. As this is for a competition, you won't be wanting actual code.
2,281,532
2,281,907
VS2008: Can I build a project with 2 CPP files of the same name in different folders?
Here is my folder structure: / | -- program.cpp -- utility.h -- utility.cpp | -- module/ | -- utility.h -- utility.cpp // Note that I have two files named utility.h and two named utility.cpp On building the project, I get a link error (LNK2028: unresolved token and so on...) saying that some symbols...
Right click both/either .cpp files > properties > C/C++ > Output Files > Object File Name > set a custom name. e.g. if both files are named MyFile.cpp in folder A and another in folder B, you can set the output to be AMyFile and BMyFile. Alternatively, you can also use a macro to prefix the object names with the immedi...
2,281,739
2,291,426
Automatically adding Enter/Exit Function Logs to a Project
I have a 3rd party source code that I have to investigate. I want to see in what order the functions are called but I don't want to waste my time typing: printf("Entered into %s", __FUNCTION__) and printf("Exited from %s", __FUNCTION__) for each function, nor do I want to touch any source file. Do you have any sugges...
Besides the usual debugger and aspect-oriented programming techniques, you can also inject your own instrumentation functions using gcc's -finstrument-functions command line options. You'll have to implement your own __cyg_profile_func_enter() and __cyg_profile_func_exit() functions (declare these as extern "C" in C++...
2,281,819
2,281,837
Pointer allocation vs normal declaration
sometimes I see in various C++ programs, objects declared and used like so: object *obj = new object; obj->action(); obj->moreAction(); //etc... Is there any benefit of doing that, instead of simply doing: object obj; obj.action(); obj.moreAction(); //etc
Yes - you can store the pointer in a container or return it from the function and the object will not get destroyed when the pointer goes out of scope. Pointers are used to avoid unnecessary copying of object, to facilitate optional object creation, for custom object lifetime management, for creating complex graph-lik...
2,281,836
2,281,887
stl hash_map - modifying key
I have a hash map defined as class KeyType { int key; mutable bool flag; KeyType(int key) : key(key), flag(false) {} void setFlag() const { flag = true; } }; struct KeyType_hasher { size_t operator()(const KeyType& s) const { return static_cast<size_t> key; } }; struct KeyType_equal {...
You'd have to remove the element from the container and re-add it with the new key. None of the C++ associative containers support changing the key in a significant way (where significant means the change alters the results of the hash in a hashed container or the comparrsion in an ordered container). If you did modify...
2,281,899
2,284,459
Stencil Buffer Read/Write mask
In Direct3D10 the Stencil Read/Write mask is a byte (from 0x00 to 0xFF) In Direct3D9 the Stencil Read/Write mask is a int (from 0x00000000 to 0xFFFFFFFF) The question is : How the stencil read/write mask in Direct3D10 relate to the Direct3D9 one? Direct3D10 | 0x00FFFFFF or Direct3D10 | 0xFFFFFF00 ? And another question...
Direct3D10 | 0xFFFFFF00 The least significant bits are the relevant ones in D3D9, the docs describe the stencil operations in terms of DWORDs but ultimately the stencil buffer only stores a single byte so it is only the least significant byte of the mask that is important. The reason D3D9 uses a DWORD is that the value...
2,281,983
2,281,998
Class definition and memory allocation
If definition stands for assigning memory. How come a class definition in C++ has no memory assigned until an object is instantiated.
C++ Class definitions do not assign memory. class is like typedef and struct. Where did you get the idea that "definition stands for assigning memory"? Can you provide a quote or reference? C++ Object creation (via new) assigns memory.
2,282,287
2,286,090
Threaded rendering with NSOpenGLView
I have an old AGL-based OpenGL windowing system that I am updating to use NSOpenGLView. The engine using it needs to run in its own loop in a separate thread and I am having trouble getting that to work. With AGL, I created the context in the loop thread, so there was no issue, but I'm a little bit confused about the w...
Your separate thread can attach the NSOpenGLContext it creates to an existing NSOpenGLView by using the setOpenGLContext: method.
2,282,323
2,282,520
Problem with x64 application and ActiveX control
I have a small unmanaged c++ application, I'm trying to use CoCreateInstance(...) to create an instance of the "Adobe SVG PLayer" which is installed as an ActiveX control. When I compile and run my application under 32-bit configuration, it works fine, but when I compile under 64-bit configuration, my application fails...
I'm assuming that the ActiveX DLL you are trying to load is 32-bit only. Since ActiveX components are typically InProc, and 64 bit apps can't load in 32 bit DLLs, then you are correct about your guess. http://thermous.spaces.live.com/blog/cns!8DC85127F8CE2F12!161.entry
2,282,349
2,282,377
Specialization of 'template<class _Tp> struct std::less' in different namespace
I am specializing the 'less' (predicate) for a data type. The code looks like this: template<> struct std::less<DateTimeKey> { bool operator()(const DateTimeKey& k1, const DateTimeKey& k2) const { // Some code ... } }; When compiling (g++ 4.4.1 on Ubuntu 9.10), I get the error: Specialization of 'templa...
This is still the way to do it. Unfortunately you cannot declare or define functions within a namespace like you would do with a class: you need to actually wrap them in a namespace block.
2,282,427
2,282,589
Interesting Problem (Currency arbitrage)
Arbitrage is the process of using discrepancies in currency exchange values to earn profit. Consider a person who starts with some amount of currency X, goes through a series of exchanges and finally ends up with more amount of X(than he initially had). Given n currencies and a table (nxn) of exchange rates, devise an ...
Dijkstra's cannot be used here because there is no way to modify Dijkstra's to return the longest path, rather than the shortest. In general, the longest path problem is in fact NP-complete as you suspected, and is related to the Travelling Salesman Problem as you suggested. What you are looking for (as you know) is a ...
2,282,450
2,283,042
stable sorting QTreeWidgetItems in QTreeWidget?
I have a list of QTreeWidgetItems (with children) in a QTreeWidget. I do not use a model for my data. From another window in my application the user can navigate thru the same set of data (viewed differently) and the QTreeWidget in the first window then highlights that specific row by setting the background colour. How...
Are you using QItemSelectionModel to do this, or did you write it yourself? If you wrote it yourself I would suggest using QItemSelectionModel. If you didn't, it sounds like you want a custom sorting algorithm which would require creating a derived QTreeWidget, if you are doing that, you might as well just use QTreeVi...
2,282,549
2,283,038
C++: Getting incorrect file size
I'm using Linux and C++. I have a binary file with a size of 210732 bytes, but the size reported with seekg/tellg is 210728. I get the following information from ls-la, i.e., 210732 bytes: -rw-rw-r-- 1 pjs pjs 210732 Feb 17 10:25 output.osr And with the following code snippet, I get 210728: std::ifstream handle; hand...
At least for me with G++ 4.1 and 4.4 on 64-bit CentOS 5, the code below works as expected, i.e. the length the program prints out is the same as that returned by the stat() call. #include <iostream> #include <fstream> using namespace std; int main () { int length; ifstream is; is.open ("test.txt", ios::binary ...
2,282,702
2,282,736
What code should be written to accept Lower and Upper case choices?
I'm beginner to c++ and writing a program that accepts user choices and acts according to it...my only problem is when the user enters Uppercase choice...the program treats it as it's a wrong choice...like if 'e' was a choice for entering a number..if the user entered 'E' the program won't display the "enter the number...
If you don't break for a case in a switch statement that matches it will continue on to the next one. If you put the capital cases before each lower case choice it will fall through. switch (choice) { case 'E' : case 'e' : enter(); break ; case 'D' : case 'd' : display(); break ; case 'U' : ...
2,282,725
2,282,774
C++ : what is :: for?
If you go to the accepted answer of this post Could someone please elaborate on why he uses: double temp = ::atof(num.c_str()); and not simply double temp = atof(num.c_str()); Also, is it considered a good practice to use that syntax when you use "pure" global functions?
It says use the global version, not one declared in local scope. So if someone's declared an atof in your class, this'll be sure to use the global one. Have a look at Wikipedia on this subject: #include <iostream> using namespace std; int n = 12; // A global variable int main() { int n = 13; // A local varia...
2,282,735
2,283,932
DirectX9, DirectDraw, Optimization?
First off, I'm programming a game. Currently in the render function there are two calls to two different functions. One renders some text, one renders sprites. On my computer (AMD Phenom(tm) II X4 955 Processor (4 CPUs), ~3.2GHz, 4096MB RAM DDR2, NVIDIA GeForce GTX 285) I have a render speed of ~2200 FPS when rendering...
You need a profiler. There's some good performance advice in the responses, but it doesn't matter. Trying to optimize a program without a profiler is like trying to write a program without a compiler. Do not guess, measure. Now with that said, profiling graphics code is an infamous pain in the neck, and there aren't ...
2,282,802
2,282,851
Building RAPI.h in VS 2005, fail on open include file
this may sound too simple, but I'm missing something. I need to write a RAPI Windows Console app using C++. I'm currently using VS2005. I've created a brand new empty Windows Consol app "MyTestRAPI" from documentation, I know I need the include of the "RAPI.H" file. So, I've tried as #include <rapi.h> and also by ...
The "Common Properties" -> "References" field refers to .NET assembly references. To add a path to the C++ #include search path, you need to use "Configuration Properties" -> "C/C++" -> "General" -> "Additional Include Directories".
2,282,928
2,285,524
Schliemann's method of programming language learning
Background: 19th-century German archeologist Heinrich Schliemann was of course famous for his successful quest to find and excavate the city of Troy (an actual archeological site for the Troy of Homer's Iliad). However, he is just as famous for being an astonishing learner of languages - within the space of two years,...
Rosetta Code may be useful. To quote the site:- Rosetta Code is a programming chrestomathy site. The idea is to present solutions to the same task in as many different languages as possible, to demonstrate how languages are similar and different, and to aid a person with a grounding in one approach to a problem in lea...
2,283,428
2,303,670
WM_MOUSELEAVE not being generated when left mouse button is held
In my Win32 app, I don't get WM_MOUSELEAVE messages when I hold down the left mouse button and quickly move the mouse pointer out of the window. But If I, holding down the left mouse button, start from the inside of the window and move slowly past the window edge, it'll generate a WM_MOUSELEAVE. If I don't hold the le...
WM_MOUSELEAVE is so that you can detect the mouse leaving your window when you don't have capture. When you have capture, you are responsible for detecting that yourself (if you care). so It doesn't make any sense to SetCapture AND TrackMouseEvent at the same time, you would use one or the other. Now, if it would ...
2,283,490
2,283,971
Is there a limit to how big an xml file can be for tinyxml to parse it?
I have an xml file that is about 42k in size. Shouldn't tinyxml be able to parse a file of this size. Looking at the tinyxml source code, it appears to just read the entire file in as a char *. When I reduce the xml file in size to 7k, tinyxml works just fine. Is there a definitive limit to the # of bytes that tin...
If there's a limit, it's a lot bigger than that -- I've used it successfully on files over 100 megabytes.
2,283,508
2,283,548
Saving image as JPG -library?
I'd like to find a JPEG-writing library that can be statically linked (so there are no DLL dependencies). No JPEG-reading ability is required. Edit: I got LibGD working, but it had one problem described here: LibGD library is not working: crash when saving image
Have you looked at LibGD? I can't seem to find the license, but neither did you specify a requirement.
2,283,712
2,283,778
What header should I include for memcpy and realloc?
I am porting a project to the iPhone and it uses realloc and memcpy which are not found. What is the header to include? It's a project mixing Objective C and C++ and I am starting to be lost. Thanks in advance for your help!
In C: #include <string.h> // memcpy #include <stdlib.h> //realloc In C++, remove the .h and prefix with a c. In C++, they will be placed in the std namespace, but are also global.
2,283,828
2,284,165
c++ templates in an iPhone project
I am porting a project to the iPhone system and I am facing the following problem: I have an header containing c++ templates If I rename it to .mm, it does not compile (because it should be an header) and if I keep it as .h, it is interpreted as an objective C header Do you have a workaround to fix this issue? Thanks i...
Wrap it in #ifdef __cplusplus //templates here #endif This way, the templates will be silently ignored when the file is included in a C or Objective C (.m) source. You can also have some Objective C-only constructs wrapped in #ifdef __OBJC__ EDIT: you can, alternatively, rename your sources (not the header!) to .mm....
2,283,845
2,283,966
Which is the best data-structure for iterating through arrangements of a string?
Lets say, we have string "ABCAD", now we need to iterate through all possible arrangement of this string in both clockwise and counter-clockwise direction. My ugly implementation looks like this: string s = "ABCAD"; string t =""; for(int i = 0; i < sz(s); i++){ t = s[i]; for(int j = i+1; ; j++){ if((j) == ...
In pseudocode, I'd go this route: function rearrange (string s) { string t = s + s; for (int i = 0; i < length(s); ++i) print t.substring(i, length(s)); } input = "ABCAD" rearrange(input); rearrange(reverse(input)); There's probably a way to rewrite rearrange() using functors, but my STL-fu is rusty.
2,284,051
2,284,174
Qt installation error
i got an error when am trying to configure Qt. Erro : execute: File or path is not found (nmake) execute: File or path is not found (nmake) Cleaning qmake failed, return code -1 // installion files. InterBase...............no Sources are in..............E:\xampp\Qt\4.6 Build is done in............E...
If you are trying to build Qt with a Visual Studio enviroment, you have to make sure that nmake and cl are in the PATH. The easiest way to do that is to simply use the Visual Studio Command Prompt (found e.g. in the start menu).
2,284,086
2,284,124
Is there an automated way to merge C++ implementation(.cpp) and header (.h) files
I am trying to create a unit test framework using CPPUnit for a large code base. I need to be able to test individual modules, all of which are part of a module tree that begins with a specific root module. Due to a non-technical reason, I cannot touch the production file (my original approach involved adding an ifdef ...
This isn't a C++ question - you are asking how to manipulate files in some sort of script. The immediate answer that comes to mind is: cat foo.h foo.cpp > fooTest.h
2,284,112
2,284,163
Easiest way for a simple 3d app
A friend of mine asked for a simple program. Input: Coordinates of some points, spheres, planes etc. ( from an excel document (strictly) ) Output: A 3D view of the input which the user can move the camera. The questions is, how can I do that easiest way. I have experience in C++, C#, Flash (AS), Java
Input: Coordinates of some points, spheres, planes etc. ( from an excel document (strictly) ) This is going to be your major problem, reading an excel document from Flash is not an easy task. You will either have to process it on a server side script with XML/JSON/AMF output to the client, or simply give up on th...
2,284,275
2,284,308
C++ Array and Vector are hold values or references?
In C++ we have value type (int, long, float, ...) and reference type (class, struct, ...). For value type, Array and Vector hold the actual values; For reference type, Array and Vector only hold the references to these objects; So when we put reference type into Array and Vector, we need to make sure those objects wi...
No. Any type can be passed by value or by reference (also any type can be created on the stack or on the heap, though you didn't ask that). For any type Arrays and Vectors hold the actual values. Because of this any type stored in a vector needs to be copy-constructible. See 2. Nope. That's only the case if you explic...
2,284,428
2,284,548
In C++ networking, using select do I first have to listen() and accept()?
I'm trying to allow multiple clients to connect to a host using select. Will I have to connect each one, tell them to move to a different port, and then reconnect on a new port? Or will select allow me to connect multiple clients to the same port? This is the client code: int rv; int sockfd, numbytes; if ((rv = ...
TCP connections are identified by the IP address and port number of both ends of the connection. So it's fine to have lots of clients (which will generally have randomly assigned port numbers) to connect to a single server port. You create a socket and bind() it to a port on which to listen(), and then wait for clients...
2,284,610
2,284,616
What is __declspec and when do I need to use it?
I have seen instances of __declspec in the code that I am reading. What is it? And when would I need to use this construct?
This is a Microsoft specific extension to the C++ language which allows you to attribute a type or function with storage class information. Documentation __declspec (C++)
2,284,648
2,303,074
DLL and fully-specialized template class
Environment: Visual Studio 9, C++ without managed extensions. I've got a third-party library which exports a fully-specialized template class MyClass<42> defined in MyClass.h. It gets compiled into a helper loader .lib and a .dll file. The .lib file contains compiled code for this specialization, and necessary symbols....
It seems that for virtual methods it is necessary to define them as both extern and __declspec(dllimport) at the same time: extern template __declspec(dllimport) MyClass<42>::~MyClass<42>(); This made my linker happy enough to link my code properly. I would be very glad if some expert described why is so, or at least ...
2,284,707
2,287,711
DAO large query lockup on Win7 multicore
I have a C++ app that uses a Jet database through DAO. Large queries work well up through Vista but lockup under Win7 on a multicore machine. I have tried both jet 3.5 and 4.0. Both fail. I have tried disabling threads in calling prog (my app) - still fails.
Calling SetProcessAffinityMask(1<<GetCurrentProcessorNumber()) is a rather brute-force way of restricting yourself to the current core only. But it's of course better to use a debugger to determine why it locks up. Which two threads deadlock?
2,284,775
2,284,805
C++ can I reuse fstream to open and write multiple files?
I have 10 files need to be open for write in sequence. Can I have one fstream to do this? Do I need to do anything special (except flush()) in between each file or just call open(file1, fstream::out | std::ofstream::app) for a each file and close the stream at the end of all 10 files are written.
You will need to close it first, because calling open on an already open stream fails. (Which means the failbit flag is set to true). Note close() flushes, so you don't need to worry about that: std::ofstream file("1"); // ... file.close(); file.clear(); // clear flags file.open("2"); // ... // and so on Also note, y...
2,284,872
2,285,580
Parsing XML using libxml
I've got a small problem with parsing XML. I cannot get the name of a child node. Here's my XML code: <?xml version="1.1" encoding='UTF-8'?> <SceneObject> <ParticleSystem> </ParticleSystem> </SceneObject> Here's how I parse the XML file: SceneObject::SceneObject(const char *_loadFromXMLFile, const char *_childType) { ...
The "text" node is the whitespace (newline character) between <SceneObject> and <ParticleSystem> in your document. cur->children->next is the <ParticleSystem> node you want in this case. In general you can consult the type member of a node to determine whether it is an element, text, cdata, etc.
2,285,110
2,285,154
Restrict application to one instance per shell session on Windows
There are a lot of solutions for restricting an application from running twice. Searching by process name, using a named mutex etc. But I all of these methods don't work if I want to restrict my application to the shell session. A user may have more than login session and shell on windows (right?)? If this is true I wa...
You can create local (session only) or global (whole system) mutexes. See http://msdn.microsoft.com/en-us/library/system.threading.mutex.aspx for more info. Look for global and local.
2,285,375
2,305,626
Intel Thread Building Blocks Concurrent Queue: Using pop() over pop_if_present()
What is the difference in using the blocking call pop() as compared to, while(pop_if_present(...)) Which should be preferred over the other? And why? I am looking for a deeper understanding of the tradeoff between polling yourself as in the case of while(pop_if_present(...)) with respect to letting the system doing ...
Intel's TBB library is open source, so I took a look... It looks like pop_if_present() essentially checks if the queue is empty and returns immediately if it is. If not, it attempts to get the element on the top of the queue (which might fail, since another thread may have come along and taken it). If it misses, it per...
2,285,409
2,286,479
C++ urljoin equivalent
Python has a function urljoin that takes two URLs and concatenates them intelligently. Is there a library that provides a similar function in c++? urljoin documentation: http://docs.python.org/library/urlparse.html And python example: >>> urljoin('http://www.cwi.nl/%7Eguido/Python.html', 'FAQ.html') 'http://www.cwi.nl...
I figured it out. I used the library uriparser: http://uriparser.sourceforge.net/ and hastily implemented the function as follows. It does sparse error checking and may leak memory. std::string urljoin(std::string &base, std::string &relative) { UriParserStateA state; UriUriA uriOne; UriUriA uriTwo; ...
2,285,718
2,285,903
How do we typedef or redefine a templated nested class in the subclass?
Consider the following: template <typename T> class Base { public: template <typename U> class Nested { }; }; template <typename T> class Derived : public Base<T> { public: //How do we typedef of redefine Base<T>::Nested? using Base<T>::Nested; //This does not work using Base<T>::template<typen...
Actually using works as advertised, it just doesn't get rid of the dependent-name issue in the template and it can't currently alias templates directly (will be fixed in C++0x): template <class T> struct Base { template <class U> struct Nested {}; }; template <class T> struct Derived : Base<T> { using Base<T>:...
2,285,822
2,285,861
C++, what is a good way to hash array data?
I have a curious problem and I am brainstorming possible solutions. The problem is such: I have a number of inputs (up to several thousand different ones), which basically differ in two-three arrays (arrays are a different size generaly, from size one up to couple thousand elements long). the functions which process a...
Are these arrays integer? If yes, just go with something like this hash = (hash + (324723947 + a[i])) ^93485734985; Similar thing would work fine for strings if you do it on all characters. Finally, you may check out extra libs here
2,285,878
2,285,968
c++ elevating privileges on an .exe using OpenProcess()
I have been reading some of the books by Hoglund and I thought I would have a 'go' at his 'simple debugger'... Anyway, I have been trying to use the line hProcess = OpenProcess(PROCESS_ALL_ACCESS | PROCESS_VM_OPERATION, 0, aPID); Every time I use it on a running process hProcess is being returned as NULL, why is this ...
One possibility is given in MSDN: Windows Server 2003 and Windows XP/2000: The size of the PROCESS_ALL_ACCESS flag increased on Windows Server 2008 and Windows Vista. If an application compiled for Windows Server 2008 and Windows Vista is run on Windows Server 2003 or Windows XP/2000, the PROCESS_ALL_AC...
2,285,900
2,285,920
Read and write bytes from a file (c++)
I think I probably have to use an fstream object but i'm not sure how. Essentially I want to read in a file into a byte buffer, modify it, then rewrite these bytes to a file. So I just need to know how to do byte i/o.
#include <fstream> ifstream fileBuffer("input file path", ios::in|ios::binary); ofstream outputBuffer("output file path", ios::out|ios::binary); char input[1024]; char output[1024]; if (fileBuffer.is_open()) { fileBuffer.seekg(0, ios::beg); fileBuffer.getline(input, 1024); } // Modify output here. outputBuf...
2,285,915
2,285,934
non-static vs. static function and variable
I have one question about static and non-static function and variable. 1) non-static function access static variable. It's OK! class Bar { public: static int i; void nonStaticFunction() { Bar::i = 10; } }; int Bar::i=0; 2) non-static function access non-static variable Definitely OK! 3) ...
static function access non-static variable It's OK or not OK? I am puzzled about this! When called, a static function isn't bound to an instance of the class. Class instances (objects) are going to be the entities that hold the "non-static" variables. Therefore, from the static function, you won't be able to acce...
2,286,016
2,286,070
Why does c++ have its separate syntax for new & delete?
Why can't it just be regular function calls? New is essentially: malloc(sizeof(Foo)); Foo::Foo(); While delete is Foo:~Foo(); free(...); So why does new/delete end up having it's own syntax rather than being regular functions?
Here's a stab at it: The new operator calls the operator new() function. Similarly, the delete operator calls the operator delete() function (and similarly for the array versions). So why is this? Because the user is allowed to override operator new() but not the new operator (which is a keyword). You override opera...
2,286,130
2,286,170
Free Lightweight IDE/Text Editor for Windows - C++ Development
I have searched a lot for the exact development tool that fits my requirements, but could not find it anywhere. Here are my requirements: 1) Free. 2) Lightweight. (Eclipse is out). 3) Can handle a large project. 4) Input: Just the source tree, and possibly makefiles. No project/solution files. 5) Indexing - Auto Comple...
Try Code::Blocks Highlights: * Open Source! GPLv3, no hidden costs. * Cross-platform. Runs on Linux, Mac, Windows (uses wxWidgets). * Written in C++. No interpreted languages or proprietary libs needed. * Extensible through plugins Compiler: * Multiple compiler support: o GCC (MingW / GNU GCC) o MSVC++ ...
2,286,162
2,290,869
Classes, Static Methods, or Instance Methods - Memory Consumption and Executable Size in Compiled Languages?
I keep wondering about this to try to improve performance and size of my Flex swfs, how do classes vs. static methods vs. instance methods impact performance and the final compiled "executable's" size? Thinking how it might be possible to apply something like HAML and Sass to Flex... Say I am building a very large ad...
Couldn't find such information for Flex, but for Java (which shouldn't be too different), object creation overhead is only 8 bytes of memory. That means if we're talking about 1000 instances, the overhead of using objects for each instance is at most 8K - negligible. If 100x more, it's still 800K which is still nothin...
2,286,207
2,286,358
Templates vs. Action Hierarchy
I'm creating a button class and am having a hard time deciding between 2 solutions. 1) Templatize the Button class and have it take a function object in its constructor to call when the button is pressed. The guy I'm coding with is worried that this will lead to code bloat/thrashing. 2) Create a ButtonAction base class...
You could use boost::function<> objects for your actions. This way you don't need any templates and the button class becomes very flexible: struct Button { typedef boost::function<void ()> action_t; action_t action; Button(const action_t &a_action) : action(a_action) { } void click() { action(); ...
2,286,298
2,286,445
how to use processor registers in visual studio?
i'm trying to write a program that solves the rsa challenge (yes i have interesting goals) and currently i don't have a 64 bit linux box and i don't really wanna spend my time writing a program that doesn't have a chance to ever finish. so while i can do some assembler programming, i would prefer using C++. however, i ...
Based on your comment to BarsMonsters anser, you don't need to get closer to the CPU, you need a large integer library. One option is gmp, which includes arbitrary integer arithmetic. It has good algorithms for things like multiplying large integers, and a good compiler will do a better job of optimising this than most...
2,286,430
2,286,462
Inserting a std::list element to std::list
std::list <std::list <int>> mylist; std::list <int> mylist_; mylist_.push_back(0); mylist.push_back(mylist_); is it possible to insert a sub-list into the list (mylist) without creating the temporary local sub-list (mylist_) and would it be better to use the type (sub-list) as pointer in list (mylis...
You can't really do it without temporaries, but you can do it more concisely: mylist.push_back(std::list<int>(1, 0)); // insert 1 element with value 0 As JonM notes, the temporary will probably be optimized away by any decent compiler. You can use arrays: int vals[] = { 1, 2, 3, 4 }; mylist.push_back(std::list<int>(va...
2,286,640
2,286,918
Boost regular expressions
Does anyone know of any good tutorials on regular expressions using boost? I have been searching for a decent one, but it seems most are for people who know a little about regular expressions
You may want to look at sections 23.6, 23.7, 23.8, and 23.9 (pp. 830-849) of Bjarne's Stroustrup's new book: Programming: Principles and Practice using C++ Just like the rest of the book, these sections are very pedagogical and assume essentially zero background on regular expressions.
2,286,794
2,292,046
Network programming using C++
How can we do network programming in C++ similar to Remoting in .NET? Please help with any tutorials. It would be fine if I know how to enable two computers to communicate in the form of sending and receiving messages using C++/C#. Thanks, Rakesh.
Check out our C++ Remoting framework. There's also a screencast showing how to use it. This is probably the closest that you'll get to .NET Remoting in C++.
2,286,890
2,286,894
getting input numbers from the user
How can I get input from the user if they are to separate their inputs by whitespace (e.g. 1 2 3 4 5) and I want to put it in an array? Thanks. Hmmmm. I see most of the responses are using a vector which I guess I'll have to do research on. I thought there would be a more simpler, yet possibly messier response sinc...
#include <vector> #include <iostream> using namespace std; int main() { vector<int> num; int t; while (cin >> t) { num.push_back(t); } }
2,286,991
2,287,034
C++ Two Dimensional std::vector best practices
I am building an app that needs to have support for two dimensional arrays to hold a grid of data. I have a class Map that contains a 2d grid of data. I want to use vectors rather than arrays, and I was wondering what the best practices were for using 2d vectors. Should I have a vector of vectors of MapCells? or should...
When you want a square or 2d grid, do something similar to what the compiler does for multidimensional arrays (real ones, not an array of pointers to arrays) and store a single large array which you index correctly. Example using the Matrix class below: struct Map { private: Matrix<MapCell> cells; public: void loa...
2,287,114
2,287,187
Thread type for background drawing to a bitmap in MFC
I have a MFC document/view C++ graphics application that does all its drawing to an off screen bitmap, and then copys that to the supplied CDC pointer in the OnDraw method. Over the last couple of days I've been looking to place the drawing component in a seperate worker thread, so it doesn't stall the GUI. I seem to...
Device contexts can be used by any thread (the only thing you must be aware of is that the thread which did the GetDC should also call ReleaseDC), but are not inherently thread safe. You have to ensure that only one caller is accessing the DC at any given point in time, but you seem to have taken care of that, from wha...
2,287,121
2,287,145
How to read groups of integers from a file, line by line in C++
I have a text file with on every line one or more integers, seperated by a space. How can I in an elegant way read this with C++? If I would not care about the lines I could use cin >>, but it matters on which line integers are. Example input: 1213 153 15 155 84 866 89 48 12 12 12 58 12
It depends on whether you want to do it in a line by line basis or as a full set. For the whole file into a vector of integers: int main() { std::vector<int> v( std::istream_iterator<int>(std::cin), std::istream_iterator<int>() ); } If you want to deal in a line per line basis: int main() { ...
2,287,212
2,287,232
How to convert UTF-8 <-> UTF16 portable
is there a simple, portable way (win32, linux at least) to convert UTF-16 to UTF-8 and back? Preferably using boost. Thx for your help, Tobias
Both libiconv and icu can do this.
2,287,318
2,287,393
Using C++/Qt4 application as backend for web application
for one of my applications I'd like to provide a minimal web interface. This core application is written in C++ and uses Qt4 as a framework. Since I'm also using some libraries I wrote to calculate some things and do some complex data management, I'd like to use this existing code as a backend to the web interface. Ide...
I would never expose a custom written application to the net as front-end, for that servers like apache or lighthttp are build. They give you some serious security out of the box. As for interaction of your app with that webserver, it depends a bit on the load and what kind of experience you have with writing software ...
2,287,442
2,287,458
Use of Mutex between a c# exe and an c++ dll
Is it possible to use a Mutex Object for a application which users c++ dll to do background work and a c# to display it. Bot these use a common resource ie db . So can Mutex be used to lock this resource. In my db c++ will insert to db and c# will read it.
There is a thing called "named mutex", which is OS object and can be shared between different libraries and applications, only by specifying its name on creation/use.Refer to http://msdn.microsoft.com/en-us/library/ms682411%28VS.85%29.aspx
2,287,451
4,684,224
How to perform atomic operations on Linux that work on x86, arm, GCC and icc?
Every Modern OS provides today some atomic operations: Windows has Interlocked* API FreeBSD has <machine/atomic.h> Solaris has <atomic.h> Mac OS X has <libkern/OSAtomic.h> Anything like that for Linux? I need it to work on most Linux supported platforms including: x86, x86_64 and arm. I need it to work on at least...
Projects are using this: http://packages.debian.org/source/sid/libatomic-ops If you want simple operations such as CAS, can't you just just use the arch-specific implementations out of the kernel, and do arch checks in user-space with autotools/cmake? As far as licensing goes, although the kernel is GPL, I think it's a...
2,287,506
2,287,626
Getting location of a file: network or local
What is the easiest way in Windows to get the location of a file? I have a filename that was returned to me by the Windows function GetModuleName (returns the full name of a module (exe or dll)), and which could be in any valid filename format, e.g. myfile.dll c:\windows\myfile.dll \?\c:\windows\myfile.dll (or somethi...
GetFullPathName() will help normalize the path name. I don't think you need it though. You'd want to go through the handle. So call CreateFile(), get a handle, then call e.g. GetFinalPathNameByHandle(VOLUME_NAME_GUID) This works because network drives don't have volume GUIDs.