question_id
int64
25
74.7M
answer_id
int64
332
74.7M
title
stringlengths
20
150
question
stringlengths
23
4.1k
answer
stringlengths
20
4.1k
3,809,033
3,813,314
Compiling libpng and using it with netbeans and mingw
I have only previously used visual studio for developing c++ but I've just moved to netbeans and am having some issues. I got mingw installed so that my projects will compile but I dont know how to add external libraries to that. I want to use a static library, not a dll. The library I specifically am looking at is lib...
I figured it out more or less. I used the cmake gui, configured for msys make and mingw g++ and gcc, on the zlib source directory and then ran msys make and make install on the output directory. After that I did the same on libpng, but I had to add some variables to point to the zlib include and library directories wit...
3,809,062
3,809,091
Formatting columns in C++
I have the following program that generates a multiplication table. A formatting problem arises when the outputs reach the double digits. How do I straighten out the columns? #include <iostream> using namespace std ; int main() { while (1 != 2) { int column, row, c, r, co, ro; cout << endl ; cout...
use the setw output manipulator: cout << setw(3) << temp[c]; By default, this uses spaces to fill, which it looks like you want. You will need to include iomanip as the documentation says.
3,809,103
3,809,186
I need a container that supports efficient random access and O(k) insertion and removal
I have tried again to ask the same question, but I ended up asking a different question by not providing essential information about my problem. I implement a data structure which is a tree. Each node of this tree has an array/vector/(random access structure) with all its children which can be arbitrary many. The inser...
From the description you gave of the tree structure you are implementing, it might be best to create a new data structure to mimic your tree. Especially if you're already tracking pointers between nodes. If I understand your statement, each node in your tree would contain a vector of children node pointers. When you ne...
3,809,415
3,809,420
How do C++ operators work
Given that x = 2, y = 1, and z = 0, what will the following statement display? printf("answer = %d\n", (x || !y && z)); It was on a quiz and I got it wrong, I don't remember my professor covering this, someone enlighten me please... I know the answer I get is 1, but why?
The expression is interpreted as x || (!y &&z)(check out the precedence of the operators ||, ! and &&. || is a short-circuiting operator. If the left operand is true (in case of ||) the right side operand need not be evaluated. In your case x is true, so being a boolean expression the result would be 1. EDIT. The orde...
3,809,489
3,810,158
Binary * Operator Not Found
I have a vector class with a properly overloaded Vect*float operator and am trying to create the global/non-member float*Vect operator as follows: (Note this is a heavily edited sample) class Vect { public: Vect::Vect(const float p_x, const float p_y, const float p_z, const float p_w); Vect operator...
The final solution was to go with a friend function because the variables were in p_vect were private: //class definition friend Vect operator*(const float scale, const Vect& p_vect); //function Vect operator*(const float p_sclr, const Vect& p_vect) { return Vect( (p_vect.x * p_sclr), (p_vect.y * p_sclr), (p_vect.z...
3,809,530
3,809,561
Copy Constructor Being Called on the Wrong Object
I'm currently implementing a copy constructor for a Linked List class. When I create a new instance of the class with another Linked List as a parameter, the constructor is being called for the object I'm passing as the parameter. This is leaving me confused beyond belief. Here is the section necessary to understand wh...
LinkedList ll = LinkedList(); This creates a linked list instance, and this instance is then copy constructed. This looks like a Java or C#-ism. It is actually equivalent to: LinkedList ll(LinkedList()); To create an empty linked list, simply write: LinkedList ll; This will implicitly call the default constructor. A...
3,809,671
3,809,679
Meaning of this #pragma notation
What could be the meaning of this notation. #pragma warning( disable : 4530 )
Quite naturally, it disables warning number 4530.
3,809,740
3,809,794
Behaviour of Delete in C++ on cast
I am working on some strange piece of code ,For me its not good piece of code. PIP_ADAPTER_INFO pAdapterInfo=(PIP_ADAPTER_INFO)new char[sizeof(IP_IP_ADAPTER_INFO)]; . . . delete []pAdapterInfo; Here PIP_ADAPTER_INFO is pointer to struct IP_IP_ADAPTER_INFO , size of IP_IP_ADAPTER_INFO ...
I'm assuming here that by IP_IP_ADAPTER_INFO you mean Windows' IP_ADAPTER_INFO structure. Even if not, the gist of this is the same: your code is leading to undefined behaviour, and it's the fault of whoever wrote it. Fix it immediately. You allocated an array of char with new, but then free that memory as if it were a...
3,809,874
3,809,890
C++0x template function object inference
I'm a Scala/Java programmer looking to reintroduce myself to C++ and learn some of the exciting features in C++0x. I wanted to start by designing my own slightly functional collections library, based on Scala's collections, so that I could get a solid understanding of templates. The problem I'm running into is that the...
You can make the operator() a template too class Print { public: template<typename T> void operator()(T elem) { cout<<elem<<endl; } }; Then you can pass Print(). For passing arguments like in ArrayBuffer<decltype(fn(T()))> I recommend using declval, so you could also work with non-default constructible T A...
3,809,937
3,830,444
C++ CORBA DII issues
Could all those CORBA experts out there please help me with this one. I have a multithreaded application with some code that sends a message to a server and waits for a response back. I can see that the server is sending the response back however the application doesnt seem to receive it. Heres part of my code. // Cr...
Managed to fix by changing object reference from _ptr to _var. I wrote a small test application to verify this. After changing the pointer type its behaving as expected serving the responses. So the problem was getting the initial reference to the interface.
3,810,157
3,815,021
dlclose() does not call the destructor of global objects
plugin1.cpp: #include <iostream> static class TestStatic { public: TestStatic() { std::cout << "TestStatic create" << std::endl; } ~TestStatic() { std::cout << "TestStatic destroy" << std::endl; } } test_static; host.cpp #include <dlfcn.h> #include <iostream> int main(int argc,char *argv[]) { voi...
The C++ Standard requires that destructors be called for global objects when a program exits in the opposite order of construction. Most implementations have handled this by calling the C library atexit routine to register the destructors. This is problematic because the 1999 C Standard only requires that the implemen...
3,810,269
3,817,419
Templates :Name resolution:Point of instantiation: -->can any one tell some more examples for this statement?
This is the statement from ISO C++ Standard 14.6.4.1 Point of instantiation For a function template specialization, a member function template specialization, or a specialization for a member function or static data member of a class template, if the specialization is implicitly instantiated because it...
I find this quite mind-screwing, and the committee has more such fun. So I think it's likely I have some errors in the below. So please read it with care :) Third paragraph For a class template specialization, a class member template specialization, or a specialization for a class member of a class template, if the sp...
3,810,281
3,810,522
Name resolution and Point of instantiation in Templates
This is the statement from ISO C++ Standard 14.6.4.1 Point of instantiation 4.If a virtual function is implicitly instantiated, its point of instantiation is immediately following the point of instantiation of its enclosing class template specialization. 5.An explicit instantiation directive is an instantiatio...
The first two statements explain where the instantiation point of certain template constructs are; it doesn't introduce new template constructs. So you can reuse your previous examples. The third statement (14.6.4.1/6) tells us what the point of instantiation points is: they are the point where names are looked up duri...
3,810,440
3,810,461
(C++) Whole class in .h file?
If I am creating a class with small functions that don't do much, is it acceptable to just put them all into the header file? So for a particular class, it's only just the .h with no .cpp to go with it.
Yes, that's acceptable. It will certainly compile. But also, if it makes the code organization cleaner, then that can be good. Most template definitions are already like this out of necessity, so you aren't doing anything unheard of. There can be some drawbacks of that class relies on other classes though. If you end u...
3,810,519
3,810,622
How to use a lambda expression as a template parameter?
How to use lambda expression as a template parameter? E.g. as a comparison class initializing a std::set. The following solution should work, as lambda expression merely creates an anonymous struct, which should be appropriate as a template parameter. However, a lot of errors are spawned. Code example: struct A {int x;...
The 2nd template parameter of std::set expects a type, not an expression, so it is just you are using it wrongly. You could create the set like this: auto comp = [](const A& lhs, const A& rhs) -> bool { return lhs.x < rhs.x; }; auto SetOfA = std::set <A, decltype(comp)> (comp);
3,810,658
3,810,686
Initialize pointer to pointer using multiple address operators in C or C++
It just occurred to me That I don't know how to initialize a pointer to pointer from a non pointer value with one statement in C++: int a = 1; int** ppa = &&a; //Does not compile int** ppa = &(&a); //Does not compile int* pa = &a; //Works but is a int** ppa = &pa; //Two step solution Am I missing something, is the t...
if you want a pointer to a pointer, the pointer that you want to point to must be located somewhere in memory, so I think there cannot be a "one step solution" because you need a pointer variable that you can point to. (Note: This sentence is not meant to be a linguistic trial to use "point" as often as possible in one...
3,810,696
3,810,975
CMake and absolute header paths
I'm trying to use CMake to build my C++ project and I have a problem in the header paths. Since I'm using a lot of classes organized in several directories, all my include statements are with absolute paths (so no need to use "../../") but when try to make the CMake-generated Makefile it just doesn't work. Does anyone ...
You need something like this in CMakeLists.txt: SET(BASEPATH "${CMAKE_SOURCE_DIR}") INCLUDE_DIRECTORIES("${BASEPATH}")
3,810,794
3,810,862
c++ factory and casting issue
I have a project where I have a lot of related Info classes and I was considering putting up a hierarchy by having a AbstractInfo class and then a bunch of derived classes, overriding the implementations of AbstractInfo as necessary. However it turns out that in C++ using the AbstractInfo class to then create one of t...
You don't require downcasting. See this example: class AbstractInfo { public: virtual ~AbstractInfo() {} virtual void f() = 0; }; class ConcreteInfo1 : public AbstractInfo { public: void f() { cout<<"Info1::f()\n"; } }; class ConcreteInfo2 : public AbstractInfo { public: void f() {...
3,810,824
3,810,978
Difference b/w Objective C's self and C++'s this?
can someone tell the difference between objective C's self and C++ this pointer?
The main difference is that this is a keyword, while self is a variable. The result of this is that while this always refers to the object that is executing a particular method, Objective-C methods are free to modify self during execution. This is sometimes used by constructors, which set self = nil on failure. The rea...
3,811,052
3,811,150
how to get drives letters which are available (not in use) in MFC?
how to get drives letters which are available (not in use) in MFC using C++ ? Any code snippet..
Your probably after GetLogicalDrives, this gives you a bit mask of all the drive letters in use by the system, it'll be up to you to convert these to letters and add them into the combo box To make it a little more clear: Return Value If the function succeeds, the return value is a bitmask representing the currently ...
3,811,125
3,811,717
What happens when windows encounters an unknown instruction in a binary?
We have a binary compiled with SSE3 optimizations which end up using the instruction LDDQU. Now when this code is executed on a Windows system (Single core, XP2) which has only SSE1,2 support (as seen through CPU-Z tool) then application crashes. (924.4f0): Invalid lock sequence - code c000001e (first chance) ... 001...
An application is compiled with SSE3 support and crashes when run on a CPU not supporting SSE3. Gee, so strange! Compiler options for choosing an instruction set must be there just because some programmer at Microsoft was bored as hell one day. You have several options: make a single version of the application using S...
3,811,132
3,811,186
Why should I check the return value of operator NEW?
Meyers in his book "50 ways to improve..." second edition writes that I must check return type of new, but I know that if operator NEW can't allocate memory it throws exception, so with newer libraries I don't need to check return value of new, am I right? thanks in advance
In general, I think you're correct: the modern libraries usually throw exceptions for this. But if you're distributing source, some compilers still return NULL rather than throwing an exception. In those situations, it can be useful, but it really depends whether you're going to be there to debug it and how critical th...
3,811,136
3,811,873
Write a program to count how many times each distinct word appears in its input
This is a question(3-3) in accelerated C++. I am new to C++. I have thought about this for a long time, however, I can't figure it out. Will anyone resolve this problem for me? Please explain it in detail, you know I am not very good at programming. Tell me the meaning of the variables you use.
The best data structure for this is something like a std::map<std::string,unsigned>, but you don't encounter maps until chapter 7. Here are some hints based on the contents of chapter 3: You can put strings in a vector, so you can have std::vector<std::string> Strings can be compared, so std::sort works with std::vect...
3,811,151
3,811,220
Injecting code in a C++ base class constructor
I'm deriving a class which is available from a C++ library, and the constructor of my subclass will only work properly when I execute some code before the base class constructor gets called. (Yes, I know, bad design, but I cannot influence how the library which I'm using works.) If the base class constructor takes argu...
You have a case of "Base from member initialization". A solution is there.
3,811,328
3,811,461
Try to write char[] to a text file
I trying to write a char[256] to a text file. Below is my current work: fstream ofs; ofs.open("c:\\myURL.txt"); ofs.write((char*)testDest,256); ofs.close(); It still does not work. here is the error: error C2440: 'type cast' : cannot convert from '' to 'char *' update: so far, here...
Several things wrong or "not good" in your code: You never check if the open fails. You use clunky write functions. You don't check if your write is succesful (not quite necessary if you're kind of sure it will work). This will give you more info if something fails: #include <fstream> using std::ofstream; #includ...
3,811,415
3,812,007
How to create a COM DLL (class library)?
I have an existing COM DLL (class library), originally written in VB6 and source code now lost. I need to very quickly rewrite to make a minor tweak it and don't have access to VB6. I understand that C++ Express 2008 will let me create the DLL, but I get bogged down ATL and the like. Is there a really simple step by st...
View these links they may be helpful to you. http://edn.embarcadero.com/article/23185 http://www.informit.com/articles/article.aspx?p=130494 http://delphi.about.com/od/comoleactivex/a/comdelphi.htm
3,811,424
3,811,441
Default class inheritance access
Suppose I have a base and derived class: class Base { public: virtual void Do(); } class Derived:Base { public: virtual void Do(); } int main() { Derived sth; sth.Do(); // calls Derived::Do OK sth.Base::Do(); // ERROR; not calls Based::Do } as seen I wish to access Base::Do through Deriv...
You might have read something incomplete or misleading. To quote Bjarne Stroustrup from "The C++ programming Language", fourth Ed., p. 602: In a class, members are by default private; in a struct, members are by default public (§16.2.4). This also holds for members inherited without access level specifier. A widesp...
3,811,440
3,811,521
What is the difference between sizeof(int) and sizeof(int*)? Also Is this statement int* numbers[] = {....} correct?
Suppose, int numbers [20]; int * p; I think this is statement is valid p = numbers; But this is not numbers = p; Because numbers is an array, operates as a constant pointer, and we cannot assign values to constants. So if we go by this then we cannot use *numbers while initializing the array?
int numbers [20]; int * p; I think this is statement is valid p = numbers; Yes But this is not numbers = p; Because numbers is an array, operates as a constant pointer, and we cannot assign values to constants. numbers is not a constant pointer, it is a non modifiable lvalue so you cannot assign to it. sizeof(int) ...
3,811,539
3,811,591
Can I call CUDA runtime function from C++ code not compiled by nvcc?
Is there any way I can call CUDA runtime function calls such as cudaMemcpy(...); in a .cpp file, compiled with a regular C++ compiler?
EDIT: There was an example here but it's not longer found, but most of the example was copied below. The caller C (but could be C++) #include <stdio.h> #include <stdlib.h> #include <string.h> #include <cuda.h> extern void kernel_wrapper(int *a, int *b); int main(int argc, char *argv[]) { int a = 2; int b = 3; ...
3,811,540
3,811,683
Restricting template instantiation using is_integral / BOOST_STATIC_ASSERT
I am trying to implement a free operator function in order to stream values of arbitrary data type into some container class (DataVector). I did a template for basic data types and some specializations for the complex data types used in my project (examples covers std::string only). To make sure the template won't be u...
I am no expert on boost, but from the look of it BOOST_STATIC_ASSERT(0) will compile even if the boost::is_integral<T>::value returns true (similar all other normal functions). Hence you get the compiler error (as intended when static assert's condition returns false). To fix this, the simplest would be change the the ...
3,811,604
3,811,625
Can't build sigqueue example with gcc but g++ is ok?
I have a strange build problem. I have a simple test program that sends a sigqueue to another process. This little code example builds and runs when I build it as a c++ program (compiled with g++) but when I compile it as a c program (with gcc) I get a error that he can't find the sigval struct. The short example: #in...
In C, struct and union tags do not introduce names that can be used on their own like they do in C++. You must spell it out: union sigval value;
3,811,645
3,811,722
Program won't run with really big numbers
I'm pretty new to programming and so I"m making this program in C++ that will take a number and find it's prime factors, which works great! Unless it's too big for an int variable. Now then I tried to change all of the int variables to long long variables so it wouldn't matter, but this doesn't seem to fix the problem....
I'm willing to be that your program IS running. I'm sure that someone is going to pop on and give you the answer in a heartbeat, but I'm hoping that it doesn't happen so that you get to experience the same thing that I did when I ran into the problem YEARS ago. Do this: start with 1, and work up from there using powers...
3,811,653
3,818,102
Is there a standard Cyclic Integer Class in C++?
I have a problem that is quite common in the code that I am writing at the moment whereby I want to have an integer that can only exist inside a certain range where the range is [start, end). Basically I want to be able to do something like the following: cyclic_int ci(4, 8); ci = 4; assert(ci == 4); ci += 3; assert(c...
I never used it and it is not yet an official Boost library, but Boost.ConstrainedValue has a wrapping_int that looks very similar to what you're looking for. Although it is not yet a part of Boost, it was reviewed and, IIUC, conditionally accepted recently: http://lists.boost.org/boost-announce/2010/09/0265.php The l...
3,811,740
3,811,882
freeing memory issue
I have an issue regarding freeing memory as under: string points; // some points sequences char* charPoints = (char*)malloc((points.length() +1) * sizeof(char)); //do something free(charPoints); Even then after freeing memory is leaked when checked with instruments
The pointer you pass to free must be the same one which returned by malloc. If you pass a different pointer it will result in a undefined behavior. Take a copy of the pointer before you do the operation such as incrementing the charPoints and then pass this original pointer to free function to properly release memory.
3,812,405
3,812,592
Lightest synchronization primitive for worker thread queue
I am about to implement a worker thread with work item queuing, and while I was thinking about the problem, I wanted to know if I'm doing the best thing. The thread in question will have to have some thread local data (preinitialized at construction) and will loop on work items until some condition will be met. pseudoc...
There are a multitude of ways to do this. One option is to use a semaphore for the waiting. The semaphore is signalled every time a value is pushed on the queue, so the worker thread will only block if there are no items in the queue. This will still require separate synchronization on the queue itself. A second option...
3,812,927
3,813,257
What's the bestway to include "third party" headers to your C++ project
I'm building a bunch of windows libraries (mostly simple wrappers to compine features from API and third party libraries) to be consumed later by set of applications which have very similar requirements. Most of libraries are depending from another library and all of them are depending from one common library. This com...
If the libraries are project specific, you will want to install the libraries in a well-known location (/project/$FOO/ or D:\projects\$FOO) and add a version number to the directory because sooner or later you'll end up supporting a development trunk and a couple of older releases that are in production and just need o...
3,813,013
3,813,156
C++ - QSettings question
Does Qt has something like QSettings, but for local scopes? I am seeking for a data structure with the same methods, but not specific for APPLICATION. I mean, I want to construct local (for example, exporting settings) settings from file (xml, for example) and use them in local scope - without polluting global applic...
You can use void QSettings::setPath ( Format format, Scope scope, const QString & path ) to set the format (as specified in the doc) QSettings::NativeFormat 0 Store the settings using the most appropriate storage format for the platform. On Windows, this means the system registry; on Mac OS X, this means t...
3,813,075
3,813,086
Is it bad practice to use C features in C++?
For example printf instead of cout, scanf instead of cin, using #define macros, etc?
I wouldn't say bad as it will depend on the personal choice. My policy is when there is a type-safe alternatives is available in C++, use them as it will reduce the errors in the code.
3,813,124
51,239,423
C++ vector max_size();
On 32 bit System. std::vector<char>::max_size() returns 232-1, size of char — 1 byte std::vector<int>::max_size() returns 230-1, size of int — 4 byte std::vector<double>::max_size() returns 229-1, size of double — 8 byte can anyone tell me max_size() depends on what? and what will be the return value of max_size() if...
Simply get the answer by std::vector<dataType> v; std::cout << v.max_size(); Or we can get the answer by (2^nativePointerBitWidth)/sizeof(dataType) - 1. For example, on a 64 bit system, long long is (typically) 8 bytes wide, so we have (2^64)/8 - 1 == 2305843009213693951.
3,813,138
3,813,166
void* or char* for generic buffer representation?
I'm designing a Buffer class whose purpose is to represent a chunk of memory. My underlying buffer is a char* (well, a boost::shared_array<char> actually, but it doesn't really matter). I'm stuck at deciding what prototype to choose for my constructor: Should I go with: Buffer(const void* buf, size_t buflen); Or with:...
API interface is more clear for user, if buffer has void* type, and string has char* type. Compare memcpy and strcpy function definitions.
3,813,377
3,813,507
Use unit tests in unusual architecture when porting from VS6 to VS2008?
we have one main application, which executes up to 5 different exes. These exes run independently and communicate with each other via UDP. Changing this architecture is not planned at the moment. We want to migrate this whole thing from VS6 to VS2008. I'm thinking about adding unit tests to make sure that after migrati...
If they communicate via UDP and you want to make sure the integration between pieces works now and later, you could write automated tests against the UDP interfaces in MSTest or NUnit in VS2008. Write the tests in VS2008 and send input/verify output of the interfaces to the the .exe applications. Then, when you switch...
3,813,492
3,813,751
Unix timestamp to XML date time conversion
Is there any C++ Library api available which converts Unix timestamp to XML datatype datetime eg : http://books.xmlschemata.org/relaxng/ch19-77049.html I am looking to convert into pattern : 2001-10-26T19:32:52+00:00 I also have access to mysql, so I can get hold of : mysql> select now(); +---------------------+ | n...
You could use the strftime() function from <time.h>: char time_buf[21]; time_t now; time(&now); strftime(time_buf, 21, "%Y-%m-%dT%H:%M:%SZ", gmtime(&now));
3,813,910
3,813,931
Boost Smart Pointers and threading
If you have to pass objects across threads which smart pointer type is best to use? Assuming the object being passed is thread safe.
A shared_ptr would work for sharing data. Its counter is atomic, so you won't run into problems there, and when the last thread is done it goes away.
3,813,916
3,814,402
Simultaneus development in Visual Studio and a Linux IDE
I am trying to get started with an existing open source project (QuantLib) using Linux operating system. However it seems that most developers use Visual Studio (judging from the project files committed with the source). Which Linux C++ IDE would be most compatible with VS project files? Is there a way to import/expor...
In my experience, the best method for doing dual-development on Linux & Windows is to throw away the existing Visual Studio project files and, instead, use CMake to generate the platform-specific build environment. It's capable of outputting Nmake makefiles (for command-line Windows builds), Visual Studio projects, and...
3,813,923
3,813,952
How to insert a pair of std::pair inside another std::pair?
I'm declaring a map of string to a pair of pairs as follow: std::map<std::wstring, std::pair<std::pair<long, long>, std::pair<long, long>>> reference; And I initialize it as: reference.insert(L"First", std::pair<std::pair<long, long>, std::pai...
The >>> can not be parsed correctly (unless you have a C++0x compiler). Change to > > > This: reference.insert("First", Should be: reference.insert(L"First", ^^^ Also there is a utility function to make the construction of pairs easier: std::pair<std::pair<long, long>, std::pair<long, long>>(std::pair...
3,813,964
3,839,259
Cant copy construction be done without creating an explicit function in the pure virtual base class?
My objective is to do a deep copy of a class, but a virtual class is causing trouble. #include<iostream> using namespace std; class Vir//pure virtual class { public: virtual void hi()=0; }; class Handler:public Vir { public: int i; Handler() {} Handler(int val):i(val) {} void hi() {cout<<"...
Maybe I am missing something but would you not be better with a virtual clone method on Vir? This means you can avoid the nasty cast in the ControlPanel copy constructor outlined in your own answer. This is the same as @Andrew Aylett suggests in his answer with duplicate being used instead of clone. Something like clas...
3,814,188
3,814,257
How to optimize merge sort?
I've two files of 1 GB each containing only numbers in sorted order. Now I know how to read the contents of the files and sort them using merge sort algorithm and output it into an another file but what I'm interested is to how to do this only using 100MB buffer size (I do not worry about the scratch space). For exampl...
Sounds like you only need to merge the numbers in your files, not sort them, since they're already sorted in each file. The merge part of merge sort is this: function merge(left,right) var list result while length(left) > 0 or length(right) > 0 if length(left) > 0 and length(right) > 0 if fi...
3,814,282
3,814,309
Should I use structs in C++?
The difference between struct and class is small in C++, basically only that struct members are per default public and class members are per default private. However, I still use structs whenever I need pure data structures, for instance: struct Rectangle { int width; int height; }; I find that very convenient...
No. If it makes sense to use a struct somewhere, why would you complicate things using something else that isn't meant to fit the purpose ? In my projects, I tend to use struct for simple "structures" which just need to hold some trivial data. If a data structure needs to have some "smartness" and hidden fields/methods...
3,814,349
3,814,487
C++: How to modify a files 'created' timestamp?
I need to modify the 'created' (if exists), 'modified' and 'accessed' timestamps of a file. Ideally this would be a platform-independent solution. I've looked around the boost libraries but I can't see anything relevant. The nearest I've found to something relevant is this for Windows. Can anyone help? Thanks.
I've never used them but i guess that you are looking for the attribute functions: http://www.boost.org/doc/libs/1_44_0/libs/filesystem/v2/doc/reference.html#Attribute-functions There are also functions for the last modification: template <class Path> std::time_t last_write_time(const Path& p); template <class Path...
3,814,425
3,814,582
COM + WaitForSingleObject
I've been trying to find a good architecture for one application for the last few days, and after some research I'm finally stuck, and the reason is COM. The app in question will have multiple GUI threads, and they will schedule work items for worker thread. The worker thread will initialize COM via CoInitialize(NULL);...
Seems like overkill, but this worked for me : int waitAndDispatch( HANDLE* event_handle, unsigned int ev_count, DWORD timeout ) { int rval = -1; bool bLoop = true; // if the loop should terminate HANDLE* pHList = new HANDLE[ev_count]; for( unsigned int i = 0; i < ev_count; ++i ) { ...
3,814,443
3,824,962
Referencing a dll in Java
I need to reference a C++ dll from my Java project. The method that I need to expose is actually written in Visual Basic. Is there any way to access the Visual Basic code in C++, so that it can eventually be accessed in the Java project?
jmac posted the original question on my behalf. I needed to find a way to call VB DLL function from a C++ DLL. I've given up on the VB DLL and opted for a C# DLL. The following link provides a downloadable Visual Studio solution that provides a project called DLLExporter that exports C# functions thus making them a...
3,814,727
3,814,794
Extending vector iterator to fill my needs
I have the following design in one of my projects: template<typename C> class B { int numValue; C inner; } template<typename C> class A { vector<B<C>> container; ... Iterator InsertItem(C item) {...} } What I want is a way to modify the existing vector iterator to return an Iterator which will ret...
If your iterator returns &inner, how will you ever access numValue? If you create your own A::iterator, it should be easy to have it contain a vector<B<C>>::iterator and forward most operations through it. Yes you'll need a full iterator class implementation, but it won't be difficult at all.
3,814,861
3,814,871
Errors with 'this' pointer
I'm having a problem with the this pointer inside of a custom class. My code looks as follows. class Foo{ public: void bar(); bool baz(); }; bool Foo::baz(){ return true; } void Foo::bar(){ bool is_baz = (*this).baz(); } As I said above, I believe the error I'm getting (LNK2019) is coming from the this. ...
class Foo(){ Change this to class Foo{ Also, this shouldn’t compile. How did you manage to get a link error? After making this change, the linker says undefined reference to 'main', which just means you don't have a main function.
3,814,865
3,815,055
What is an "operator int" function?
What is the "operator int" function below? What does it do? class INT { int a; public: INT(int ix = 0) { a = ix; } /* Starting here: */ operator int() { return a; } /* End */ INT operator ++(int) { return a++; } };
The bolded code is a conversion operator. (AKA cast operator) It gives you a way to convert from your custom INT type to another type (in this case, int) without having to call a special conversion function explicitly. For example, with the convert operator, this code will compile: INT i(1234); int i_2 = i; // this wil...
3,814,969
3,814,986
Segmentation fault using FastDelegate
I've got a problem with my test code. It compiles well, but when I try to call delegate, program crashes. #include "..\libs\FastDelegate\FastDelegate.h" #include <string> #include <map> #include <iostream> typedef fastdelegate::FastDelegate1 <int, int> FuncPtr; struct Function { FuncPtr Ptr; int Param; Function() ...
RegisterFunction ("Foo", Function(&foo, 1)); ^ capital F ExternalFuncs ["foo"] (5); ^ lowercase f Since there is no element in the map with the key "foo", ExternalFuncs["foo"] default constructs a new Function, inserts that default constructed object into the map, and returns a ref...
3,815,554
3,815,592
c / c++ disable access to files
Is it possible to disable access of some program to files completely? Because I don't want it to have any kind of access to files on system, is it possible to compile it so it doesn't have access to file stream or to run it someway it cant access files?
The closest you'd be able to come to that is to run your program in a chroot jail.
3,815,564
3,815,827
Linking libpng with g++
I'm trying to get libpng working on linux. I couldn't get it to work through netbeans, so I ran g++ directly as g++ -lpng -lz main.cpp -o test and it compiles. When I try to run it it it outputs ./test: error while loading shared libraries: libpng14.so.14: cannot open shared object file: No such file or directory. I as...
It's odd that g++ is able to find the library but test can not (you can tell that g++ can find it because test specifically expect libpn14 even though you only tell g++ '-lpng'). Are you sure you aren't passing any -L or -R flags to g++? Are your LD_PRELOAD or LD_LIBRARY_PATH environment variables set in the shell you'...
3,815,647
3,815,737
Using map for inventory system
Is there any practical way to get objects to work with maps? (I don't really know much about maps so sorry if this is a bad question). I'm interested in using a map for an inventory system that will contain item objects. An item object has a name, description, and money value. The key would be the item's name, and the ...
The C++ standard library template map is just a storage container so it can definitely be used with objects. The map will take your object as its templated argument parameter. A map would work well for your inventory system. Use something like: #include <pair> #include <map> #include <string> #include <iostream> clas...
3,816,051
3,816,088
What happens to open file handles after an execv call? (C++)
On Linux, I have some C++ code where I want to execv another application. That program outputs some data to the stderr. I therefore redirect the stderr by calling freopen() with stderr as the stream parameter. The thing is, I want to redirect the stderr for another process that is run. Here is the scenario I am work...
The redirection is very much valid. The execv call changes the process image, but the file descriptors remain untouched.
3,816,345
3,817,087
At what stage of compilation are reserved identifiers reserved?
Just a little curiosity at work, here. While working on something dangerous, I got to thinking about the implementations of various compilers and their associated standard libraries. Here's the progression of my thoughts: Some classes of identifiers are reserved for implementation use in C++ and C. A compiler must per...
(The comments on the question explain that we're talking about reserved identifiers in the sense of C99 section 7.1.3, i.e., identifiers matching /^_[A-Z_]/ anywhere, /^_/ in file scope, /^str[a-z]/ with external linkage, etc. So here's my guess at at least a part of what you're asking...) They're not reserved in the ...
3,816,437
3,816,557
Asking for help to troubleshoot a c++ Eight queens puzzle code
I have written a function in C++ code for the eight queens problem. The program is supposed to print out all 92 possible solutions. I only can run up to 40. Don't know where the problem is. Try to debug but I'm still stuck. #include "stdafx.h" #include <cmath> #include <iostream> using namespace std; bool ok(int b...
Your problem is in the ok function. It has three errors, all relating to the bounds of your matrix. The first error (which will if anything cause you to receive too many solutions), is here: for(int c = 7; c > 0; c--){ This will never check column 0. The test should be c >= 0. The other two errors, which cause unpredi...
3,816,445
3,816,458
Undefined reference to static member
I have a static member in my class. It's declared and defined: In my header: class Bla { ... static Bla* instance; ... }; In my implementation file: Bla::Bla* instance = 0; But ld doesn't seems to like it: release/bla.o:bla.cpp:(.text+0x19f7): undefined reference to `Bla::instance' I'm using GCC 4.4.0 from the Qt SD...
You missed a Bla, and instead created a global. Make it: Bla* Bla::instance = 0;
3,816,446
3,816,473
How can I safely average two unsigned ints in C++?
Using integer math alone, I'd like to "safely" average two unsigned ints in C++. What I mean by "safely" is avoiding overflows (and anything else that can be thought of). For instance, averaging 200 and 5000 is easy: unsigned int a = 200; unsigned int b = 5000; unsigned int average = (a + b) / 2; // Equals: 2600 as in...
Your last approach seems promising. You can improve on that by manually considering the lowest bits of a and b: unsigned int average = (a / 2) + (b / 2) + (a & b & 1); This gives the correct results in case both a and b are odd.
3,816,484
3,816,519
Applying compiler options to specific files
I am trying to compile and build a project(s) in visual studio and I started looking into compiling with the /Wall option which gives all warnings. I am wondering iof there is a way to run this only on those files I am interested in, since currently I get a million warnings on files i have no ability or desire to chan...
In the Solution Explorer select the files you want all warnings for, right click and select Properties. From there you can adjust whatever compiler settings you want to for those files, just about like you would for the entire project.
3,816,492
5,978,709
eclipse cdt: add include path from pkg-config
i want to add a dynamic configuration path (generated from pkg-config) to my project. (this is basically for third-party dependencies like boost, so workspace includes is not appropiate, and filesystem include neither because that would be hardcoded and every developer would have to change that manually) i am on projec...
Pkg-config support is finally coming to CDT and will be finished on August. http://code.google.com/p/pkg-config-support-for-eclipse-cdt/
3,816,680
3,816,720
Something similar to ParallelPython for C++?
I need to do some extensive searching and string comparisons and for this I figure that a compiled program is much better than an interpreted ones especially after seeing some comparison studies. I came across ParallelPython which was beautiful. It has autodiscovery for clusters and can pretty much do all the load bala...
I would suggest OpenMPI. I do not know what ParallelPython does exactly, but OpenMPI is an open API for cluster computing, and I imagine it will provide the requested functionality.
3,816,811
3,816,917
Need help, I do not understand why following code is not getting compiled
Header file is "graph.h" #ifndef _GRAPH_H_ #define _GRAPH_H_ #include <map> #include <vector> using namespace std; template <class T> class VERTEX { public: VERTEX(T inVertex): m_vertex(inVertex), m_visited(false){} ~VERTEX(){} private: T m_vertex; bool m_visited; }; template <class T> class GRAPH {...
There are two problems. First you have to qualify the dependent type in insert: void insert(GRAPHVERTEX inSRC, GRAPHVERTEX inDST) { typename GRAPHMAP::iterator itr = m_graph.find(inSRC); } Second, you need a < operator for your vertex class. In the public section of VERTEX add this: bool operator<(const VERTEX<T>&...
3,816,818
3,816,867
static const data member vs hard-coded value in function
I have a class with a data attribute, say of type int, which should be constant throughout the run of the program, and have the same value in all class instances. I want this value to be accessable through a public member function called get_value(). The obvious way to do this is to define a private static const clas...
From a computational point of view there shouldn't be much differences in term of compiled code. But with the first method your are not hiding variable inside your function : if you have not 1 but 10 of these variable I would expect to see them defined at the begin of your class, not inside some getter functions 10's o...
3,816,912
3,817,222
C++: Custom data type - typecasting and union issues
What I'm trying to do is create a new custom data type that behaves like all other primitive types. Specifically, this data type appears like a Fixed Point fraction. I've created a class to represent this data type, called "class FixedPoint", and in it there are ways to typecast from "FixedPoint" to "int" or "double" ...
I am having a hard time at seeing what you would try to use this for. It seems smelly to have to constantly ensure that sizeof(FixedPoint) == sizeof(int) and, assuming that, there are other hidden gotchas, like endianness. Maybe I should back up a little bit here, unions only "convert" a value from one type to anoth...
3,816,958
3,816,974
How to detect newline character(s) in string using Visual Studio 6 C++
I have a multi-line ASCII string coming from some (Windows/UNIX/...) system. Now, I know about differences in newline character in Windows and UNIX (CR-LF / LF) and I want to parse this string on both (CR and LF) characters to detect which newline character(s) is used in this string, so I need to know what "\n" in VS6 ...
inputString.find ("\n"); will search for the LF character (alone). Library routines may 'translate' between CR/LF and '\n' when I/O is performed on a text stream, but inside the realm of your program code, '\n' is just a line-feed.
3,816,969
3,816,987
C++ What is the purpose of destructors if compiler creates them implicitly?
Everywhere i read, if no destructor is defined the compiler creates one anyway. So what is the point of explicitly defining one? Thank you
The compiler-provided default may not do everything you need done. For example, if you have dynamically allocated memory that needs to be deleted, you'll have to define the destructor yourself. The compiler will not do that for you.
3,817,208
3,817,250
Qt ISO C++ forbids declaration without type - header file is included?
I'm receiving the forbids declaration without type error in a Qt application I'm working on. The problem is that I have included the header file which declares the class. It should be defined as a type as far as I can tell. I tried forward declaration as well, but I'd like to use the methods of the class in this fil...
You have a circular dependency between your header files -- Shapes.h includes glwidget.h, which includes Shapes.h again. So, the second time the compiler tries to include glwidget.h, the include guard AGLWIDGET_H has been defined, so it doesn't include it again, and then the code in Shapes.h tries to use types that ou...
3,817,238
3,817,286
embedded programming in C
I am a newbie as far as it comes to embedded systems programming. I have to write lots of simple C or C++ programs like atoi, itoa, oct_to_dec, etc., which would have been easy to write in normal C. But my hardware unit does not have the usual header functions and hence I cannot use standard library functions. :( Could...
Most embedded compilers do indeed have an implementation of at least a subset of the standard C libraries, including functions like itoa and atoi. Depending on the compiler and the type of microcontroller that you are using, you might not have to rewrite any of the functions. Seeing that this is homework, however, that...
3,817,246
3,817,365
Order of assignment and comparison in an 'if' statement
Looking at the code: int i = 5; if (i = 0) { printf ("Got here\n"); } What does the C standard have to say about what will get printed? Or in more general terms does the assignment happen first or the comparison?
§6.8.4 says that the syntax for an if selection statement is: if ( expression ) statement Further in this section, it mentions that if the expression compares unequal to 0, then statement is executed. The expression must therefore be evaluated before it can be compared to 0. i = 0 is an expression which evaluates to 0....
3,817,410
3,825,883
Qt 'Rectangle' is not a type - when rectangle is declared as a class
Im having a problem of my Rectangle class not being seen as a type. I've included the proper header, and so I am confused. shapes.h #ifndef SHAPES_H #define SHAPES_H #include "Colors.h" #include <QPoint> #include "glwidget.h" //class GLWidget; class Shape { public: virtual void draw(); }; class Rectan...
Well I'm gonna go with it had something to do with the virtual function within Shape not being defined as in g++ undefined reference to typeinfo. The machine I had the strange error on is using an older version of Qt than I have on my personal machine, and my personal is having no issues with this code. Thanks for t...
3,817,414
3,950,396
Large scale usage of Meyer's advice to prefer Non-member,non-friend functions?
For some time I've been designing my class interfaces to be minimal, preferring namespace-wrapped non-member functions over member functions. Essentially following Scott Meyer's advice in the article How Non-Member Functions Improve Encapsulation. I've been doing this with good effect in a few small scale projects,...
OpenCV library does this. They have a cv::Mat class that presents a 3D matrix (or images). Then they have all the other functions in the cv namespace. OpenCV library is huge and is widely regarded in its field.
3,817,631
3,817,716
Basic signal handling in C++
This is a pretty basic scenario but I'm not finding too many helpful resources. I have a C++ program running in Linux that does file processing. Reads lines, does various transformations, writes data into a database. There's certain variables (stored in the database) that affect the processing which I'm currently readi...
I would handle it just like you might handle it in C. I think it's perfectly fine to have a stand-alone signal handler function, since you'll just be posting to a semaphore or setting a variable or some such, which another thread or object can inspect to determine if it needs to re-read the settings. #include <signal....
3,817,641
3,817,651
Plugin System without rebuilding for each OS?
I'm making a game that will allow content development and I'd like it to be sort of a DLL based system. But, my game works for Linux (X86 arch) , Mac OSX and 32 bit Windows. Is there a way I could allow content developers to compile only one thing and have it work based on the platform? I fear it might get confusing if...
You can decide to use a cross-platform scripting environment like Lua for plugins. This is essentially what most cross-platform games do.
3,817,842
3,817,961
Accessing MySQL through C++
I want to run queries on my MySQL server through a C++ program that will be released to the public for free, but not under the GPL or any other open-source license. My first question is if I can use the MySQL Connector/C++ library in my application. If not, then what alternatives are there for me to use?
Unfortunately, MySQL has changed client libraries licenses from LGPL to GPL which means that any application linking with those libraries statically or dynamically becomes a derivative work. Therefore, you cannot use MySQL client libraries (that are used to access MySQL server) in non-FOSS applications unless you purch...
3,817,910
3,818,029
Calling map::find with a const argument
I have an object: map<A*, string> collection; I would like to call the map::find function, but the value I have for the key is const, like in the following code, which does not compile: const A* a = whatever(); collection.find(a); The following code works and performs the equivalent of the find operation: const A* a ...
Comparing pointers has nothing to do with it. The OP may or may not need a custom compare operation; it looks to me like they're just looking for a specific object by its address, which seems perfectly reasonable. The first two answers seem to have missed the point that find() doesn't compile while a handwritten search...
3,817,914
3,817,934
Why should I have an enumeration declared with a typedef in C++?
I had code that looked like this: enum EEventID { eEvent1, eEvent2, ... eEventN }; And that got reviewed and changed to typedef enum { eEvent1, eEvent2, ... eEventN } EEventID; What is the difference between the two? Why make the change? When I looked at this question, the only mention of typedefs g...
The two are identical in C++, but they're not the same in C -- in C if you use the typedef you get code that is compatible between C and C++ (so can be used freely in a header file that might be used for either C or C++). That's the only reason I can see for preferring it.
3,817,980
3,818,030
How to Pass a std::string variable into a function
I have a C++ method that takes one variable the method signature is like this: DLL returnObject** getObject( const std::string folder = "" ); I tried passing in: const std::string myString = "something"; but I get the following error: No matching function call to ... getObject( std::string&); I have a couple questio...
This little example works as expected: #include <stdio.h> #include <string> class foo { public: void getObject( const std::string folder = "" ); }; int main () { const std::string myString = "something"; foo* pFoo = new foo; pFoo->getObject( myString); pFoo->getObject(); // call using default...
3,818,280
3,818,629
Implementing communication timeout
I'm implementing a class that talks to a motor controller over a USB device. I have everything working except for a way to indicate whether a parameter fetched over the comm link is "fresh" or not. What I have so far: class MyCommClass { public: bool getSpeed( double *speed ); private: void rxThread(); struct M...
If you don't need to do something "right away" when a message becomes stale, I think you can skip using timers if you store both the computer's time and the device's timestamp with each message: #include <ctime> #include <climits> class TimeStamps { public: std::time_t sys_time() const; // in seconds unsigned lo...
3,818,618
3,818,632
C++ equivalent to the Python len() function?
I have an integer and need to find out how many digits are in it.
A little tricky to handle negative numbers and the case where the input is zero: int length(int n) { int len = 0; if (n < 0) { len = 1; n = -n; } while (n > 9) { n /= 10; len++; } return len+1; }
3,818,640
3,819,174
How to use OpenGL and GLUT in Cygwin
I've attempted to follow the instructions from various places [1][2][3], but I keep getting link errors when attempting to use GLUT and OpenGL in Cygwin. Everything I try gives me a link error similar to: $g++ -Wall -pedantic -c -o triangle.o triangle.cpp $g++ -o triangle *.o -lglut32 -lglu32 -lopengl32 -o triangle tr...
The error indicates that you didn't define _STDCALL_SUPPORTED before including . Also see answers for this question.
3,818,703
3,819,756
Lua or Python binding with C++
I have used Lua.NET on .NET platform and I could call the .NET class/object from Lua and I could call the Lua from .NET Lua API interface. I did the same with the IronPython. I knew the how the .NET binding works. Now I have a C++ project and I want to use the dynamic capabilities. I want to call C++ object which may ...
When considering Lua to Python in C++ for two way calling, is Python have upper hand with Boost Python library? There are a few libraries that simplify the communication between C++ and Lua. One of them, luabind, is inspired by boost.python and is quite powerful and fairly easy to use. Other C++ <-> Lua libraries to...
3,818,796
3,818,843
Including header files in VS2005
How do you include header files from top-level and sub-directories in c++?
#include "sub/some_header.h" #include "../other_header.h"
3,818,893
3,819,048
Adjusting tab width in C++
Is there any way to adjust tab width in the console?
It's hard to know until you elaborate more in your question but there's the possibility you just want to write some justified text out to the console, if this is the case you could: #include <iomanip> and use: std::setw or possibly std::ios std::setiosflags std::resetiosflags Difficult to know unless you give us mor...
3,819,030
3,819,043
How can I build a lookup table in C++?
I am a complete novice in C++. I am trying to read a file and build a lookup table (more like a hashtable just to check the existence of a string value). The file has about 300 thousand entries that I will use to build a lookup table. And after this, I will be performing some 1 million lookups on this. What is the most...
Based on the scenario, you probably also want to look at Tries
3,819,068
3,823,679
Discard ALT key press in CMainFrame
I'm having the following code: CMainFrame* pFrame = new CMainFrame; if (!pFrame) return FALSE; m_pMainWnd = pFrame; // create and load the frame with its resources pFrame->LoadFrame(IDR_APP_MAINFRAME, WS_OVERLAPPEDWINDOW | FWS_ADDTOTITLE, NULL, NULL); // The one and only window has been initialized, so show...
In your CMainFrame override PreCreateWindow and destroy the menu. Try something like this: BOOL CMainFrame::PreCreateWindow(CREATESTRUCT& cs) { if(cs.hMenu!=NULL) { ::DestroyMenu(cs.hMenu); cs.hMenu = NULL; } return CFrameWnd::PreCreateWindow(cs); }
3,819,439
3,819,447
Java program with 2 native methods declared and defined in C and C++
Can anyone give me an example of a Java program which has two native methods declared and defined in C and C++. Actually, I need a procedure as well as the code, so that I can run it and learn from it, thanks.
You can do it with JNI [Java Native Interface] Check this tutorial WIN env Linux Environment :-) better one
3,819,572
3,819,586
Another way to use continue keyword in C++
Recently we found a "good way" to comment out lines of code by using continue: for(int i=0; i<MAX_NUM; i++){ .... .... //--> about 30 lines of code continue; ....//--> there is about 30 lines of code after continue .... } I scratch my head by asking why the previous developer put the continue keyword inside ...
Using continue in this case reduces nesting greatly and often makes code more readable. For example: for(...) { if( condition1 ) { Object* pointer = getObject(); if( pointer != 0 ) { ObjectProperty* property = pointer->GetProperty(); if( property != 0 ) { ///blahblahb...
3,820,048
3,820,078
Where did the datatypes get their name from?
Why is a bit, called a bit. Why is a 8-bits a Byte? What made people call a 16-bits a Word, and so on. Where and why did their alias come about? I would love other people to include things like basic ASM types, then branch out to C/C++ and move on to SQL and the like's datatypes. 1-Bit Bit - binary Unit Bool - Named ...
Wikipedia is your friend: bit nibble byte "char" is just short for "character" "short" is an alias for "short int" word "is the native or most efficient size the CPU can handle" (thanks to Tony for pointing that out). "int" is short for "integer". The size is undefined (can be 16, 32 or 64 bits). "float" is short for ...
3,820,051
3,820,071
Undefined reference to `RPositionServer::RPositionServer()`
i'm writing program for Nokia 5230 (S60 5th edition platform) using Nokia Qt SDK. I have the problem with retrieving geolocation info. I'm trying to use example from nokia forum (http://bit.ly/be3QDK first one). The following code: #include <lbs.h> #include <lbsrequestor.h> #include <lbscommon.h> #include <lbsposition....
You have to link against Lbs.lib. See Reference here.
3,820,178
3,820,473
What is the main difference in object creation between Java and C++?
I'm preparing for an exam in Java and one of the questions which was on a previous exam was:"What is the main difference in object creation between Java and C++?" I think I know the basics of object creation like for example how constructors are called and what initialization blocks do in Java and what happens when con...
In addition to other excellent answers, one thing very important, and usually ignored/forgotten, or misunderstood (which explains why I detail the process below): In Java, methods are virtual, even when called from the constructor (which could lead to bugs) In C++, virtual methods are not virtual when called from the ...
3,820,363
3,820,388
Class Private members modified on creating a structure (C++)
I was just going through some codes of C++. Where in I came across the concept of reinterpret_cast operator. EDIT 1 : I know that accessing private members of a class is not recommended. But in some situations we ought to go ahead and access them. I have just put forth this question to get my concepts clear. In the e...
$5.2.10/2 - "An expression of integral, enumeration, pointer, or pointer-to-member type can be explicitly converted to its own type; such a cast yields the value of its operand." This means that pointers 'bs2' and 'bs3' are pointing to the same location $9.2/16 - "Two standard-layout struct (Clause 9) type...
3,820,384
3,820,433
Compiling & linking multiple files in C++
One of my "non-programmer" friends recently decided to make a C++ program to solve a complicated mechanical problem. He wrote each function in a separate .cpp file, then included them all in the main source file, something like this: main.cpp: #include "function1.cpp" #include "function2.cpp" ... int main() { ... } ...
The main reason people compile object by object is to save time. High-level localised code changes often only require compilation of one object and a relink, which can be faster. (Compiling too many objects that draw in heaps of headers, or redundantly instantiate the same templates, may actually be slower when a cha...
3,820,390
3,820,890
What C++ IDEs on Linux have "intellisense" in par with, or better, than Visual Studio?
There are some Linux based C++ projects in the pipe. What IDEs should I go for that have some kind of "intellisense" in par with, or better, than the one of a bare Visual Studio (that is, without the Visual Assist steroids). (Note that I didn't use the words "as good as, or better". I consider the Visual Studio C++ int...
None. Eclipse and Qt Creator are popular choices, but they have nothing on VS.
3,820,396
3,820,857
ifstream::unget() fails. Is MS' implementation buggy or is my code erroneous?
Yesterday I discovered an odd bug in rather simple code that basically gets text from an ifstream and tokenizes it. The code that actually fails does a number of get()/peek() calls looking for the token "/*". If the token is found in the stream, unget() is called so the next method sees the stream starting with the tok...
is there anything that is not correct in the code that could cause the problem (not talking about whether it makes sense) Yes. Standard streams are required to have at least 1 unget() position. So you can safely do only one unget() after a call to get(). When you call peek() and the input buffer is empty, underflow()...
3,820,667
3,820,920
OpenGl surface&texture
I have: 3d pointset, which is calculated from 3d reconstruction process from N frame. sample frame snapshot (for example first frame when camera in (0,0,0)) 3d to 2d corresponds I want: create triangulation of point set and put texture (frame snapshot) on it. How can I create this triangulation + texture via OpenGL...
Triangulation must be part of the reconstruction process. OpenGL has nothing to do with it. When you done the triangulation you project the texture by specifying 2d screen coordinates of the vertices in the original frame as texture UV coordinates.