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
6,319,327
6,319,471
Help with 3d camera class
I am trying to add the ability for the camera to go up and down on the Y axis, something it currently does not support. I have tried adding to the Y value when W and or S is pressed but it doesn't work correctly. What kind of formula do I need? I know it has to do with the pitch and adding to the Y axis. void WALKING_C...
For forward movement, something to this effect should work: position.y += (float)sin(anglePitch * M_PI / 180) * distance * 25; You may have to reverse the sign, as I'm not sure whether your application uses positive or negative Y values for upward movement.
6,319,347
6,319,359
What does "ns" stand for in "nsresult"?
What does "ns" stand for in nsresult as seen in C++ code for Firefox? Likewise, I'm sure that the meaning is the same in uses of NS_IMETHODIMP as used in Mozilla projects.
Pretty sure it's short for Netscape.
6,319,376
6,319,503
How works statics variables in .Net and C++?
Static variables. in NET work differently to global variables that compile to native languages​​like C++ or Fortran? Why?
There is no semantic difference. A static field is just a fancy name for a global variable.
6,319,397
6,319,424
C++ retrieve a part of a string
How do retrieve the first word of a string in C++? For example, "abcde fghijk" I would like to retrieve abcde. Also what do I do to retrieve fghijk? Is there a convenient function for this or should I just code it?
Use stringstreams (<sstream> header) std::string str ="abcde fghijk"; std::istringstream iss(str); std::string first, second; iss >> first >> second;
6,319,419
6,319,439
What is wrong with this Singleton implementation?
The idea is to have a Singleton in C++ deleted when the program ends. We learned this method of implementation in class: class Singleton { private: static Singleton* the_singleton; protected: Singleton() { static Keeper keeper(this); /*CONSTRUCTION CODE*/ } virtual ~Singleton(...
There's no problem with it at all. The "Keeper" thing is nuts for this application, IMHO. There are a few cases where it might be warranted. For instance, if the Singleton must take constructor arguments, allocating it statically might not be possible. Or if its constructor might fail, the simpler approach wouldn't al...
6,319,519
6,319,561
C++ Memory Debugger?
Can anyone recommend a quality C++ memory debugging API or software for Windows(specifically, one that works with MinGW)? I'm nearly positive there's a memory leak in my program, but I have no idea where to start looking. Also, on a related note, I previously tried overloading the global new and delete operators myself...
For memory leaks in Windows, I've found that UMDH with usermode stack traces enabled is pretty useful. Here's a tutorial. For a list of other tools, look here.
6,319,606
6,319,626
File I/O from current Windows position C++
I have not yet found a definitive answer about this. I am trying to have access to files in subfolders from my .EXE. When I have asked before, people tell me to use the absolute location i.e. "c:/game/info/" if I wanted to access something in /info/ But it is completely unreasonable for me or anyone to assume that some...
Your title says "Windows", so I'll give a WinAPI-specific answer. On Windows, you can find your application directory with GetModuleFileName(NULL, ...), and PathRemoveFileSpec. Then PathAppend will make the full path to your data files. Or you can store the data inside you .exe file as Win32 resources, so they never g...
6,319,628
6,319,646
C++ get directory prefix
For example I have the string "root/data/home/file1.txt" I would like to get "root/data/home" Is there a convenient function in C++ that allows me to do this or should I code it myself?
You can do basic string manipulation, i.e. std::string path = "root/data/home/file1.txt"; // no error checking here std::string prefix = path.substr(0, path.find_last_of('/')); or take a third option like Boost.Filesystem: namespace fs = boost::filesystem; fs::path path = "root/data/home/file1.txt"; fs::path prefix = ...
6,319,783
6,319,843
Error: calling delete twice on the same memory location
I wrote this function in C++ as part of a bigger program: Object Single_list<Object>::pop_front() { //Single_node<Object> *tmp_front; //Object hold; if (empty()) { throw underflow(); } Single_node<Object> first_node = front(); Single_node<Object> *ptr = list_head; ...
Building on Mankarse's comment, try the following: Object Single_list<Object>::pop_front() { if (empty()) { throw underflow(); } Object result = front().retrieve(); Single_node<Object> *ptr = list_head; list_head = list_head->next(); delete ptr; return result; } This grabs the...
6,320,081
6,321,653
C++ advice from Code Complete on encapsulation?
In the section on "Good Encapsulation" in Code Complete, it is recommended to hide private implementation details. An example is given in C++. The idea is basically to completely separate the interface from the implementation, even in the class level. class Employee { public: ... Employee( ... ); ... F...
Another advantage of the PIMPL idiom may be in maintaining the ABI. See The Pimpl Idiom in practice. The size of the class remains constant. This means that you may change the internal implementation, while keeping the interface intact. If the implementation is distributed in compiled form (lib, dll, so, etc.), then, u...
6,320,195
6,320,235
Repetitive sequence constructor
Can I build a vector<vector<int> > using Repetitive sequence constructor? I know I can build one like vector<int> v(10, 0); but I dont know how to build a vector of vector using this same method. Thank you!
Just pass it a vector as the second parameter: // 10 x 10 elements, all initialized to 0 vector<vector<int> > v(10, vector<int>(10, 0));
6,320,319
6,336,288
Mex dynamic memory management issue with std::vector in linked external DLL; Segmentation error
I am trying to create a mex file that interfaces MATLAB with an external C++ library that communicates with some hardware. An imported library and precompiled DLL (.lib and .dll) are provided by the hardware vendor for my version of VC++ and I was able to implement them in C++ without any issue. However, I ran into seg...
Thanks everyone for the answers and comments. I was able to resolve the issue with some help from the friendly folks at MathWorks. From the original post at http://www.mathworks.com/matlabcentral/answers/9294-mex-dynamic-memory-management-issue-with-std-vector-in-linked-external-dll-segmentation-error : You are probab...
6,320,520
6,320,749
In win32 C++ how can i enable static text control to copy text?
I am writing a simple win32 application that has a window and static text , now I want to enable the user to copy the text with his right click (mark and copy) how can i do that? LANGUAGE LANG_NEUTRAL, SUBLANG_NEUTRAL IDD_DIALOG1 DIALOG 0, 0, 369, 318 STYLE DS_3DLOOK | DS_CENTER | DS_MODALFRAME | DS_SHELLFONT | WS_CAP...
You can't do this with static text. In particular you can't highlight text. Instead you should use a read only edit control.
6,320,573
6,320,612
How to get list of files in a directory programmatically
I have searched everything , but no source codes i found work with VS C++ 2008, Do you have any way to find list of files in a directory programmatically? I am using VS 2008 C++ on Windows.
This shall find the list of files in C: drive, It doesn't use dirent.h just simple file handling api's, FindFirstFile & FindNextFile #include <windows.h> int main(int argc, char* argv[]) { WIN32_FIND_DATA search_data; memset(&search_data, 0, sizeof(WIN32_FIND_DATA)); HANDLE handle = FindFirstFile("c:\\*", &...
6,320,622
6,320,641
Does C++ have anything like List<string> in C#?
Does C++ has anything like List<> in C#? Something like List<string> for storing an array of strings.
The answer is actually std::vector<std::string> std::list is a linked list, not an array like C#'s List<T> class. E.g. #include <iostream> // iostream is for cout and endl; not necessary just to use vector or string #include <vector> #include <string> using namespace std; int main() { vector<string> list; lis...
6,320,659
6,321,087
C++ newbie: my loop should CHANGE a string, then print the string to a file. But it is ADDING to the string
I have written C++ code for performing calculations. There is a loop in the code. At the end of each loop, I want to: 1) Get the time, a calculation result. 2) Make a name for a file. The name should contain the time. 3) Print the file name into an external file. Each new loop should overwrite the file name from the ...
The issue is that this line is adding to your stringstream inside the loop. You are never resetting its contents. storeNumberForConversion << global_time << flush; The simplest thing to do is to move the declaration of storeNumberForConversion inside your loop so it is created empty just before you use it. Alternative...
6,320,700
6,320,837
Debugging and preprocessor directive
For debugging I have many calls to a debug log function in my application. Of course in the production version these debugging calls need to be skipped. Instead of writing: #if DEVEL == 1 Log::debug(...); #endif around all calls to the debug function I decided the write the following in the debug function itself: ...
Instead of worrying about optimizer, you can do a simple trick: #if DEVEL == 1 #define LOG_DEBUG(...) Log::Debug(__VA_ARGS__) // variadic macro #else #define LOG_DEBUG #endif Now use LOG_DEBUG everywhere to keep it simple.
6,320,737
6,320,764
a way to read file line to line , but give problem
I want to read file line to line , here is code : map<int,string>WordList ; //int is the key, string the returnad value int GetWordList(char* file) { WordList.clear(); char getch; int wordindex=-1; string tempstring=""; ifstream myFile(file); while (!myFile.eof()) { myFile.get(getch...
Here goes again: Do not test against eof. Next, why do you make your loop so complicated if you always want to read in exactly one line? There's std::getline for that. Build your loop around that and you should be fine.
6,320,825
6,320,844
NULL in instantiation
When writing C++, let's assume the following line of code: Object* obj = new Object(); If this line both compiles and does not cause exceptions or any other visible runtime problems, can obj be NULL right after this line was executed?
No, obj cannot be NULL. If new fails, it will throw a std::bad_alloc exception. If no exception was thrown, obj is guaranteed to point to a fully initialized instance of Object. There is a variant of new that doesn't throw an exception Object *obj = new(nothrow) Object(); In this case, obj will be NULL if new fails, a...
6,320,916
6,321,027
spliting in c++ like what we do in c#
Possible Duplicates: How to split a string in C++? Splitting a C++ std::string using tokens, e.g. “;” think I have this string : string a = "hello,usa,one,good,bad"; I want to splitting this string with , so I need a array of string like here : string *a ; a = { hello , usa , one , good , bad } what shoudl I do ...
This simple AXE parser will do it: std::vector<std::string> strings; auto split = *(*(axe::r_any() - ',') >> e_push_back(strings)); split(a.begin(), a.end());
6,320,995
6,321,005
Why I cannot cout a string?
Why I cannot cout string like this: string text ; text = WordList[i].substr(0,20) ; cout << "String is : " << text << endl ; When I do this, I get the following error: Error 2 error C2679: binary '<<' : no operator found which takes a right-hand operand of type 'std::string' (or there is no acceptable conversion) ...
You need to include #include <string> #include <iostream>
6,320,999
6,321,019
Error C2064: term does not evaluate to a function taking 1 argument
When I try the below program its gives me the :error C2064: I tried in google but not able to find the exact reason. Please help. class myClass { public: void function(myClass dTemp) { cout<<"Inside myClass: taking myClass parameter"<<endl; } }; . int main() { myClass ...
Did you mean to be able to call an object of type myClass like a function? You need to overload operator() for that: void operator()(myClass dTemp){ // ... } If you instead wanted to call the function, well, you should actually do so: myClassTemp.function(myClassTemp1);
6,321,170
6,321,226
Is there any advantage to using pow(x,2) instead of x*x, with x double?
is there any advantage to using this code double x; double square = pow(x,2); instead of this? double x; double square = x*x; I prefer x*x and looking at my implementation (Microsoft) I find no advantages in pow because x*x is simpler than pow for the particular square case. Is there any particular case where pow is ...
FWIW, with gcc-4.2 on MacOS X 10.6 and -O3 compiler flags, x = x * x; and y = pow(y, 2); result in the same assembly code: #include <cmath> void test(double& x, double& y) { x = x * x; y = pow(y, 2); } Assembles to: pushq %rbp movq %rsp, %rbp movsd (%rdi), %xmm0 mulsd %xmm0,...
6,321,191
6,321,394
Using friend in templates
I am writing a small class, the class is basically a factory for the C class, but I want other classes to be able to access some of the methods. template<class C> class CFactory { public: friend class C; }; This should make the fields of CFactory available to the class C, but the compiler thinks otherwise. I'm g...
Ise's response is correct -- Comeau's FAQ contains a question concerning this issue in more detail. However, perhaps you can try an extra template indirection that might work? Something like this: template <typename T> struct FriendMaker { typedef T Type; }; template <typename T> class CFactory { public: frien...
6,321,223
6,321,235
c++: write a char at a given char* causes segfault
I want to copy a char to an address where a given char* points to. it's in a function which is called by main: char data = " "; myfunction(data, somethingelse); ... inside the function i have something like void myfunction(char* data, short somethingelse) { ... char byte = 0; inputfilestream.read(&byte, 1); *da...
String literals are readonly. If you want a modifyable string, you must use an array, e.g.: char data[10]; Or: char *data = new char[10]; To elaborate a bit more: the type of a string literal is actually const char*. Assigning a string literal to a non-const char* is therefore technically invalid, but most compilers ...
6,321,281
6,321,358
How to know if a horizontal scrollerbar is shown in a QPlainTextEdit inherited class?
How can i know that whether the scrollbar is displayed in a QPlainTextEdit ? I tried QScrollBar::isHidden() , but always return true. Appreciate any of your help !
You should try using the isVisible() method on your edit's verticalScrollBar(). This works as expected here: #include <QtGui> class Win: public QWidget { Q_OBJECT public: Win(QWidget *parent=0): QWidget(parent) { edit = new QPlainTextEdit; QPushButton *b1 = new QPushBut...
6,321,333
6,321,557
How to read user input with adding space or some other character?
I want to read user input, something like here : char *text = new char[20] ; cin >> text ; but if the user enters "hello", I want my other empty characters to be filled with space or -, something like: "hello------------------------" How can I do this?
There's no standard and fast way to do this. I can think of some options. Suppose we have: char *text = new char[20]; cin >> text; Note - we need to know that the capacity is 20! I'd recommend you to use some constant for this, especially if this will be used for other strings, too. Okay, first option - use std::st...
6,321,335
6,321,359
Send or execute internet direction without downloading annything
I have a wireless IP cam that play sounds. I know how to play this sounds because i know the direction and the command. I tried it with this Terminal command: http://192.168.0.90/axis-cgi/playclip.cgi?clip=6 The problem is wget command download the clip and i only want to reproduce it. Beacuse i want to do into a progr...
mplayer or vlc will stream the URL and play it as if it was a local file. As for doing it in C++, you have much more work to do (find an HTTP library, read the contents, decode it and reproduce it. Maybe the ffmpeg library can help you here.
6,321,487
6,321,535
Boost named_condition implementation
What is native Linux API used for Boost named_condition class implementation? In Windows, I guess, this is CreateEvent, I want to know what Linux feature can be used to get this functionality.
Posix Threads Condition Variables
6,321,602
6,321,741
Boost thread Leakage C++
Could someone let me know whether boost thread library leaks. It seems to me that it does: Google says that I should compile with both boost thread and pthread which I am doing and that in version 1.40 this problem has been fixed but I still get leakage. Note that this will compile fine but leaks are detected. #include...
This is in relation to boost 1_46_1, so it may not be true for the version that you are using. Look at the boost sources if you really want to convince yourself. (The leak detector on OSX does not detect any leaks when I run your example code). This is not an actual leak (unless there is a bug with either pthreads, the...
6,321,679
6,321,704
Effective C++ "35. Minimize compilation dependencies between files". Is it still valid today?
In this chapter Scott Meyer mentioned a few technique to avoid header files dependency. The main goal is to avoid recompiling a cpp file if changes are limited to other included header files. My questions are: In my past projects I never paid attention to this rule. The compilation time is not short but it is not into...
I don't think compiler technology has advanced particularly. clang is not some piece of magic - if you have dependencies then and you make changes, then dependent code will have to be recompiled. This can take a very, very long time - read hours, or even days for a big project, so people try to minimise such dependenci...
6,321,692
6,321,701
Unexpected output with c++ class
This is my c++ code: class base { public: int bval; base(){ bval=0;} void give() { std::cout<<bval<<":"; } }; void SomeFunc(base *arr,int size) { for(int i=0; i<size; i++,arr++) std::cout<<arr->bval; std::cout<<"\n"; for(int i=0; i<size; i++,arr++) arr->give(); std::cout<<...
Your array, BaseArr has 5 elements, not 6. Its upper bound is 4. base BaseArr[5]; SomeFunc(BaseArr,5); //should fix it. EDIT: For why you are getting output: in C arrays doesnt have fixed limits, you can easily go out of bounds without getting any errors. Result is generally catastrophic. You will never know what will...
6,321,756
6,321,779
Environment Variables are in a char* how to get it to a std::string
I am retrieving the environment variables in win32 using GetEnvironmentStrings(). It returns a char*. I want to search this string(char pointer) for a specific environmental variable (yes I know I can use GetEnvironmentVariable() but I am doing it this way because I also want to print all the environment variables on ...
You do not want to use sizeof() in this context- you can just pass the value into the constructor. char* trivially becomes const char* and you don't want to use strcpy or printf either. That's for conventional C-strings- however GetEnvironmentStrings() returns a bit of a strange format and you will probably need to in...
6,321,803
6,321,818
How to send D3D Device by giving reference ( DirectX/C++ Prgoramming )
H1. I'm trying to depart my codes into different .cpp and .h files to make them find, see and understand easier. Here is what I'm trying to do now: I got a Meshes.cpp wich is my main .cpp source file. In the Render function ( Render() ) I have to call a function that named SetupMatrices: This is my "d3dGeneral.cpp" fil...
Have you tried this: (*PDev)->SetTransform( D3DTS_PROJECTION, &matProj );
6,321,911
6,333,905
Using an abstract deleter with std::unique_ptr
I want to have a run-time interface that offers some creation methods. These methods return unique_ptr<T>, and I want to enable custom deletion by the creating class. The thing is that I definitely don't want the interface to offer these methods directly- they should only be available in the destruction of the unique_p...
Your specification isn't completely clear to me, but have you considered unique_ptr<T, void(*)(void*)>? This is a very flexible type with many qualities of a dynamic deleter. If that isn't what you're looking for, you might try something along the lines of: class impl { public: virtual ~impl(); virtual void o...
6,322,063
6,325,049
QwtPlotCurve doesn't show up on graph
I'm currently working on a project in which I load a huge number of data points on a graph (something like 50,000, so I can zoom in as much as I want). I wanted to test how the commands worked, so I thought I'd try out the code with 10 pieces of data, but unfortunately my curve refuses to show up on my graph. QwtPlot *...
Try calling leftGraph->replot() to make the curve appear.
6,322,243
6,322,255
C2143 in nested template class
template <class T> class Edge; template <class T> class Vertex; template <class T> class Vertex { T key; char color; std::vector<Edge> adjVertices; }; template <class T> class Edge { Vertex* source; Vertex* target; }; Gives me error in line: std::vector< Edge > adjVertices; error: error C2143: s...
Your must #include <vector> and change std::vector<Edge> adjVertices; to std::vector<Edge<T>> adjVertices; The same applies to: Vertex<T>* source; Vertex<T>* target; Next you'll face the problem that Vertex is defined before Edge. You should reverse the order.
6,322,245
6,323,298
Should I switch from using boost::shared_ptr to std::shared_ptr?
I would like to enable support for C++0x in GCC with -std=c++0x. I don't absolutely necessarily need any of the currently supported C++11 features in GCC 4.5 (and soon 4.6), but I would like to start getting used to them. For example, in a few places where I use iterators, an auto type would be useful. But again, I don...
There are a couple of reasons to switch over to std::shared_ptr: You remove a dependency on Boost. Debuggers. Depending on your compiler and debugger, the debugger may be "smart" about std::shared_ptr and show the pointed to object directly, where it wouldn't for say, boost's implementation. At least in Visual Studio,...
6,322,275
6,322,293
copying vector of pair
I am trying to copy a vector of pair to another: vector<pair<int,int>> vp = {pair<int,int>(1,1), pair<int,int>(2,2)}; vector<pair<int,int>> vp2; for_each(vp.begin(), vp.end(), [vp2](pair<int,int> p){ if(/*some condition*/){ v...
Copying is much easier than that: vector<pair<int,int>> vp2(vp.begin(), vp.end()); or even: vector<pair<int,int>> vp2 = vp; // or vector<pair<int,int>> vp2(vp); The error in your code is that you capture vp2 by value which effectively makes it const in your anonymous method, and you cannot call push_back on a const v...
6,322,364
6,324,146
C++0x Error: overloading a function with std::shared_ptr to const argument is ambiguous
Suppose I have two unrelated classes A and B. I also have a class Bla that uses boost::shared_ptr like this: class Bla { public: void foo(boost::shared_ptr<const A>); void foo(boost::shared_ptr<const B>); } Notice the const. That's the important part which the original version of this question lacked. This com...
shared_ptr has a template single-argument constructor, which is considered for the conversion here. That's what allows an actual parameter shared_ptr<Derived> to be supplied where a shared_ptr<Base> is needed. Since both shared_ptr<const A> and shared_ptr<const B> have this implicit conversion, it's ambiguous. At leas...
6,322,495
6,322,554
Are there any tools could package some C++ class to C#?
One software SDK affords some APIs by C++ class library, including the h, lib, dll files. However, I want to use C# to work with the library. So, are there any tools could package the C++ class library to C#? Or some suggestion? I don't want use CLI, because of so many classes.
Use C++/CLI, the dialect of C++ used in managed code on the .NET platform. The language was designed primarily for use in an application such as yours. See this article (the title is a bit of an exaggeration, but the content is good). Other searches on wrappers for C++ code should give you more examples. As Barry...
6,322,573
6,322,591
Compiler not allowing to define a compiler-generated constructor
I'm trying to define the constructor that compiler generates automatically and resulted in an compilation error. Here is my code: class myclass { public: void Test_Func() {} }; myclass::myclass() { } Is compiler doing anything in addition for a simple class like above. Here is the error that I got i...
The synthesised constructor is both declared and defined. You may not define it yourself. You'll have to declare your own constructor in order to provide an implementation. [special] (2003 wording, 12/1) says: The default constructor (12.1), copy constructor and copy assignment operator (12.8), and destructor (12....
6,322,685
6,322,902
Why is it forbidden to open multiple namespaces at a stretch?
It's possible to do using namespace foo::bar; (i.e., using the inner namespace without using the outer namespace first / at all), why does the standard forbid to do the following? namespace foo::bar { // open nested namespace bar in foo and extend it... } I'm not looking for a workaround, just a possible rational on...
I'm not sure "forbidden" is the right word - maybe it was just an oversight. It's a fairly small nice-to-have which isn't really a big deal. You could also take the point of view that the namespace foo isn't created yet when you write foo::bar, so allowing that syntax makes it look like foo was already created when it...
6,322,779
6,322,878
modulus operations on long long in c++
I am working on prime factorization on large numbers (mainly, project 3 @ project Euler. I need to use the modulus on numbers declared as long long. Everytime I try to modulus that gigantic number I get a floating point exception. Any help would be profusely appreciated. Thanks. I have run this through gdb and see ...
Don't try to mod by 0, it's undefined! Doing so will result in a divide-by-zero error. long x = 0; modulus = number % x; // x is 0 here and thus not valid To expand a bit on my answer, per Wikipedia's article on Modulo Operations a modulo 0 is undefined in the majority of systems, although some do define it to be a. ...
6,322,785
6,322,931
c++ Temporary object question
Is there a difference in the number of temp objects created between these 2 functions? string foo1() { return ""; } string foo2() { string s = ""; return s; } This is a homework question so please assume there is no compiler optimization.
No- only one temporary is created. The object on the stack of the function is not a temporary, it is an lvalue. The string literal is also an lvalue. Both involve exactly the same process- returning a string constructed from an lvalue.
6,322,949
6,322,985
Downcasting using the 'static_cast' in C++
Consider: class base { base(); virtual void func(); } class derived : public base { derived(); void func(); void func_d(); int a; } main { base *b = new base(); sizeof(*b); // Gives 4. derived * d = static_cast<derived*>(b); sizeof(*d); // Gives 8- means whole derived obj size...
Using static_cast to cast an object to a type it doesn't actually have yields undefined behavior. The symptoms of UB vary widely. There's nothing that says UB can't allow the derived member function to be called successfully (but there's nothing that guarantees that it will, so don't count on it). Here is the rule fo...
6,322,970
6,323,091
Should std::vector::swap() with stateful allocators invalidate all iterators?
Given allocators a1 and a2, where a1 != a2, and std::vectors v1(a1) and v2(a2) then v1.swap(v2) invalidates all iterators. Is this expected behavior?
In general, swap never invalidates iterators. However, another rule comes into play when the allocators are different. In that case the behavior depends on allocator_traits<a1>::propagate_on_container_swap::value and allocator_traits<a2>::propagate_on_container_swap::value. If both are true, the allocators are excha...
6,323,255
6,323,432
Infer subclass template types in a template
I have a class that derives from a templated class: template <typename A,typename B> class TemplatedClass { }; class Hello : public TemplatedClass<int,float> { }; Now, I want to make a templated class that will infer the types int,float from Hello. I thought I could do something like this, but it doesn't work: tem...
First, change that typename to class, §14.1 [temp.param] p1: type-parameter: class identifieropt class identifieropt = type-id typename identifieropt typename identifieropt = type-id template <template-parameter-list > class identifieropt template <template-parameter-list > class identifieropt = id-expression Next,...
6,323,289
6,323,375
C/C++ Static vs dynamic libraries example
I'm learning about static and dynamic libraries. So far I understand why I would need a dynamic library. In case something is changing it's good to plug in a newer version and all the applications will update automatically without even noticing. a) Great for plugins, b) multiple apps using the same library and c) main...
A static library is basically a ZIP of object files. The only advantage it has over just distributing the object files is that it's a single file that encompasses your whole library. Users can use your headers and the lib to build their applications. Because it's just a ZIP of object files, anything the compiler does t...
6,323,619
6,323,624
C++ ifstream error using string as opening file path.
I have: string filename: ifstream file(filename); The compilers complains about no match between ifstream file and a string. Do I need to convert filename to something? Here's the error: error: no matching function for call to ‘std::basic_ifstream<char, std::char_traits<char> >::basic_ifstream(std::string&)’ /usr/in...
Change ifstream file(filename); to ifstream file(filename.c_str()); Because the constructor for an ifstream takes a const char*, not a string pre-C++11.
6,323,885
6,323,912
Array initialization in c++?
int main() { clrscr(); int x[3]; int n; cout<<"Enter the array size= "; cin>>n; cout<<"Enter the elements for array= "; for(int i=0;i<n;i++) { cin>>x[i] ; } for(i=0;i<n;i++) { cout<<"x["<<i<<"]="<<x[i]<<"\n"; } getch(); return 0; } When m trying t...
If you have an array: char array[3]; And you try to write into an element that doesn't exist: array[15] = '!'; Then this is an error. However, a compiler is not required by the C++ Standard to diagnose this error, and most do not. This is because it would require computation every time you accessed the array to deter...
6,323,984
6,324,014
Passing object parameter to a functor by reference
I've got a functor that takes a lat3d object as a parameter, and I want to pass this functor to a root finding routine that adjusts ef. The functor looks like: struct NormalizeNer { NormalizeNer(lat3d &lat) : lat(lat) {} double operator()(const double ef) { lat.setEf(ef); //...
The member variable lat should be a reference as well: lat3d &lat; In your current code, the NormalizeNer constructor accepts a reference but then makes a copy.
6,323,993
6,324,061
How to check if char* p reached end of a C string?
template<class IntType> IntType atoi_unsafe(const char* source) { IntType result = IntType(); while (source) { auto t = *source; result *= 10; result += (*source - 48); ++source; } return result; } and in main() I have: char* number = "14256"; atoi_unsafe<unsigned>(n...
while(source) is true until the pointer wraps around to 0, but will probably crash well before that in modern systems. You need to dereference the pointer to find a null byte, while(*source). I hate posting short answers
6,324,133
6,324,158
Help with queue and singly linked lists?
Im currently working on trying to understand Lists, Stacks, and Queues in C++. Im reviewing for my test and came across a question asking to "efficiently implement a queue class using a singly linked list, with no header or tail nodes." Im kind of stumped, does anyone know how to do this?
Hint: Queues are often implemented using circular buffers. How would you create a circle with a singly linked list?
6,324,299
6,324,347
Problem throwing and catching custom exceptions in C++
I've created the class Someting which throws an exception SomethingException (SomethingException inherits from std::exception) when it fails to instantiate. the problem is I can't catch SomethingException as such (I had to do a dirty trick to catch it). There is somewhere in the program where it executes: This doesn't ...
In general it's best to throw exceptions by value and catch them by reference: try { throw SomethingException(); } catch (const SomethingException& error) { std::cerr << error.what() << '\n'; } You would only be able to catch an exception with catch (SomethingException*) if you were to throw it with throw ...
6,324,300
6,324,389
subclassing with or without virtuals vs performance vs convenience
It is well-known that STL classes do not use virtual methods anywhere (and STL does not use inheritance anywhere, too, and that these two facts are inter-related), and that STL is not unique in that. Let's assume that other performance freaks exist on earth [well they exist], such performance freaks who ask themselves...
Question: is there technique (for c++) that allows programmer to create in one shot two versions of same class X, a "non-virtuals" version Xnv (for performance), and "virtuals" version Xv, for subclassing ? Why do that, when you can have your cake and eat it too? With CRTP, you have compile-time polymorphism, and the...
6,324,326
6,324,532
passing multiple strings from c to java(jni) in a function
In JNI when we want to pass a string from C to java we do it by(C++): return env->NewStringUTF("MY String"); As this is a return statement, it can be called just once ie. Only 1 string can be passed from C to Java. What about the function in which we want to pass multiple String from C to Java?! For example consider t...
This can be achieved by a) calling java methods (call backs) in the for loop (which are essentially setters for the required array). b) passing jbyte(int) array as argument and filling it in loop. c) method you mentioned in question - packing the return object(in byte array) and returning it ; unpack it in java side. ...
6,324,452
6,324,468
best way to implement a sql statement binding in C++
Ok so I am writing a DB wrapper in c++0x, the API is in C. I have preprepared statements which I can bind at runtime. I would like to bind and execute the statement in 1 function call to the wrapper. My initial though is to use variation templates. but with the documentation I have seen I have not found out how to limi...
Take advantage of function overloading. void bind(std::string& arg) { bindstring(arg); } void bind(int& arg) { bindint(arg); } ... std::vector<boost::variant<double,std::string,int>> args = {...} for (auto arg : args) bind(arg); -- edit -- Another approach using variadic template void bind(std::string& arg) { bi...
6,324,694
6,324,714
Type erasure in C++: how boost::shared_ptr and boost::function work?
Type erasure - is that how you call it? How boost::shared_ptr stores its deleter and how boost::function stores its function object? Is there any tutorial that teaches the trick? What is the run-time cost of using type-erased function objects?
The idea is simple, you define a base class that has an interface with the functionality you need, and then inherit from it. Since the type erased class uses only that interface, the actual type underneath is forgotten and erased. Alternatively, if the only needed interface can be expressed as free functions you can st...
6,324,994
6,325,001
C++ multithread safe local variables?
I know that that question may be seemed as a duplicate, but I haven't got the answer reading the other questions. My situation - Visual C++ compiler 2005 from express edition studio + Windows sdk. Just a question if a function like that: void myFunc() { int i=0; i++; } is safe to call from multiple threads? Ye...
Yes, it is thread safe. i will not be static in memory, because it is not static. If, on the other hand, you had written: void myFunc() { static int i = 0; i++; } Then it would not be thread safe (well, if i was actually used). Local variables are all located on the stack (or live entirely in registers). Each ...
6,325,069
6,325,172
Get a pointer to an object in a std::set (c++)
I have a std set S. S contains a few instances of MyType. Is this the best way to get a pointer to an instance of MyType in S? MyType *pointerToMyType = (MyType*)(&*S.find(anotherInstanceOfMyType)); The above code works. I'm just not sure if it's the best or safest way. Edit: I do check the result of find to S.end...
You should not take a mutable reference or pointer to an element in a set. If you change it's properties, then you will invalidate the container's invariants, causing Undefined Behaviour. That compile-time error is there for a good reason, and furthermore, your code shows an excellent example of why C-style casts are b...
6,325,238
6,325,260
c++ execute code from no file system
First of all, had a hard time figuring out a title, and it's a bit ambiguous, but oh well. Alright, so I have a mixed c++ & asm bootloader program. I can copy it onto my mbr and run it. The only problem I'm having is the fact that the mbr is very small. I'm assuming the purpose of it is to only call external code writt...
The BIOS sets up several interrupt handlers before running the code in the MBR. One of these can be used to do things like read/write sectors directly from the hard drive without a OS, device driver, or file system. That's interrupt 19 (13H as its more commonly known). You'll need to use that to read the code, then ju...
6,325,248
6,325,296
gluUnproject Question/moving character question
hi every1 i have been reading lots of posts here about how to use gluUnproject and i think ive got basically what its doing. but yeah my problem is this.. ive got 1 plane and if i click in there theres no problem my object goes there but if i click outside of it well my object dissapears any idea why is it doing this a...
Check the depth you read from the depth buffer. If the depth value is the glClearDepth value you set (or close enough to it), then you know that nothing was rendered there. So don't position the object at that location.
6,325,288
6,325,326
Creating static array in c++ at run time
Is there any way of creating a static array in c++ at run time. What i want is really simple like just want to get input number from user and create a static array of size of input number at run time. No new operator is required no pointer are required just static array?
If you mean unsigned size; std::cin >> size; int arr[size]; Then: No. C99 has a feature called Variable-Length-Arrays, but the C++03 (and '0x) standard have no notion of this kind of feature.
6,325,291
6,325,341
Why can I extend a private nested class by a template class?
I have come across a bit of an oddity where it seems a template class can extend a private nested class. Given the following private nested class: class A { private: class B { protected: void doSomething() { ... } }; }; The following does not compile, as expected: class C : public A::B { public: ...
That should be a compiler error. The class is not accessible from any class that is not a friend of A, including any instantiation of a class template. GCC 4.2.1 and 4.6 accept that code Clang++ rejects it with the error message error: 'B' is a private member of 'A' struct C : A::B { Comeau rejects the code with a s...
6,325,396
6,325,426
How to test assertions?
I am using a unit testing framework to test my libraries. I have quite a few assertions in the library to make sure that programmer errors are caught in debug builds. Now I want to make sure I am testing for all possible programmer errors. E.g. in a Table class, I want to make sure that the rows and cols passes are no...
The question then becomes are you planning on refactoring your code so that if this condition occurs you'll throw an exception instead of relying on <cassert> functionality to clue you into a problem? If so, you can just check that the exception was thrown. If not, then it's going to be more difficult to test an asse...
6,325,483
6,325,533
C++ check if string is space or null
Basically I have string of whitespace " " or blocks of whitespace or "" empty in some of the lines of the files and I would like to know if there is a function in C++ that checks this. *note:* As a side question, in C++ if I want to break a string down and check it for a pattern which library should...
Since you haven't specified an interpretation of characters > 0x7f, I'm assuming ASCII (i.e. no high characters in the string). #include <string> #include <cctype> // Returns false if the string contains any non-whitespace characters // Returns false if the string contains any non-ASCII characters bool is_only_ascii_w...
6,325,515
6,325,711
Using GCC dependency files causes Make to rebuild project completely every time
I've followed the instructions online to set up gcc (actually g++) to generate .d files for dependencies, and now my makefile looks something like this: CPPFLAGS := ... -MMD -MP ... OBJECTS := $(shell find *.cpp *.s | sed -e 's/\.cpp/\.o/' -e 's/\.s/\.o/') all: setupdir $(OBJECTS) link image And then at the end of the...
It's important to note that -M is not magic bullet for dependencies, in many cases you'll need to specify certain headers so things are re-built appropriately if they change. In fact, the most common problem with letting gcc handle dependencies is things not being re-built that should be (broadly depending on the vers...
6,325,644
6,325,666
Boost Asio example - strange C++ syntax
I've just been having a look at the boost asio framework and the examples. In the source code for Daytime.3 - An asynchronous TCP daytime server, the code defines a constructor for the tcp_server class as follows: tcp_server(boost::asio::io_service& io_service) : acceptor_(io_service, tcp::endpoint(tcp::v4(), 50500)) ...
Uhm.. why shouldn't it be able to do so? The member variables are visible through-out the whole class, no matter where they are defined: class Foo{ public: Foo(int i) : _i(i) {} private: int _i; }; If you meant how that while initialization thing works after the colon :, search for "initializer list"/"ctor initia...
6,325,661
6,325,844
Dwarf Error: Cannot find DIE
I am having a lot of trouble debugging a segmentation fault in a C++ project in XCode 4. I only get a segfault when I built with the "LLVM 2.0" compiler option and use -O3 optimization. From what I understand, there are limited debugging options when one is using optimization, but here is the debug output I get after I...
I don't think there's enough information that I can help you with the DWARF issue. I am not familiar enough with that toolchain to know how robust it is. Your crashing symptoms however smell a lot like heap corruption. I don't know what allocator OSX uses by default, but common optimizations store metadata inline wit...
6,325,699
6,325,965
How to save to a bitmap in MFC C++ application?
I am just starting with MFC so please be tolerant ;). I have wrote (it was mostly generated to be honest) a simple application which should do the Paint chores: drawing lines, rectangulars, ellipses, changing a color of object to be drawn etc. I need to save what has been drawn on the screen into a bmp file. Any ideas ...
The CreateBitmap call only requires the desktop width and height if the image you wish to save is actually the entire size of the screen. If that's indeed your intent, you can use CWnd::GetDesktopWindow() to get a CWnd object that you can query for its width and height: http://msdn.microsoft.com/en-us/library/bkxb36k8...
6,325,745
6,325,790
Need pow(-1,1.2) to be 1
I am using math.h with GCC and GSL. I was wondering how to get this to evaluate? I was hoping that the pow function would recognize pow(-1,1.2) as ((-1)^6)^(1/5). But it doesn't. Does anybody know of a c++ library that will recognize these? Perhaps somebody has a decomposition routine they could share.
It seems like you're looking for pow(abs(x), y). Explanation: you seem to be thinking in terms of xy = (xN)(y/N) If we choose that N === 2, then you have (x2)y/2 = ((x2)1/2)y But (x2)1/2 = |x| Substituting gives |x|y This is a stretch, because the above manipulations only work for non-negative x, but you're the one wh...
6,325,887
6,326,099
Calling a function in a shared library given its name and signature
I have a little DSL that needs to be able to load shared libraries and run functions that they export. Finally, a solved problem: dlopen, dlsym, LoadLibrary, and GetProcAddress are all you need for cross-platform use of dynamic libraries. This is easy! C++ disagrees. Thanks to dlsym, etc., I've got everything I need: a...
Use libffi to call the function. If you have a pointer to the function, and you know its argument & return types, you're golden. Ffi knows how to deal with the platform-specific ABI, building the stack frame, pushing the arguments and popping the return value, etc. C++ name-mangling makes this a bit more difficult, but...
6,325,894
6,325,924
std::istreambuf_iterator "peek" with std::ifstream
When dealing with streams of data, I prefer to write the code in terms of templates and iterators. Often I need to "peek" at the next character. In order to make the code be able to deal no-bidirectional iterators, I have a snippet which looks like this: template <class I> I next(I it) { return ++it; } Obviously, ...
Well, it actually doesn't increment all iterators but rather consumes the stream, which in the end has the same effect. If you want to peek ahead, you need to do so on the stream itself, AFAIK.
6,325,925
6,325,970
Splitting a char* at its many '\0' chars
The following is in C++. I have a string that contains the environment variables I need to split it at the declaration of each variable & store it in a string: char* envVars = "=::=::\0system=blah\0othervar=blah\0" So I am using cstring functions to split the string at the occurence of the null terminator char '\0' bu...
I would have expected this to exit immediately, but actually the man page says: The terminating null character is considered to be part of the string; therefore if c is '\0', the functions locate the terminating '\0'. Of course, the result of pos = strchr(environVar, '\0'); is that *pos == '\0' and strlen(pos) == 0. ...
6,325,996
6,326,007
Calling a C, C++ program from Java
Is it possible to call C or C++ code from a Java Code, i can re-write the code in Java, but need to reuse the existing code.. Thanks
Yes, it's possible using the Java Native Interface.
6,325,998
6,326,005
How free handles null pointer
Possible Duplicates: checking for NULL before calling free What happens when you try to free() already freed memory in c? Hope this isn't a totally dumb question. Anyway... What happens when a null pointer is passed to free. Thank you! P.S. What about a standard compliant allocator? Thanks again!
It immediately returns without doing anything. Per 7.20.3.2, paragraph 3: The free function causes the space pointed to by ptr to be deallocated, that is, made available for further allocation. If ptr is a null pointer, no action occurs. Otherwise, if the argument does not match a pointer earlier returned by the cal...
6,326,032
6,351,678
No rule to make target /usr/lib/libX11.so
I'm writing a program using the library SFML, which requires libX11. I just recently upgraded to ubuntu 11.04 from an older version, and ever since I did I can't compile my program. I get the following error: make[3]: *** No rule to make target `/usr/lib/libX11.so', needed by `lib/libsfml-window.so.2.0.0'. Stop. I th...
Turns out a simple make clean on everything was all I needed. I'm still unclear as to what happened between updates, but everything compiles and works when I rebuild the project form scratch.
6,326,064
6,326,125
C/C++ sockets and a non-blocking recv()
I'm having a problem where calling recv() system call does not block. I have a client-server structure setup at the moment, and the problem I am having is I send the server one message, while the server is set up so that it's something like: while (1) { char buf[1024]; recv(fd, buf, sizeof(buf), flags); proces...
recv() does not necessarily block until the full request is fulfilled but can return a partial request. The return code will inform you of how many bytes were actually received which can be less than you requested. Even if you specify a MSG_WAITALL flag it can return less due to a signal, etc. On posix systems, in bl...
6,326,199
6,326,305
Stack around variable corrupt, not sure what the problem is
Problem solved, thank you all for the help I've got a bit of a problem here it's not something that's blowing my program up, but it's just bothering me that I can't fix it. I have a function reading in some data from a file, at the end of the execution, the stack around variable longGarbage is corrupted. I've looked ...
What's happening is that something is writing to memory around or over the location of longGarbage which is causing the corruption. You don't say what development environment you are using. One way to diagnose this would be to set a breakpoint that triggers when a specific memory location changes. Choose a memory l...
6,326,534
6,326,684
Can storing unrelated data in the least-significant-bit of a pointer work reliably?
Let me just say up front that what I'm aware that what I'm about to propose is a mortal sin, and that I will probably burn in Programming Hell for even considering it. That said, I'm still interested in knowing if there's any reason why this wouldn't work. The situation is: I have a reference-counting smart-pointer cl...
Any reason? Unless things have changed in the standard lately, the value representation of a pointer is implementation-defined. It is certainly possible that some implementation somewhere may pull the same trick, defining these otherwise-unused low bits for its own purposes. It's even more possible that some implementa...
6,326,757
6,327,305
Conversion from boost::shared_ptr to std::shared_ptr?
I got a library that internally uses Boost's version of shared_ptr and exposes only those. For my application, I'd like to use std::shared_ptr whenever possible though. Sadly, there is no direct conversion between the two types, as the ref counting stuff is implementation dependent. Is there any way to have both a boos...
Update to an "off the top of my head" answer, almost eleven years later: As pointed out in this answer, an implementation is allowed to extend the lifetime the deleter beyond the lifetime of the shared_ptr. For example, until after all weak_ptr instances are also destroyed. This would cause a problem where the presence...
6,326,805
6,326,867
Why is "using namespace X;" not allowed at class/struct level?
class C { using namespace std; // error }; namespace N { using namespace std; // ok } int main () { using namespace std; // ok } I want to know the motivation behind it.
I don't know exactly, but my guess is that allowing this at class scope could cause confusion: namespace Hello { typedef int World; } class Blah { using namespace Hello; public: World DoSomething(); } //Should this be just World or Hello::World ? World Blah::DoSomething() { //Is the using namespace va...
6,326,828
6,326,848
how do I include header files like list.h, queue.h and vector.h in C++ file?
I downloaded a sample code and cpp files include header files like list.h, queue.h, and vector.h and if I try to build then I got "fatal error: No such file or directory compilation terminated" I think I should include the path to the system library that has those header files but I don't know how to do that. Thanks in...
Most modern "stock" C++ headers don't have a filename extension. #include <list> #include <queue> #include <vector>
6,326,874
6,326,884
C++ Access violation writing location 0x0... setting int *
I've looked through various questions both here and other places, but I still cannot explain the access violation error I'm getting. "Access violation writing location 0x00000000" corresponds to a NULL pointer, correct? I've declared an int pointer, and I later try to set a value at that location. Shouldn't the memory ...
Memory is allocated for the pointer, but the pointer itself still doesn't point anywhere. Use new to allocate memory for the pointer to point to, and free it with delete later.
6,326,907
6,326,952
C++ allocating memory using array
concerning this question on how to allocate memory without using new or malloc, suppose I have a structure linked list struct stack { string info; stack next*; }; The answer provided says use global byte array. How would I implement an linked list by allocating to global byte array?
One way is to have a memory pool declared in data segment and have your own memory allocation function. char myMemoryPool[10000000]; // global variable (can be enclosed in namespace) And you have to write your own memory manager: void* MyMemoryAlloc (size_t SIZE) { //... use SIZE } Usage: A* p = (A*)MyMemoryAlloc(si...
6,327,030
6,327,081
C++ Design pattern for using a abstract class object in another class
I'm having a class with 2 pure virtual methods and another class which needs to use an object of this class. I want to allow the user of this class to specify which derivation of the abstract class should be used inside of it. I'm struggling to figure out what the right way is. struct abstract { virtual int fst_fun...
I would say that passing the abstract object into the constructor of your user is the proper approach as the methods of the user depend being called on the same abstract object. I would even go further and make the x parameter an internal state of your user as you have said it's important that this value is the one ret...
6,327,082
6,327,394
Launching exe from an application
I have to launch an exe from other application.There is code in the internet to do it. I wanted to discuss how the Application get the path of the other exe to launch, Since path of the exe can be any. Is Storing in the registry or config is the option?? What an application should do if the exe already running. Ple...
You have two choices for launching EXE files: ShellExecuteEx(), and CreateProcess(). Each behaves a bit different, check them out on MSDN. As for the varying path, the registry may be a good alternative.
6,327,172
6,327,194
How expensive is it to copy a map?
I have a map<EntityState, boost::weak_ptr<Animation>> in my EntityRepresentation class. I would kinda want to create a Builder class for the representation, but I have to consider the costs of copying the map. EntityState is cheap to copy since it's just a collection of static functions; boost::weak_ptr is also cheap t...
It depends on the number of items it has. I don't think its own members will cause much problem.
6,327,196
6,327,274
Marshalling C# Jagged Array to C++
I'm trying to marshal a 2D C# jagged array (double[][] jaggedArray) to a C++ dll where i've specified the receiving variable to be a double**. However, i'm getting the message: There is no marshaling support for nested arrays. Short of flattening the jagged array is there a way to use jagged arrays from C# in a C+...
Using low level Marshal class methods, it is possible to marshal any type to unmanaged memory. For example, for every double[] array in jaggedArray, allocate unmanaged memory block with Marshal.AllocHGlobal, and copy array members to it using Marshal.Copy Method (Double[], Int32, IntPtr, Int32) method. AllocHGlobal ret...
6,327,223
6,327,306
Switching on enum class in C++ 0x
Will new "enum class" declarations in C++ 0x allow switching on the new-fangled enums? I'm asking what the standard says, not about the compiler support.
From the n3242 draft: 6.4.2 The switch statement [stmt.switch] [...] 2 The condition shall be of integral type, enumeration type, or of a class type for which a single non-explicit conversion function to integral or enumeration type exists (12.3). 7.2 Enumeration declarations [dcl.enum] [...] enum-key: enum ...
6,327,343
6,327,356
length of string containing \0
char p[]="abc\012\0x34"; printf("%d\n",strlen(p)); I am getting output 4. Shouldn't it be 3 ??? Although for following i am getting 3. char p[]="abc\0"; printf("%d\n",strlen(p));
Your string does contain four characters before the \0, i.e. abc and \012. The latter is a valid octal escape sequence, which is 10 in decimal, i.e an ASCII linefeed character. \0x34 on the other hand isn't valid octal - only the \0 part is valid hence that's the real end of your NUL terminated string.
6,327,639
6,327,653
How do I interpret this C++ code?
NetworkManager::NetworkManager():m_Thread(0), m_Continue(true), m_Init(false){ } The first one is a name space and the second one is the name of the function. and what are those three parameters?. I think it might be related to the inheritance but those are not the class name. Those are the private variables. Thanks i...
That's the definition of a constructor - there are no namespaces. NetworkManager :: NetworkManager() : m_Thread(0), m_Continue(true), m_Init(false){ } The constructor is for a class called NetworkManager, and it is initialising its members using an initialisation list. What's going on is conceptually (if not complete...
6,327,784
6,327,870
How to use libjpeg to read a JPEG from a std::istream?
libjpeg can read JPEG data from a FILE* or a buffer. My data is coming from a std::istream. I could read the entire std::istream into a buffer to use with libjpeg, but I'd rather have libjpeg read directly from the std::istream if possible. How can this be done?
You just need to provide wrappers around your istream. Define a struct, for instance struct JpegStream { jpeg_source_mgr pub; std::istream* stream; byte buffer [4096]; } Then you need four methods to operate on the stream: void init_source (j_decompress_ptr cinfo) { auto src = (JpegStream*)(cinfo->src); ...
6,327,960
6,328,115
Pointer to vector in a struct C++
I am getting a few crashes related to the fact that I use a vector in my struct that may have to use about 6000 elements. Here is my struct: struct Students { char* names; std::vector<int> scores; }; Is there a way to make it so my vector is not causing my struct to cause an error. Here is my calling code. while(scor...
You remind me of a similar problem someone here met before. As there is no enough information provided for the rest of your code, I just make a guess here. Obviously students is an array of structure Students. Assuming it's allocated on the heap, if you do that using malloc, it won't work properly because malloc won't ...
6,327,976
6,328,017
What are the concepts I need to learn to completely use all features of gcc/g++ compiler?
Can you explain to me what the options mean in the following g++ command to build a boost.python object? # location of the Python header files PYTHON = /usr/include/python2.7 # location of the Boost Python include files and library BOOST_INC = /usr/include BOOST_LIB = /usr/lib # compile mesh classes TARGET = ex1 $(...
GCC has probably more options than any other existing program - literally thousands of them. You certainly are never going to need them all, but you will need to understand some, so you need to read the GCC documentation.
6,328,034
6,328,148
ELF file structure in FreeBSD & Linux
In PE (for windows) it is possible to read the headers/sections of that structure by #include<windows.h> and can use the struct PIMAGE_DOS_HEADER to read the dos header in any PE file, for example. How can i do that for ELF header in FreeBSD/Linux? What kind of preprocessor need to be added at the head of the C/C++ co...
You're looking for libelf.
6,328,167
6,328,209
C++ class containing arrays
I'm starting a C++ app project that basically has an object class as it's core to hold the data, then some functions will process that object's data to get the info required. I've written similar to this before in VB.net, and I've written small programs in C++ before, but that was back in Turbo C++ and didn't include c...
struct struct_Tags { struct struct_TagProps { string Name; string Value; }; string TagName; vector<struct_TagProps> TagProperties; bool HasProperties() const { return !TagProperties.empty(). } }; vector<struct_Tags> obj_Tags; To insert something: struct_Tags newValue;...
6,328,191
6,328,341
What's an efficient way to convert "unsigned char" array to its "unsigned short" counterpart?
What's an efficient way to convert "unsigned char" array to its "unsigned short" counterpart? I usually use the following code snippet to do so. #define CH_LINE_PIXELS 2291 #define SCANLINE_SIZE 57301 #define CH1_INDEX 2297 #define CH2_INDEX 4592 #define CH3_INDEX 6887 #def...
Addressing short on byte boundary may (or may not) cause alignment issues, depending on platform. Also, multiplying is very ineffective, why not use shifting instead? (some compilers may optimize x * 0x100, but if they don't - it's a huge performance hit when all you want is just x << 8...) Also, as noted, reinterpret...
6,328,439
6,328,558
C++ : Confused on something about functions
#include <iostream> using namespace std; int myFunc (unsigned short int x ); int main () { unsigned short int x, y; x=7; y = myFunc(x); std::cout << "x:" << x << "y: " << y << "\n"; return 0; } int myFunc (unsigned short int x ) { return (4 * x ); } Now this ^ Code works, but when I change y...
That's because the compiler expects the value of type unsigned short int, but you've passed a type int. What did you expected to get? The result of 4*int is undefined. You can pass types when you use templates. Take a look on the following sample: // Here's a templated version of myFunc function template<typename T> T...