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 |
|---|---|---|---|---|
4,698,163 | 4,698,177 | Any Disadvantage to using String (C++) | I actually checked on google for this but I usually found the reverse.
Is there actual any disadvantage in C++ to using the string library strings instead of C strings or some kind of character arrays? besides maybe being a bit slower?
Feel free to point me to a dupe, however I've searched and couldn't find anything (a... | There's really no significant disadvantage, assuming the vendor implementation of std::string is competent. The std::string class is not likely to be any slower than plain C-strings with compiler optimizations turned on.
Even if you find yourself in a situation where you need a C string (like say, you need to work wit... |
4,698,267 | 4,698,282 | C++ : Assignment and checking for NULL on new/delete | Is the assignment and check for null explicitly required in the below snippet to achieve the same result. Also, is there anything wrong or can be improved here.
class Sample
{
private:
char *bits;
public:
Sample()
{
bits = NULL; //should this be explicit?
}
~Sample()
{
if (... | In the first case, where you do this in the constructor:
Sample()
{
bits = NULL;
}
Whether or not you need this assignment depends on your code - if bits may not have any memory allocated to it at all, then the NULL assignment should be there because of the delete in the destructor. And really as a safety issue, y... |
4,698,420 | 4,698,613 | Error including <vector> in Netbeans (C++) | This is odd. I'm getting errors for including <vector>: (edit: works fine with <list> but I don't want to forsake vectors)
g++.exe -c -g -MMD -MP -MF build/Debug/Cygwin-Windows/main.o.d -o build/Debug/Cygwin-Windows/main.o main.cpp
from MemoryScanner.h:11,
from main.cpp:10:
/usr/lib... | /Facepalm. I just needed to remove #include <windows.h> from main.cpp because it's already included in MemoryScanner.h
|
4,698,852 | 4,699,255 | c++ problem with vector push_back | UPDATE:
The following code gives me an error
Graph.cpp: In function 'std::ostream&
operator<<(std::ostream&, const
Graph&)': Graph.cpp:43: error: passing
'const std::map >,
std::less,
std::allocator > > > >' as
'this' argument of '_Tp&
std::map<_Key, _Tp, _Compare,
_Alloc>::operator[](const _Key&) [wit... | The cause of your problems is that map's operator[] is a mutable operation (if the key doesn't exist, it will be added to the map).
You will have to use the iterator returned from find():
map< lint, vector<lint> >::const_iterator it = inGraph.adjList.find(i);
if (it != inGraph.adjList.end();
for(lint idx = 0; idx < it-... |
4,698,946 | 4,698,975 | What could cause a returning function to crash? C++ | So I have been debugging this error for hours now. I writing a program using Ogre3d relevant only because it doesn't load symbols so it doesn't let me stack trace which made finding the location of the crash even harder. So, write before I call a specific function I print out "Starting" then I call the function and imm... | Most of the times when something weird and un-understandable happens, it's because of something else.
You could have some dangling pointers in your code (even in a place far away from that function) pointing to some random memory cells.
You might have used such dangling pointer, and it might have resulted in overwritin... |
4,699,048 | 4,699,085 | Getting the symbols of kernel32 |
Is the Symbol Server the only way to get the symbols of kernel32.dll in C++/Windows?
thanks:)
| You could download symbol packages too. Start point is here.
|
4,699,084 | 4,699,110 | Initialization of static class variable inside the main | I have a static variable in the class.
I am Initializing that in the global scope, its works fine.
But
When I try to Initialize in the main linker throws an error.
Why it so.
class Myclass{
static int iCount;
} ;
int main(){
int Myclass::iCount=1;
}
And In global scope why I have to specify the variable type... | The section $9.4.2/7 from the C++ Standard says,
Static data members are initialized
and destroyed exactly like non-local
objects (3.6.2, 3.6.3).
Note the phrases "initialized" and "exactly like non-local objects". Hope that explains why you cannot do that.
In fact, static members are more like global objects acc... |
4,699,148 | 4,699,222 | Why doesn't OnKeyDown catch key events in a dialog-based MFC project? | I just create a dialog-based project in MFC (VS2008) and add OnKeyDown event to the dialog.
When I run the project and press the keys on the keyboard, nothing happens. But, if I remove all the controls from the dialog and rerun the project it works.
What should I do to get key events even when I have controls on the di... | When a dialog has controls on it, the dialog itself never gets the focus. It's stolen by the child controls. When you press a button, a WM_KEYDOWN message is sent to the control with focus so your CgDlg::OnKeyDown is never called. Override the dialog's PreTranslateMessage function if you want dialog to handle the WM_KE... |
4,699,158 | 4,699,176 | Can you use Win32 GUI in a browser plugin? | Of course it would mean you're plugin is not cross-platform but let's focus on the technical side...
Is a browser plugin (like done in NPAPI) restricted in what it can do? Or do you get fairly free reign to access the PC and the render-window you're given? For instance can you create Win32/MFC controls in your browser ... | There are 2 types of NPAPI plugins: windowed and windowless plugins. Both of them has some advantages and disadvantages (see this link). When you deal with windowed plugin on Win32 you get HWND of browser plugin window and you can work with it like with any window in OS.
|
4,699,301 | 4,699,358 | GetCurrentDirectory for startup App. c++ |
Possible Duplicates:
Win32: Find what directory the running process EXE is stored in
How to get the application executable name in Windows (C++ Win32 or C++/CLI)?
hi,
i want to make my application run on statup,it uses some of files in the same directory.it works good but when it start at startup the GetCurrentDirec... | Try using GetModuleFileName or GetModuleFileNameEx.
Do this:
wchar_t exeDirectory[1024]; //to store the directory
DWORD ret = GetModuleFileName(NULL, exeDirectory, 1024);
if ( ret )
{
/*the path to your EXE is stored in the variable "exeDirectory" - use it */
}
Note I'm passing NULL as first argument, because MSDN s... |
4,699,568 | 4,699,676 | OpenGL Icosahedron Texture Mapping | I've got currently no solution for texture mapping an icosahedron without a seam from pole to pole. The texture mapping of this primitive seems to be a common problem, which is not completely solved yet. I've made a lot of research and I've tried a lot of different approaches for generating the uv coordinates, the most... | You need to change your texture image, the texture image you have is a distortion of the sphere where the pole is stretched into a line, you will never be able to map this properly to an icosahedron, in order to do so you would need a division more like the longitude and latitude system which such a distortion comes fr... |
4,699,784 | 4,699,791 | Access violation on char * arr[5] = {...}, what is this? |
Possible Duplicate:
Modifying C string constants?
can you explain why i get access violation on the mentioned line? i guess that is my process memory and i can access and change it's content.
#include <stdio.h>
int main()
{
char* list[5]={"An","exam","on","Hall oween","night!!!!"};
char **p;
p=list;
... | Your code is equivalent to p[1][2]='A'; i.e. it wants to set the third char in the second string.
But since the strings are string literals they are immutable and you get undefined behavior when you try to modify their content. In particular they can be located in readonly memory. In which case you get an access violat... |
4,699,808 | 4,753,524 | Can't add minimize button to QDialog under linux | I'm trying to add a minimize button to my QDialog using this code in the constructor:
Qt::WindowFlags flags = windowFlags();
flags |= Qt::WindowMinMaxButtonsHint;
setWindowFlags(flags);
It's working on Windows but not on Linux.
| Its a late answer but could be useful to others, I had the same problem and fixed like so:
Qt::WindowFlags flags = Qt::Window | Qt::WindowSystemMenuHint
| Qt::WindowMinimizeButtonHint
| Qt::WindowCloseButtonHint;
this->setWindowFlags(flags);
inside the overridden... |
4,699,910 | 4,700,035 | GTK+ gio No such file or directory | I'm using VC++ 2008 and I've the code:
#include <gtk/gtk.h>
int main( int argc, char *argv[])
{
GtkWidget *window;
gtk_init(&argc, &argv);
window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
gtk_widget_show(window);
gtk_main();
return 0;
}
And in every compiler i get same error: gio/gio.h: No such file or d... | You also need to install gtk includes (the folder with gtk.h) and specify that path in the Include paths of your compiler.
Also be aware that GTK depends on several other libraries, including gobject and glib. You will need to install them too.
|
4,700,052 | 4,700,073 | Are vector a special case of linked lists? | When talking about the STL, I have several schoolmates telling me that "vectors are linked lists".
I have another one arguing that if you call the erase() method with an iterator, it breaks the vector, since it's a linked list.
They also tend to don't understand why I'm always arguing that vector are contiguous, just l... | I'm sorry to say that your schoolmates are completely wrong. If your schoolmates can honestly say that "vectors are linked lists" then you need to respectfully tell them that they need to pick up a good C++ book (or any decent computer science book) and read it. Or perhaps even the Wikipedia articles for vectors and li... |
4,700,063 | 4,712,070 | Using eclipse CDT without creating a project | I am currently learning c++.My first language was python.I am used to coding in eclipse in pydev.
I learn a language by writing a lot of code snippets and use the debugger extensively to understand what is actually happening.
Now,I downloaded CDT for eclipse,since I am used to the interface.
But now,I am forced to crea... | I suggest you create one project containing all your files (assuming each one has its own main function), and inside this project, create one 'Build configuration' per program by using :
Project > Properties > C/C++ Build > Configuration > Manage... > New
To avoid multiple definition of main in each 'Build configurat... |
4,700,184 | 4,700,205 | ffmpeg image to video frame length | hi i am useing ffmpeg to convert images into videos but images loads very fast and movie end very shortly how can i add a delay in images
i am useing this command
ffmpeg -r 10 -b 1800 -i %03d.jpg -vframes 100 abc.avi
| Lower the -r value, you have it currently set to 10 frames per second.
|
4,700,266 | 4,700,392 | Custom container with custom iterator doesn't work when container defined as const |
More or less everything is in the topic.
when I have
func(my_cont& c)
{ c.begin() };
things works, but
func(const my_cont& c)
{ c.begin() };
doesn't work, compiler claims that cant convert this to const my_cont<..>.... from my_cont<..>
What are the requirements for the container and my custom iterator to handle thi... | Your container class should have two implementations of begin() and end() - one returning iterator and another returning const_iterator:
iterator begin ();
const_iterator begin () const;
iterator end ();
const_iterator end () const;
const_iterator cannot be used to modify the object that it points to.
|
4,700,427 | 4,700,467 | Is main() a User-Defined Function? | The programmer does define what happens inside main(), after all.
So, should it be considered a user-defined function?
| The C++ standard doesn't have the notion of user-defined functions. Instead, it has the notion of library functions. main is not a library function. However, the standard also imposes some requirements on its signature, and that it must not be overloaded or declared static or inline. In particular, it must not be used,... |
4,700,508 | 4,700,546 | Why does the area come back as 0? | Here's the code.
int a;
int pi = 3.14;
int area;
int main()
{
cout << "Input the radius of the circle ";
cin >> a;
a *= a *= pi >> area;
cout << "The area is " << area;
}
| The area of a circle is pi * r * r therefore you would want to do;
a = a * a * pi
Hope that helps
and they all would need to be floats.
|
4,700,641 | 4,701,005 | problem with glreadPixels on iphone | I have no problem drawing a texture to the screen but I cant get the right pixels when printing them from memory. I have a 4x4 png image with 4 black pixels and I am trying to print them. This is what I do:
glBindTexture(GL_TEXTURE_2D, m_textureId);
const int size = m_width * m_height * 4;
GLubyte pixels[size];
glRea... | glReadPixels reads from framebuffers, not textures. To retrieve the contents of a texture object use glGetTexImage: http://www.opengl.org/sdk/docs/man/xhtml/glGetTexImage.xml
|
4,700,739 | 4,700,870 | tactics to think as a computer | I have some question from the exam in which I need to deduce the output of the following code:
01 int foo(int a) {
02 print 'F';
03 if (a <= 1) return 1;
04 return bar(a, foo(a-1));
05 }
06
07 int bar(int x, int y) {
08 print 'B';
09 if (x > y) return baz(x, y);
10 return baz(y, x);
11 }
12
13 int baz(int x, int y) {
1... | I would use a "bottom-to-top" attempt:
baz is the function that is called, but doesn't call other functions (except itself). It outputs 'Z' exactly y + 1 times, the return code is x*y (you add x after each call).
bar is the "next higher" function, it outputs 'B' once and calls baz with its lower argument as the second ... |
4,700,749 | 4,700,791 | Convert Hexdump to string in c | Is there a way to convert a hexdump e.g. aec4d2f3c6a4e70ea6cea074f65812d2a34b180cc92b817edcd867167e7a91c5beb942f0
to a string in c so that every two hexadecimal digits make a char? If so, what?
| Reads from stdin and prints to stdout:
int main()
{
int ch;
while(scanf("%2x", &ch) == 1)
putchar(ch);
}
I think you can modify it easily yourself for your specific source and destination requirements.
|
4,700,991 | 4,700,999 | C++ : Implementing copy constructor and copy assignment operator | After reading about copy constructors and copy assignment operators in C++, I tried to create a simple example. Though the below snippet apparently works, I am not sure whether I am implementing the copy constructor and copy assignment operator the right way. Could you please point out if there are any mistakes/improve... | Your copy assignment operator is implemented incorrectly. The object being assigned to leaks the object its base points to.
Your default constructor is also incorrect: it leaves both base and var uninitialized, so there is no way to know whether either is valid and in the destructor, when you call delete base;, Bad T... |
4,701,107 | 4,701,945 | How does Process Explorer enumerate all process names from an XP Guest account? | I'm attempting to enumerate all running process EXE names, and have stumbled when attempting this on the XP Guest account. I am able to enumerate all Process IDs using EnumProcesses, but when I attempt OpenProcess with PROCESS_QUERY_INFORMATION Or PROCESS_VM_READ, the function fails.
I fired up Process Explorer under t... | I suppose that the Process Explorer use NtQuerySystemInformation with parameter SystemProcessInformation to get the list of processes. For the code example see my old answer. Additionally the function NtQueryInformationProcess will be used to get additional information.
By the way, if you start Process Explorer under D... |
4,701,140 | 4,701,186 | Building static (but complicated) lookup table using templates | I am currently in the process of optimizing a numerical analysis code. Within the code, there is a 200x150 element lookup table (currently a static std::vector <std::vector<double>> ) that is constructed at the beginning of every run. The construction of the lookup table is actually quite complex- the values in the l... | Usually the best solution is code generation. There you have all the freedom and you can be sure that the output is actually a double[][].
|
4,701,256 | 4,701,279 | comparision function in stl::sort() | class node{
public:
unsigned long long int value;
int index;
};
bool comp2(node& a,node& b){
if(a.value < b.value) { return true; }
return false;
}
vector <node*>llist,rlist;
sort(llist.begin(),llist.end(),comp2);
Above code was giving me some weired error that is too in some other lines(places latter in co... | You have defined a std::vector of node *. Therefore, all the elements are node *, and all operations that the vector performs will be on node *. You can't give sort a comparison function of a different type.
|
4,701,282 | 4,702,499 | How to figure out why ssh session does not exit sometimes? | I have a C++ application that uses ssh to summon a connection to the server. I find that sometimes the ssh session is left lying around long after the command to summon the server has exited. Looking at the Centos4 man page for ssh I see the following:
The session terminates when the command or shell on the remote m... | Use libssh or libssh2, rather than calling popen(3) from C only to invoke ssh(1) which itself is another C program. If you want my personal experience, I'd say try libssh2 - I've used it in a C++ program and it works.
|
4,701,535 | 4,701,596 | Changing behaviour of double quotes when >> a stringstream | Here is what I'm trying to do:
say I have a stringstream. Then I << "\"hello world\" today";
then when I do
sstr >> myString1 >> myString2;
I would like myString1 to have "hello world"
and for myString2 to have "today"
Is there a way, possibly with a manipulator, to achieve this?
Thanks
| No.
You either need to change the stream type (and hence the parsing semantics) or use your own string type (and hence change the parsing semantics in your overloaded op>>).
Instead, consider writing a function, similar to getline, which parses a possibly-quoted "word" out of a stream:
getqword(sstr, myString1);
getqwo... |
4,701,659 | 4,701,673 | Strange beep when using cout | today when I was working on some code of mine I came across a beeping sound when printing a buffer to the screen.
Here's the mysterious character that produces the beep: ''
I don't know if you can see it, but my computer beeps when I try to print it like this:
cout<<(char)7<<endl;
Another point of interest is that th... | In ASCII the character 7 is the "bell" character that signals to the terminal that it should beep.
EDIT: To answer your followup question, it's really just for historical reasons. The old teletype terminals needed a way to alert the operator of an incoming message so a bell was used. The bell character told the termina... |
4,701,731 | 4,701,771 | How to pass a linc to class function and call it? | So I have a class like
class mySafeData
{
public:
void Set( int i )
{
myMutex.lock();
myData = i;
myMutex.unlock();
}
void Get( int& i)
{
myMutex.lock();
i = myData;
myMutex.unlock();
}
private:
int myData;
boost::mutex myMutex;
};
its i... | Sounds like you want something like this:
class myOtherData
{
public:
myOtherData(mySafeData& dataSource) :
myDataSource(&dataSource)
{}
private:
// note that if you take the advice in the comments,
// you don't need this wrapper function at all,
// it's simple just to call myDataSource.Get()
... |
4,701,808 | 4,701,830 | How could this code behave as I saw? | I have a C++ application that had a one time assertion failure that I cannot reproduce. Here is the code that failed once:
unsigned int test(std::vector<CAction> actionQueue) {
unsigned int theLastCount = actionQueue.size() - 1;
std::vector<CAction>::const_reverse_iterator rItr = actionQueue.rbegin();
std::vect... | I believe that if test() passed for all fileActions, theLastCount would be -1. Consider:
theLastCount starts at actionQueue.size() -1. You decrement it once for each item in actionQueue- that is, it is now actionQueue.size() - 1 - actionQueue.size() = -1. Think about it. theLastCount keeps the index of the current iter... |
4,701,837 | 4,701,857 | How to pass 2D map as a pointer to function | I have 2 maps:
map<int, map<int, int> > m1;
map<int, map<int, int> > m2;
And want to fill them in with a function:
void fillMaps (m1, m2) {
* m1[0][0] = 5;
* m2[0][1] = 4;
}
How should i pass those maps to the function?
I guess the variable itself can be passed just like this:
map<int, map<int, int> > m1;
map... | To change the maps in the function you'll want to pass them by reference:
void fillMaps (map<int, map<int, int> >& m1, map<int, map<int, int> >& m2) {
m1[0][0] = 5;
m2[0][1] = 4;
}
Note that there are spaces between the close angle braces to prevent weird compiler errors. Also note that with the pass by refer... |
4,702,072 | 4,702,085 | How do I force eof on stdin? | For a C++ application, how can I programmatically force an end of file (EOF) on stdin?
| Actually, you cannot. As long as you can read data from stdin, EOF hasn't been reached, and in fact you can never reach it. You can close the stdin itself, however. To close it, do this:
fclose(stdin);
After this, you cannot read data from stdin.
|
4,702,114 | 4,702,436 | Build Interactive Floor With Projection? | Dear Guys
I am somehow newbie and sometimes guru , but at this moment i don't have enough time to research
My nightmare is , my boss ask me to create an interactive floor ( he just saw in an exhibition ) , he ask me to create one of them instead of buying , i am an actionscript crawler and developer with some skills ... | Try looking into cinder and openframeworks. these are two great libraries that help speed up this kind of stuff. openframeworks works well with opencv (intel's open computer vision library) which makes tracking much easier
of:
http://www.openframeworks.cc/
http://www.aliak.com/content/openframeworks-opencv-computer-vis... |
4,702,418 | 4,702,554 | Move an object in the direction of a bezier curve? | I have an object with which I would like to make follow a bezier curve and am a little lost right now as to how to make it do that based on time rather than the points that make up the curve.
.::Current System::.
Each object in my scene graph is made from position, rotation and scale vectors. These vectors are used to ... | You should have a curve in parametric form and use derivative vector to evaluate the rotation of your object (rotation angle = derivative angle) as @etarion said.
To move the object on a curve with a desired velocity ( i think it is the think you want) each simulation step you shoud estimate the distance the point shou... |
4,702,512 | 4,703,292 | Stopping threaded server loop using Boost::Asio | I am developing a tiny server loop for a bigger software but it doesn't work as I want it to do.
When the user types in ".quit" I want the software to stop this threaded server loop:
try {
while (true) {
acceptor.accept(socket);
const size_t buffersize = 1024;
char data[buffersize+1] = {0};
dat... | Typically servers are written using asynchronous methods
async_accept
async_read
async_write
in which case the suggested technique to shutdown all pending asynchronous operations is to stop the io_service's event processing loop. Note that you should pay special attention to the ~io_service documentation
The destruc... |
4,702,604 | 4,702,621 | C++ error - C2228, identifier not recognized as class | Here is the relevant code:
Canvas.cpp
#ifndef CANVAS
#define CANVAS
#include "graphicsDatatypes.h"
class Canvas
{
private:
// Current and next points to draw to
struct cartesianPoint currentPoint, nextPoint;
public:
Canvas::Canvas() { numLinesDrawn = 0; };
... | The line
Canvas userDrawSpace();
looks like it should be creating Canvas object, but in fact it declares a function called userDrawSpace returning a Canvas object :-(.
That's a very common gotcha in C++.
Just get rid of the () and it should be ok.
|
4,702,638 | 4,702,734 | gdb "watch pointer " giving too many h/w watchpoints error | class Message{
double *val
};
Message** val_msgs;
val_msgs = new Message*[120];
for(int i=0; i<120; i++)
val_msgs[i]=new Message();
I am using gdb to watch a variable inside the Message data structure
watch val_msgs[0]->val
However, I get this error
(gdb) watch val_msgs[0]->val
Hardware watchpoint 2: this->v... | The replies to this previous question may help: gdb problem setting hardware watchpoint/how to set software watchpoint
|
4,702,732 | 4,703,059 | The program can't start because libgcc_s_dw2-1.dll is missing | I have created a simple program in C++ with Code::Blocks.
If I run it from Code::Blocks, it works correctly; but if I run it by doubleclicking on the executable file, a window pops up with this message:
The program can't start because libgcc_s_dw2-1.dll is missing from your computer.
Try reinstalling the program to ... | I believe this is a MinGW/gcc compiler issue, rather than a Microsoft Visual Studio setup.
The libgcc_s_dw2-1.dll should be in the compiler's bin directory. You can add this directory to your PATH environment variable for runtime linking, or you can avoid the problem by adding "-static-libgcc -static-libstdc++" to you... |
4,702,793 | 4,702,813 | C++: Accessing Grandparent Method | Why doesn't this work, and what would be a good alternative?
class Grandparent
{
void DoSomething( int number );
};
class Parent : Grandparent
{
};
class Child : Parent
{
void DoSomething()
{
Grandparent::DoSomething( 10 ); // Does not work.
Parent::DoSomething( 10 ); // Does not work.
... | class Grandparent
{
protected:
void DoSomething( int number );
};
class Parent : protected Grandparent
{
};
class Child : Parent
{
void DoSomething()
{
Grandparent::DoSomething( 10 ); //Now it works
Parent::DoSomething( 10 ); // Now it works.
}
};
At a minimum it needs to look like th... |
4,702,825 | 4,702,884 | Loop crashing program having to do with 2D arrays | I am creating an encoding program and when I instruct the program to create a 5X5 grid based on the alphabet while skipping over letters that match up to certain pre-defined variables(which are given values by user input during runtime). I have a loop that instructs the loop to keep running until the values that access... | An array with the first five letters of the alphabet (a size of 5) can be visualized like so:
Index 0: a
Index 1: b
Index 2: c
Index 3: d
Index 4: e
As you can see, the index of the first value is actually zero. This can get confusing!
char MyCharacterArray[5]; // Initializes a one-dimensional character array with a ... |
4,702,873 | 4,755,020 | Android NDK OpenGL ES 1.0 Simple Rendering | I'm starting out with the Android NDK and OpenGL. I know I'm doing something (probably a few) things wrong here and since I keep getting a black screen when I test I know the rendering isn't being sent to the screen.
In the Java I have a GLSurfaceView.Renderer that calls these two native methods. They are being called ... | I finally found the problem after MUCH tinkering.
Turns out that because I was calling the code from a GLSurfaceView.Renderer in Java the frame buffer already existed and so by calling:
glGenFramebuffersOES(1, &framebuffer);
I was unintentionally allocating a NEW buffer that was not attached to the target display. By ... |
4,702,906 | 4,706,088 | when do luabind free created objects? | I'm having problems with luabind. I define a std::map to allocate objects created in lua. I publish this map as a global object in lua in this way:
luabind::globals(L)["g_SceneManager2D"] = this;
After that, this object is used into a function into lua, where many objects are created and inserted into this map. The pr... | I suggest use a shared_ptr<>(this) rather than raw this. boost::shared_from_this might help. Make sure your class is registered using Luabind too, and that the class_ is specified as held by a shared_ptr.
Another fun idea might be to make your Lua function just generate the "map" as a Lua table, return it, and you ca... |
4,703,081 | 4,703,107 | Reverse reading WORD from a binary file? | I have a structure:
struct JFIF_HEADER
{
WORD marker[2]; // = 0xFFD8FFE0
WORD length; // = 0x0010
BYTE signature[5]; // = "JFIF\0"
BYTE versionhi; // = 1
BYTE versionlo; // = 1
BYTE xyunits; // = 0
WORD xdensity; // = 1
WORD ydensity; ... | You are on an x86 cpu which stores words low byte-high byte (little endian)
The binary file is presumably stored in big endian.
You need to manually swap each byte in the file (or possibly your JFIF library will do this for you)
ps. The safest way to swap bytes is to use the ntohs() and htons() macros in your 'C' libra... |
4,703,194 | 4,703,261 | Sorting data using std::map or std::multimap | Happy New Year. Hope everyone is ok. I have not been here for a while.
I have some contact lens data I'm trying to sort. I have some sort rules are static (hard-coded) followed by other rules form 'normal' rules
Here are the requirements:
First sort by Company and Product is a static order (hard-coded, non alphb... | You can write a comparison functor that can take into account any number of criteria. The idea is to start at the most significant criterion, then go down the list only when the upper levels are equal.
struct LensCompare
{
bool operator()(const Data & left, const Data & right)
{
if (left.key < right.key... |
4,703,400 | 4,719,727 | Is this a good design? | Right now, I'm making a Gui Library for games. The Widgets have several callbacks / listeners for various events.
The thing about it is a listener can consume an event.
The issue comes here. The base class is called with event info. It calls the callbacks for the listeners. Any of them can handle the event.
This means... | If you want to this for many events, I'd rather go the onMouseClick way (IIUC):
void TextBox::onMouseClick(MouseEvent &event)
{
//do stuff or empty of not needed
}
in class Widget:
void Widget::MouseClick(MouseEvent &event) // nonvirtual
{
// do the listeners' stuff
if(event.isHandled()) onMouseClick(event)... |
4,703,731 | 4,703,753 | Converting a string like "2.12e-6" to a double | Is there a built in function in c++ that can handle converting a string like "2.12e-6" to a double?
| atof should do the job. This how its input should look like:
A valid floating point number for atof is formed by a succession of:
An optional plus or minus sign
A sequence of digits, optionally containing a decimal-point character
An optional exponent part, which itself consists on an 'e' or 'E' character followed b... |
4,703,902 | 4,705,002 | In what situation should ostream_iterator increment be used? | std::istream_iterator<std::string> ist(std::cin);
std::istream_iterator<std::string> eof;
std::vector<std::string> str_vec(ist, eof);
std::ofstream ofs("a");
if (!ofs) {
throw std::runtime_error("Open file failed.");
}
std::ostream_iterator<std::string> ost(ofs, "\n");
for (size_t index = 0; index != str_vec.size()... | Further experimentation might show that you don't even need to dereference the iterator to make it work. :)
ost = str_vec[index];
All these no-op methods are necessary to give stream iterators a similar interface to other iterators.
Instead of a manual loop, you could rather use the std::copy algorithm. (As that's pre... |
4,704,097 | 4,704,157 | C++: ifstream::getline problem | I am reading a file like this:
char string[256];
std::ifstream file( "file.txt" ); // open the level file.
if ( ! file ) // check if the file loaded fine.
{
// error
}
while ( file.getline( string, 256, ' ' ) )
{
// handle input
}
Just for testing purposes, my file is just one line, with a space at the end... | First leets make sure your input file is good:
Run the following command and let us know the output:
#include <iostream>
#include <sstream>
#include <string>
#include <iterator>
#include <fstream>>
#include <iomanip>
#include <algorithm>
int main()
{
std::ifstream file("file.txt");
std::cout << std::hex;
... |
4,704,404 | 4,704,609 | Implicit conversion : const reference vs non-const reference vs non-reference | Consider this code,
struct A {};
struct B { B(const A&) {} };
void f(B)
{
cout << "f()"<<endl;
}
void g(A &a)
{
cout << "g()" <<endl;
f(a); //a is implicitly converted into B.
}
int main()
{
A a;
g(a);
}
This compiles fine, runs fine. But if I change f(B) to f(B&), it doesn't compile. If I write f... |
I would like to hear reasons, rationale and reference(s) from the language specification
Is The Design and Evolution of C++ sufficient?
I made one serious mistake, though, by allowing a non-const reference to be initialized by a non-lvalue [comment by me: that wording is imprecise!]. For example:
void incr(int& rr) ... |
4,704,424 | 4,704,445 | How to enable intellisense in VIM (gvim) | Is there any way I can have intellisense enabled in VIM (gvim).
I wish to use it for STL.
| Forgive me for correcting you first, but IntelliSense is the name of the advanced code completion in Microsoft Visual Studio, not the general term for code completion.
To answer your question, you will probably want to use YouCompleteMe. The setup is not terribly hard with vim plugin managers, but don't forget to run ... |
4,704,521 | 4,706,177 | How to I count key collisions when using boost::unordered_map? | I have a data structure with 15 unsigned longs, I have defined a hash function using hash_combine as follows:
friend std::size_t hash_value(const TUPLE15& given)
{
std::size_t seed = 0;
boost::hash_combine(seed, val1);
boost::hash_combine(seed, val2);
...
return seed;
}
I insert... | How about comparing the number of tuples vs. the number of unique hash values?
set<size_t> hash_values;
BOOST_FOREACH(const TUPLE15& tuple, tuples)
hash_values.insert(hash_value(tuple));
size_t collisions = tuple_map.size() - hash_values.size();
or
size_t collisions = 0;
for (size_t bucket = 0; bucket != tuples.bu... |
4,704,531 | 4,704,552 | C/C++ Inline assembly [with C loops] | #include <stdio.h>
#define OPT //define for assembly
int main()
{
char chr;
for(chr = 'A' ; chr <= 'Z' ; chr++)
{
#ifdef OPT
__asm
{
lea eax,chr
push eax
mov eax, putchar
call eax
pop ebx
}
#endif
#ifndef OPT
putchar(chr);
#endif
}
return 0;
}
Upon usage of the assembly code, al... | It doesn't work because lea instruction is intended to get the address of a variable. (+1 to zebarbox for this note.) We need the value of chr, not its address, so we use this instead:
movsx eax,chr
This pseudoinstruction will compile to something like this:
movsx eax,[ebp-4]
You can also write putchar(chr), put ther... |
4,704,567 | 4,704,741 | Function with parameter type that has a copy-constructor with non-const ref chosen? | Some time ago I was confused by the following behavior of some code when I wanted to write a is_callable<F, Args...> trait. Overload resolution won't call functions accepting arguments by non-const ref, right? Why doesn't it reject in the following because the constructor wants a Test&? I expected it to take f(int)!
st... | Overload resolution picks the function that is the closest match to the supplied argument. You supplied a Test. No conversion necessary -- identity conversion used. Thus function resolution chooses f(Test). Test can't be copied from rvalue, which you supplied, but overload resolution has succeeded already...convers... |
4,704,590 | 4,704,603 | Getting around access specifiers with C++0x decltype | Consider the following code:
class A
{
private:
class B {};
public:
B f();
};
A a;
A::B g()
{
return a.f();
}
The compiler rejects this - g cannot return A::B because A::B is private.
But suppose I now use decltype to specify the return value of g:
class A
{
private:
class B {};
public:
B f();
};... | Access only applies to names (and as a special case, to constructors/destructors). It doesn't apply to entities themselves. The spec further elaborates
[ Note: because access control applies to names, if access control is applied to a typedef name, only the accessibility of the typedef name itself is considered. The a... |
4,704,605 | 4,704,608 | Are there any downsides in using C++ for network daemons? | I've been writing a number of network daemons in different languages over the past years, and now I'm about to start a new project which requires a new custom implementation of a properitary network protocol.
The said protocol is pretty simple - some basic JSON formatted messages which are transmitted in some basic fra... | I for one can't think of any technical reason to chose C over C++. Not one that I can't instantly think of a counterpoint for anyway.
Edit in reply to edit: I would seriously discourage you from considering, "...C code is basically C++." Although you can technically compile any C program with a C++ compiler (in as fa... |
4,704,940 | 4,704,991 | C++ is it possible to make a class extend one class and be a realization of an interface at the same time? | Coluld you provide a simple code example? (sorry C++ nube) and how to call a function from the class you are extending?
| A bit useful example: :-)
class CImplementation
{
public:
void doFoo();
};
void CImplementation::doFoo()
{
//implementation
}
class IInterface
{
public:
virtual void foo()=0;
};
class DerivedFromImplementationAndInterface : public CImplementation, public IInterface
{
virtual void foo();
};
void DerivedFromImplement... |
4,704,947 | 4,704,970 | Class and class-helpers | I am new to c++ and want to ask about class helpers.
Well, i have a class and i what class helpers to be in other file. For that i should use namespaces but then i cant #include this file multiple times(because of redefinition).
What is the right way to make class helpers in other classes? Should i use static classes ... | use #ifdef to guard against multiple redefinitions.
also look at this post: #pragma once vs include guards?
|
4,704,982 | 4,704,988 | How to check if one C++ class extends another (like if that another one was an interface)? | So generally having
class A { ... };
class B { ... };
class C: public A, public B {}; // C inherits from A and B.
when we create an instance of C and want to pass it into some function ho do we check if class we pass to a function is extending A?
| C is defined as inheriting from A so there is no need to check:
It is mandatory that an instance of C is also a A (and a B).
However, if you have a function taking a A as a parameter, you can use dynamic_cast<> to check if the instance is actually a C:
void function(const A& a)
{
const C* c = dynamic_cast<const C*>(&... |
4,704,986 | 4,704,995 | Switch statement using or | I'm creating a console app and using a switch statement to create a simple menu system. User input is in the form of a single character that displays on-screen as a capital letter. However, I do want the program to accept both lower- and upper-case characters.
I understand that switch statements are used to compare aga... | This way:
switch(menuChoice) {
case 'q':
case 'Q':
//Some code
break;
case 's':
case 'S':
//More code
break;
default:
}
More on that topic:
http://en.wikipedia.org/wiki/Switch_statement#C.2C_C.2B.2B.2C_Java.2C_PHP.2C_ActionScript.2C_JavaScript
|
4,705,015 | 4,705,062 | Performance of OpenMP Parallel Programming in C | I wrote a C program for Pi computation using OpenMP getting help from a book. I believe the performance of this program will depend on the processors used.
In my case, I used the environment variable to check the performance of parallelism by increasing the number of processors or threads (I am not sure what is correct... | You probably have a processor that supports hardware threads (Intel calls this hyper-threading).
What this basically means is that your cores each have two instruction caches and can thus execute two interweaving threads more efficiently than usually. This is especially noticeable if the threads often have to wait for ... |
4,705,097 | 4,705,124 | inherit operator new from base class | This page (from C++ in action book) shows code:
class Link
{
friend class FreeList;
public:
Link (Link * pNext, int id)
: _pNext (pNext), _id (id) {}
Link * Next () const { return _pNext; }
int Id () const { return _id; }
// allocator
void * operator new (size_t size)
{
ass... | A new expression will cause an allocation function (operator new) to be called with the correct size for the object being constructed. That's what the size_t parameter for operator new is for.
The particular implementation of operator new in the example, however, can only cope with uniform sized allocation requests. If... |
4,705,109 | 4,705,387 | Make object by its name | is it possible to return exemplar of object using passed type name (string) in c++?
I have some base abstract class Base and a few derivates. Example code:
class Base
{
/* ... */
};
class Der1 : public Base
{
/* ... */
};
class Der2 : public Base
{
/* ... */
};
And I need function like:
Base *objectByType(c... | There is a nice trick which allows you to write a factory method without a sequence of if...else if....
(note that, AFAIK, it is indeed not possible to do what you want in C++ as this code is generated in the compile time. A "Factory Method" Design Pattern exists for this purpose)
First, you define a global repository ... |
4,705,151 | 4,705,332 | How to throw meaningful data in exceptions? | I would like to throw exceptions with meaningful explanation (socket handle, process id, network interface index, ...) !
I thought of using variable arguments worked fine but lately I figured out it's impossible to extend the class in order to implement other exception types. So I figured out using an std::ostreamstrin... | It is a bit awkward to pass ... arguments, but possible. You need first to convert them to va_list. So, for your derived class to be able to pass the format and the arguments to its base class something like the following can be done:
class Exception: public std::exception {
public:
Exception(const char *fmt, ...)
... |
4,705,316 | 4,705,380 | How to know if the argument that is passed to the function is a class, union or enum in c++? | I want to define an operator<< for all enums, to cout the value and print that it is an enum like this:
code:
enum AnyEnum{A,B,C};
AnyEnum enm = A;
cout << enm <<endl;
output:
This is an enum which has a value equal to 0
I know a way of doing this with Boost library by using is_enum struct. But I don’t understand ho... | Determining class types you could use the fact that member pointers exist
template<typename A, typename B>
struct issame { };
template<typename A>
struct issame<A, A> { typedef void type; };
template<typename> struct tovoid { typedef void type; };
template<typename T, typename = void>
struct isclass { static bool co... |
4,705,411 | 4,705,512 | Boost::Asio : io_service.run() vs poll() or how do I integrate boost::asio in mainloop | I am currently trying to use boost::asio for some simple tcp networking for the first time, and I allready came across something I am not really sure how to deal with. As far as I understand io_service.run() method is basically a loop which runs until there is nothing more left to do, which means it will run until I re... | Using io_service::poll instead of io_service::run is perfectly acceptable. The difference is explained in the documentation
The poll() function may also be used
to dispatch ready handlers, but
without blocking.
Note that io_service::run will block if there's any work left in the queue
The work class is used to i... |
4,705,714 | 4,705,810 | C++ Generic Linked List | For the code below:
#include <iostream>
#include <string>
using namespace std;
class Foo2;
class Foo3;
template <class T>
class Foo1 {
public:
Foo1();
void print() {
cout << "My name is: " << name << endl;
}
T getNext(){
return nextLink;
}
string name;
T nextLink;
};
cla... | I think the problem is the "?" in LinkedList
If this is the case, then you should use LinkedList<Foo1 *>.
Why can't you use std::list? Maybe we can help you with that, it will be far better that using your own implementation.
|
4,705,769 | 4,705,885 | C++ Library Compatibility | I am currently writing a library and am considering moving from GCC 4.1.2 to 4.5.2 (latest release) of GCC. If I compile my code into a static library can I assume compiler compatibility (on the same OS obviously) should be a non-issue for clients?
EDIT
To further clarify: if I provide a client a statically linked libr... | Just came across this which I believe answers my question from http://gcc.gnu.org/bugs/#nonbugs:
ABI changes The C++ application binary
interface (ABI) consists of two
components: the first defines how the
elements of classes are laid out, how
functions are called, how function
names are mangled, etc; the se... |
4,705,822 | 4,706,116 | Vistual studio 2008 executaable cannot run on target system without .net frame work | i have crated application in VS 2008 using VC console project. i execute this executable to target system which does not have VS i got error
"The system cannot execute the specified programe."
i have also installed vcredist_x86.exe on target system but no success. i have the following test programe
#include "stdafx.h... | Don't try to run the Debug build of your program on another machine, only deploy the Release build.
For small programs like these, you don't have any need for the shared CRT dlls. Right-click your project in the Solution Explorer window, Properties, C/C++, Code Generation. Be sure the Release configuration is selecte... |
4,705,968 | 4,705,984 | What is value of EOF and '\0' in C | I know that EOF and '\0' are of type integers, but if so shouldn't they have a fixed value?
I printed both and got -1 for EOF and 0 for '\0'. But are these values fixed?
I also had this
int a=-1;
printf("%d",a==EOF); //printed 1
Are the value for EOF and '\0' fixed integers?
| EOF is a macro which expands to an integer constant expression with type int and an implementation dependent negative value but is very commonly -1.
'\0' is a char with value 0 in C++ and an int with the value 0 in C.
The reason why printf("%d",a==EOF); resulted in 1 was because you didn't assign the value EOF to a. In... |
4,706,156 | 4,706,219 | New thread on a class function | I want to make a class that contains a bunch virtual functions which are called on different events. I have the class already but how do I start those functions as new threads? I can manage to do this on global functions only. I want my class to look like this:
class Callbackk{
CallBack(){};
virtual ~Callback(){};
... | Different threading mechanisms are using different syntax for this case.
I will supply the example for boost::thread library.
Obviously, you have to bind your function to some class instance for it to be called. This can be accomplished the following way:
// Thread constructor is a template and accepts any object that ... |
4,706,199 | 4,706,225 | Post-increment and pre-increment within a 'for' loop produce same output | The following for loops produce identical results even though one uses post increment and the other pre-increment.
Here is the code:
for(i=0; i<5; i++) {
printf("%d", i);
}
for(i=0; i<5; ++i) {
printf("%d", i);
}
I get the same output for both 'for' loops. Am I missing something?
| After evaluating i++ or ++i, the new value of i will be the same in both cases. The difference between pre- and post-increment is in the result of evaluating the expression itself.
++i increments i and evaluates to the new value of i.
i++ evaluates to the old value of i, and increments i.
The reason this doesn't matte... |
4,706,284 | 4,706,336 | Getting byte value from char | It simple but I am getting problem with this.
http://www.ipix.lt/images/90928843.png
I want to cout buffer[5]. But not the symbol value, but 255. Tried typecasting to int or byte but that gets -1.
| It's correct that, casting it to int, you get -1, because char in your implementation is a signed type (it's actually implementation-defined if char is signed or unsigned, and usually you can change it in the compiler options); what you see in the debugger window is it's unsigned representation.
To get its unsigned val... |
4,706,404 | 4,706,420 | Post/pre increments in 'printf' |
Possible Duplicates:
Output of multiple post and pre increments in one statement
Post-increment and pre-increment in 'for' loop
The following code snippet
int i=0;
printf("%d %d",i++,i++);
gives the output
1 0
I can understand that, but the following
int i=0;
printf("%d %d",++i,++i);
gives the output
2 2
Can some... | Both printfs invoke undefined-behavior. See this : Undefined behavior and sequence points
Quoted from this link:
In short, undefined behaviour means
anything can happen from daemons
flying out of your nose to your
girlfriend getting pregnant.
For newbies : Don't ever try to modify values of your variables twic... |
4,706,494 | 4,706,823 | OpenMP: Get total number of running threads | I need to know the total number of threads that my application has spawned via OpenMP. Unfortunately, the omp_get_num_threads() function does not work here since it only yields the number of threads in the current team.
However, my code runs recursively (divide and conquer, basically) and I want to spawn new threads as... | Having in mind you know the exact amount of threads being created, the simplest solution I come up with is keeping your own thread counter.
Be aware I'm completely in the dark about OpenMP as I've never really used it.
|
4,706,572 | 4,712,374 | Difference between operator and function in C++? | I could use some help understanding the following in C++, particularly the difference between an operator and a function:
What is an operator?
What is a function?
What is the difference between them?
Is a user-defined operator+() a function or an operator?
Can an operator operate on operands at compile-time? Do they a... | An operator is a symbol like +, -, += and so forth (see 13.5). They don't carry a meaning. During semantic analysis, the meaning of an operator is determined.
A function is a constructor, destructor, conversion function (that looks like operator type()) or operator function (function template specialization and instan... |
4,706,584 | 4,706,587 | what does this mean in c int a:16;? |
Possible Duplicate:
What does 'unsigned temp:3' mean?
please what does this notation mean
int a:16;
I found it is code like this and it does compile.
struct name {
int a:16; }
| This is a bitfield.
This particular bitfield doesn't make much sense as you just could use a 16-bit type and you're wasting some space as the bitfield is padded to the size of int.
Usually, you are using it for structures that contain elements of bit size:
struct {
unsigned nibble1 : 4;
unsigned nibble2 : 4;
}
... |
4,706,646 | 4,794,717 | Distributed Programming Technology | I'm looking for a technology which is targeting on building distributed applications. My friend adviced me to use CORBA (Java & C++ combination) . But I have read it's sort of obsolete stuff. I'm planning to write rather simple distributed application. What solutions would you advice to use? Thanks!
| If you want to distribute your code logic to multiple servers and have it managed as a single entity, I would recommend CloudIQ Platform from Appistry. You can deploy Java, .NET and C/C++ code to the framework. From an administrative point of view, the servers work and act as one. When you submit a request for execu... |
4,706,654 | 4,707,092 | Regex vs. string:find() for simple word boundary | Say I only need to find out whether a line read from a file contains a word from a finite set of words.
One way of doing this is to use a regex like this:
.*\y(good|better|best)\y.*
Another way of accomplishing this is using a pseudo code like this:
if ( (readLine.find("good") != string::npos) ||
(readLine.fi... | The regexp will perform better, but get rid of those '.*' parts. They complicate the code and don't serve any purpose. A regexp like this:
\y(good|better|best)\y
will search through the string in a single pass. The algorithm it builds from this regexp will look first for \y, then character 1 (g|b), then character 2 (g... |
4,706,677 | 4,707,150 | Partial template specialization with multiple template parameter packs | Continuing my journey into the world of variadic templates, I encountered another problem.
Assuming the following template class:
template < typename T >
struct foo
{
//default implementation
};
it is possible to partially specialize it for variadic template instantiations like this:
template < template < typenam... | Probably this answer won't clear your question directly,
but the following code compiled on ideone(gcc-4.5.1) when I tested.
#include <cstdio>
#include <tuple>
template< class, class > struct S {
S() { puts("primary"); }
};
template<
template< class... > class T, class...TArgs
, template< class... > class U, clas... |
4,706,685 | 4,706,717 | Why is C++ still using stdio.h? | this is probably a dumb question, but I couldnt find the answer I was looking for. Also, I was unsure if this was a C++ question or a VS2010 question, but the answer I'm looking for is that of a technical POV, so I ended up here.
When you start a new Console Application project in VS2010, it automatically includes stda... | IO streams in older C++ implementations were pretty slow, leading programmers to keep using stdio.h. Apparently, that got included in stdafx.h in the past and cannot be removed from that header anymore as removing it would break existing code.
|
4,706,690 | 4,706,738 | C++ why the assignment operator should return a const ref in order to avoid (a=b)=c | I am reading a book about C++ and more precisely about the operator overloading.
The example is the following:
const Array &Array::operator=(const Array &right)
{
// check self-assignment
// if not self- assignment do the copying
return *this; //enables x=y=z
}
The explanation provided by the book about returning cons... | (x=y) means x.operator=(y), which returns the object x. Therefore, (x=y)=z means (x.operator=(y)).operator=(z). The expression in parens sets x to y and returns x, and then the outer bit sets x to z. It does not set y to z as you might expect, and as the expression x = y = z does.
This behavior is counter-intuitive (t... |
4,706,788 | 4,706,867 | Why can I expose private members when I return a reference from a public member function? | In the code snippet, I am able to access the private member variable outside the class scope. Though this should never be done, why is it allowed in this case? Is it a bad practice to receive a returned private variable by reference ?
#include <iostream>
#include <cstdlib>
class foo
{
int x;
public:
f... | private does not mean "this memory may only be modified by member functions" -- it means "direct attempts to access this variable will result in a compile error". When you expose a reference to the object, you have effectively exposed the object.
Is it a bad practice to receive a returned private variable by reference... |
4,706,790 | 4,706,810 | template not in scope | Got this in "char.h"
#ifndef _CHAR_H_
#define _CHAR_H_
#include <stdio.h>
template <unsigned int TChar>
class Char
{
public:
Char(){ *m_data=0; m_len=-1; }
private:
char m_data[TChar+1];
int m_len;
};
#endif
Now with this simple test :
#include "char.h"
void test(Char<TChar> &oo)
{
//...
}
int main(i... | The full implementation of a template class must be in that template class's header (otherwise you are likely to get a linker error).
The compiler needs to have access to the entire template definition (not just the signature) in order to generate code for each instantiation of the template, so you need to move the de... |
4,706,841 | 4,708,337 | Using boost::depth_first_search with Visitor | As the title suggests, I'm using boost::depth_first_search and using a Visitor (inheriting from boost::default_dfs_visitor) to implement some algorithm.
However, during the algorithm's run, I want to save some information in the visitor, to be queried later. However, the information is erased after the DFS is done, so ... | Does it really make sense that the information is part of the visitor?
My guess is that the information logically belongs with the graph, and should be stored there, not in the visitor.
You can store a reference to the graph in the visitor. Then, as the visitor traverses the graph, it can update the information that i... |
4,706,976 | 4,707,005 | 4x8 bit int to 32 bit integer | I have
_int8 arr[0] = 0;
_int8 arr[1] = 0;
_int8 arr[2] = 14;
_int8 arr[3] = 16;
I need to convert it to one _int32 using as arr[0] as first part <..> and arr[3] as last.
In the end it should be
_int32 back = 3600;
Should I use bit shifts or smth like that to achieve this?
| If you know the byte ordering (i.e. big endian or little endian, check it out on wikipedia), and the array is set up in the right order you can just do:
back = *(_int32 *)arr;
That'll just interpret your array of 4 bytes as a buffer holding a single 32-bit integer. In your example though, I think you've got it set up... |
4,707,057 | 4,707,280 | How to generate an OpenGL texture from non-continous data? | My goal is to create a texture from a webcam image. I get the image via OpenCV's new VideoCapture interface from a Logitech QuickCam for Notebooks webcam. The problem is that I get non-continuos data this way, which means that each row of the matrix holding my image data has a gap at the end.
The layout of my image dat... | You could try a combination of GL_UNPACK_ALIGNMENT and GL_UNPACK_ROW_LENGTH.
In your specific case, this would give :
glPixelStorei(GL_UNPACK_ALIGNMENT, 4) // as 2560 is a multiple of 4
glPixelStorei(GL_UNPACK_ROW_LENGTH, 2560/3) // to consider each row having this number of pixels
But all in all, are you su... |
4,707,133 | 4,707,154 | locale in c++ n java | I have been sneaking into some code written by professionals (not to mention on the SO)..
I found people referencing often to the word locale ( for eg found some std::locale). Even some code in java refers to locale . So what is this locale and why do we actually need it? And is it necessary to use it ( I guess it is u... | "A Locale object represents a specific geographical, political, or cultural region. An operation that requires a Locale to perform its task is called locale-sensitive and uses the Locale to tailor information for the user. For example, displaying a number is a locale-sensitive operation--the number should be formatted ... |
4,707,162 | 4,707,257 | Why cin.get(char *, int, char t) and cin.getline(char *, int, char t)? | The documentation says the cin.get(...) will leave the termination character(parameter t) in the buffer! I am wondering how could this be useful compared to getline(...) which will discard the termination character... BTW, suppose I have char buf[256], how can I flush that buf to cout?
| For lines, the terminating newline is considered part of the line, and you generally want to remove it when reading a line. Convention has determined that the resulting string containing the line not contain that newline, however, which is why getline discards it instead of storing it. (Other languages/libraries don'... |
4,707,384 | 4,707,425 | Disable all types of optimizations in VS2010 | How should you disable all types of optimizations while debugging in VS2010?
| To insure optimizations are off, right click on your project -> Properties -> Configuration Properties -> C/C++ -> Optimization -> Optimization = Disabled. This is the /Od compiler switch.
|
4,707,610 | 4,708,171 | Does std::map need to be initialized? | I have a singleton, that is an image manager. When I try to load an image, I call singleton in this way:
utils::CImageBuff* img4 = utils::CImageManager::getInstance()->loadFromFile("uswg.png");
And, into loadFromFile method, I store the image into a map:
m_imageMap[imageHashID].setHeight(ilGetInteger(IL_IMAGE_HEIGHT))... | I'm assuming that m_imageMap is a regular member variable of a class and you are calling this from a member function of that class.
If that is the case, then you are likely calling that member function on a zombie, null otherwise invalid pointer. Is the line of code with m_imageMap in it the first use of a member vari... |
4,707,809 | 4,707,837 | forward declaring with inheritance information | This compiles fine, although I wouldn't want to try running it just yet. However ...
//class base;
//class derived;
//class derived : public base;
class base {};
class derived : public base {};
class other
{
public:
void func() {base1 = derived1;}
base* base1;
derived* derived1;
};
void m... | This should work. You need to move other up
BUT declare func below. That way func is able to "see" that derived is of type base.
e.g.,
class base;
class derived;
//class derived : public base;
class other
{
public:
void func();
base* base1;
derived* derived1;
};
class base {};
class derive... |
4,707,861 | 4,707,884 | C++ Simple Variant Boost | I'm attempting to create a list of objects using the variant boost.
#include <string>
#include <list>
#include <iostream>
#include <boost/variant.hpp>
using namespace std;
using namespace boost;
class CSquare;
class CRectangle {
public:
CRectangle();
};
class CSquare {
public:
CSquare();
};
int main()
{ t... | Just need to change a few things and it works:
#include <iostream>
#include <list>
#include <string>
#include <boost/variant.hpp>
using namespace std;
using namespace boost;
class CRectangle
{
public:
CRectangle() {}
};
class CSquare
{
public:
CSquare() {}
};
int main()
{
typedef variant<CRectangle, CSquare, b... |
4,707,962 | 4,708,738 | C++ Winsock - accept() | I've started tying to learn Winsock with C++ and I'm having some problems.
I started by following the Winsock Example on MSDN ( a basic client-server ).
http://msdn.microsoft.com/en-us/library/ms738545(v=vs.85).aspx
When I build and run the code I get the output:
Client.exe
14 bytes sent.
Connection closed.
Server.exe
... | Sounds like your client hasn't connected to the server. It's connected to something, but maybe not your server. Here are some things I would look at:
Hard-code the server IP address in the client.
The server listens only on IPv4 but the client will try both IPv4 and IPv6. Should be OK, but I recommend removing that am... |
4,707,981 | 4,708,568 | Linking : Static vs Dynamic | In my application I have 3 major parts:
Exe : an executable file
Lib_A : a library contains a singleton class and a base class for some calculations to be use in singleton
class
Lib_B : a library contains a number of classes derived from the base in Lib_A
The reason that I have the derived classes in Lib_B is, I ... | From what I understand of your project description, you should link Lib_A dynamically : if you link Lib_A statically to each of your Lib_Bx shared libraries, you will duplicate x times the Lib_A code and static variables.
Say, if you have a class in Lib_A, that have the form :
class BaseKlass
{
static int instance_co... |
4,708,037 | 4,708,124 | Visual Studio or GCC? | What should you choose to learn cpp programming? As I know both have support for language but does that really make any difference If I have to make a choice?
| If you're just learning, I'd recommend G++ but I'd recommend you get the newest one you can. This might be a little tougher than usual on win32 (you'll probably have to hand-upgrade mingw or something). So, you might do yourself a lot of favors installing Linux on a second partition or some old PC or something.
The m... |
4,708,105 | 4,708,160 | Performance of qsort vs std::sort? | According to Scott Meyers, in his Effective STL book - item 46. He claimed that std::sort is about 670% faster than std::qsort due to the fact of inline. I tested myself, and I saw that qsort is faster :( ! Could anyone help me to explain this strange behavior?
#include <iostream>
#include <vector>
#include <algorithm>... | std::clock() is not a viable timing clock. You should use a platform-specific higher resolution timer, like the Windows High Performance Timer. More than that, the way that you call clock() is that first, text is output to the console, which is included in the time. This definitely invalidates the test. In addition, ma... |
4,708,264 | 4,708,308 | class classname(value); & class classname=value; difference when constructor is explicit | When constructor is explicit, it isn't used for implicit conversions. In the given snippet, constructor is marked as explicit. Then why in case foo obj1(10.25); it is working and in foo obj2=10.25; it isn't working ?
#include <iostream>
class foo
{
int x;
public:
explicit foo( int x ):x(x)
{}
};
int ma... | There is a difference between these two lines of code. The first line,
foo obj(10.25);
explicitly calls your foo constructor passing in 10.25. This syntax, in general, is a constructor call.
The second line,
foo obj2 = 10.25;
tries to implicitly convert from 10.25 to an object of type foo, which would require use o... |
4,708,335 | 4,708,462 | istream::getline return type | What does the istream::getline method return?
I am asking because I have seen that to loop through a file, it should be done like this:
while ( file.getline( char*, int ) )
{
// handle input
}
What is being returned?
| It returns a stream so that we can chain the operation.
But when you use an object in a boolean context the compiler looks for an conversion operator that can convert it into a type that can be used in the boolean context.
C++11
In this case stream has explicit operator bool() const. When called it checks the error fla... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.