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
5,821,890
5,822,340
How to call Carbon function from Qt Creator project?
I'm trying to use ChangeWindowAttributes() function in Qt Creator project on Mac OS X. But I can't build the project. What I've tried: #include <MacWindows.h> Result (compiler): File not found #include <Carbon/Carbon.h> // Or the same: #include </Developer/Headers/FlatCarbon/MacWindows.h> Result (compiler): ChangeWi...
By default, QT Creator build your project in your Mac's CPU architecture. The libraries themselves come in x86 and x86_64 universal binaries. This is if you are using the prebuild SDK from Nokia. If you are running 64-bit capable OS/Mac combination, like 10.6 on a new Intel Mac, it will build it in x86_64. Carbon calls...
5,822,014
5,822,120
Using vectors to bleep some predefined strings
So i'm currently doing the exercices in my programming book "Programming: Principles and practice using c++" from Bjarne Stroustrup and i'm curently stuck at one exercice. Basically, the exercice is to write a program that bleeps out words it doesn't like. The way it works is that the user inputs a string and the progr...
Ok, let me explain a simple approach to it. There are more elegant ones, but for now it's important that you get a feeling of how std::vector can be accessed and how to compose control structures correctly. Step 1 - looping through all elements of a vector You can use iterators to go through all elements of a vector. f...
5,822,031
5,824,624
Performance difference between multiple pointer dereferences vs references
This was an interview question asked from me a few months back: Which of the following functions will execute faster, Foo1 or Foo2? void Foo(SomeObjectArray** array, unsigned int size) { for (int i = 0; i < size; i++) { if (((*array) + i) != NULL) { ((*array) + i)->Operation1(); ...
I think this is a pretty interesting question, and I saw a lot of speculation about what a compiler might do, but I wanted to take a closer look and find out for sure. So I took e.James' program and ran it through GCC to get the assembly. I should say that I don't really know assembly, so somebody correct me if I'm wro...
5,822,064
5,829,181
Weird CPU usage in OpenGL program
In an MFC-program I built myself I have some weird problems with the CPU usage. I load a point cloud of around 360k points and everything works fine (I use VBO buffers which is the way to do it from what I understand?). I can move it around as I please and notice no adverse effects (CPU usage is very low, GPU does all ...
Ok, so I think I have figured out how this can happen. To begin with the WM_TIMER messages doesn't seem to be generated more often than every 15 ms at best, even when using timeBeginPeriod(1), at least on my computer. This resulted in the standard 65 fps I was seeing. As soon as the scene took more than 15 ms to render...
5,822,141
5,834,380
MSVC istream implementation locking buffer
I'm working with some existing code which is deserializing objects stored in text files (I potentially need to read tens of millions of these). The contents of the file are first read into a wstring and then it makes a wistringstream from that. Running the Very Sleepy profiler on the program shows that it is spending ...
It turned out accessing the underlying buffer directly by replacing things like c = _text_in->get(); with things like this c = _text_in->rdbuf()->sbumpc(); fixed the problem and provided a big boost to performance.
5,822,297
5,822,532
cannot find identifier: __mul128
I'm getting an error (VS2010 sp1) : Error 25 error C3861: '_mul128': identifier not found Code looks like this: #include "stdafx.h" #include <intrin.h> int _tmain(int argc, _TCHAR* argv[]) { __int64* high = nullptr; _mul128(2LL,4LL,high); return 0; } Could it be that this fnc can be called only on 64...
_mul128 is only supported on 64-bit architectures. You can see this on the MSDN page: Architecture: IPF, x64
5,822,401
5,822,442
what is const keyword necessary
My code does not compile. int foobar() { // code return 5; } int main() { int &p = foobar(); // error // code const int& x = foobar(); //compiles } Why does adding the keyword const make the code compile?
In C++ temporaries cannot be bound to non-constant references. In int &p = foobar(); The rvalue expression foobar() generates a temporary which cannot be bound to p because it is a non-const reference. const int &x = foobar(); Attaching the temporary to x which is a reference to const prolongs its lifetime. It i...
5,822,603
5,822,657
Operator &= for elements of vector<bool> not defined?
I did some tests with the operator &=. As the following examples shows, this works for single bool type as well as a vector<int> type, but not vector<bool>. #include <vector> int main (){ bool a, b; a &= b; // ok std::vector<bool> c(1); c[0] &= b; // error c[0] = c[0] & b; // ok std::vector<in...
vector<bool> is not a container actually . :P The article says (If anyone else had written vector, it would have been called "nonconforming" and "nonstandard." Well, it's in the standard, so that makes it a little bit harder to call it those names at this point, but some of us try anyway in the hopes that it will even...
5,822,629
5,822,835
Using Template Specialization To Discriminate Between Values And Arrays (of Values)
I am trying to construct a device which will do one thing for a value (specifically, a native type) and another thing for a C-style array of primitives. This is what I have now, which does not do what I wish. #include <cstdlib> #include <string> #include <iostream> #include <iomanip> using namespace std; template<cla...
This should do the trick: template<class A, size_t S> void dump_buf(const A (& ary)[S]) { cout << "ary size = " << S << "\n"; for( size_t i = 0; i < S; ++i ) cout << "\t" << i+1 << " : " << ary[i] << "\n"; } By taking a reference to an array, rather than a pointer to the start of an array, the size is ...
5,822,861
5,823,028
operator overloading in c++ - A query
I was reading a book on operator overloading in c++ and I encountered the following code: class Array { ... public: Array & operator << ( int x) { // insert x at the end of the array } }; Next It says: that overloading of the form a << x << y << z ; wll not workSo It sugges...
This really has nothing to do with operator overloading. It's called chaining and it's easier to explain using regular member functions. Suppose you defined a member function called insert like this: Array& insert(int x) { // insert x at the end of the array return *this; } The return *this will return a refer...
5,823,204
5,823,579
std::vector Assertion failed (vector iterators incompatible)
I have this struct: struct MxMInstanceData { D3DXVECTOR2 mTransform; float mSpacing; }; Then I create a vector of MxMInstanceData: std::vector<MxMInstanceData> instInFrustumData; If I call instInFrustumData.clear() I get this error: Assertion failed (vector iterators incompatible) Vector creation code: i...
You may want to check out a reference on using std::vector like http://www.cplusplus.com/reference/stl/vector/ or buy a good STL book. You are using some methods in what I would consider unorthodox ways. Use empty() to check if a vector has elements (if not empty clear just reads better) Use locally scoped variables ...
5,823,253
5,823,529
Store templated objects as member objects
suppose you have some code like this: struct Manager { template <class T> void doSomething(T const& t) { Worker<T> worker; worker.work(t); } }; A "Manager" object is created once and called with a few diffent types "T", but each type T is called many times. This might be, in a simplified form, like Ma...
You can use something like a std::map<std::type_info,shared_ptr<void> > like this: #include <map> #include <typeinfo> #include <utility> #include <functional> #include <boost/shared_ptr.hpp> using namespace std; using namespace boost; // exposition only: template <typename T> struct Worker { void work( const T & ...
5,823,317
6,463,006
omnicppcomplete not supporting all forms of const
I have omnicppcomplete working fine except once in a while it won't complete some of the variables methods/members. I finally got annoyed enough to dig into why and I believe the reason is that omnicppcomplete does support the syntax "Foo const & foo" in function arguments. For example, if I have a function defined as...
Seems like a limitation in omnicppcomplete, but I pulled up the vim debugger and found it. Open up autoload/omni/cpp/utils.vim, go to line 518, should look like this: for token in tokens if state==0 if token.value=='>' let parenGroup = token.group let state=1 ...
5,823,700
5,848,783
Notification window in Mac. With or without Qt
Qt project on Mac OS X. I need to show notification window on top without stealing a focus from any active application. Here the widget constructor part: setWindowFlags( Qt::FramelessWindowHint | Qt::WindowSystemMenuHint | Qt::Tool | Qt::WindowStaysOnTopHint ); setAttribute(Qt::WA_TranslucentBackground)...
I did it! #ifdef Q_OS_MAC #include <Carbon/Carbon.h> #endif NotifyWindow::NotifyWindow() : QWidget(0 /* This zero is the first point */) { setWindowFlags( #ifdef Q_OS_MAC Qt::SubWindow | // This type flag is the second point #else Qt::Tool | #endif Qt::FramelessWindowHint | ...
5,823,723
5,824,155
When will a connected UDP socket be closed by the OS?
I have a UDP file descriptor in a C++ program running under Linux. I call connect() on it to connect it to a remote address and then read and write from that socket. According to UNIX Network Programming, "Asynchronous errors are returned to the process for connected UDP sockets." I'm guessing that these asynchronous e...
connect() on an UDP socket just records the port number and IP address you pass in, so it'll only accept packets from that IP/port, and you can use the socket fd to send/write data without specifying the remote address for each send/write call. Regarding this, async errors means if you send() something, and that send ...
5,823,843
5,824,991
evaluate variable/function in gdb
I have the following code, ... char* seg = mmap(0, ...) printf("seg=%x\n", seg); ... The program prints with seg=b7ffd000. While in gdb (for the same execution), when using p/x seg, it prints $2 = 0x0. I am confused here. Isn't it the same var seg? why are the values different. PS: in mmap, the first argument is the p...
Now that you've answered my question in the comments, I can answer! The value that you see as the result of the printf is the real address. You are seeing 0 as the value of seg in the debugger because when optimizations are enabled, the compiler is free to do all sorts of weird things (which generally makes step-by-st...
5,824,365
5,824,400
How to use html, java script with c++
I am very new to C++ and using Unix. I have a doubt that can we use C++ like JSP. For example consider a login page, Java script validate user inputs and passes that to C++ then C++ will check with database and return result html page. Can i do like this? If yes please help me how to do that. Thank you.
A programming language is a programming language. You just need a way to get the web server to pass data to and get data from the program you write. Options include: CGI is the simple, but slow and inefficient (because the server has to spawn a new process for every request), way. FastCGI is better, but a bit more com...
5,824,613
5,824,670
What compiler argument shall be provided to gcc for it to think it is g++?
Is it possible to write an argument to gcc such that it would think its G++?
This documentation states there is a flag -x to specify the language: gcc -x c++ ...
5,824,812
5,824,848
C++ Class Specification, Implementation problem
I'm having problem getting some separate compilation done. It's simple, but I can't figure out this error. I'm getting these exceptions: > 36 C:\Cpp\P6\employee.cpp expected `)' before ',' token 36 > C:\Cpp\P6\employee.cpp expectedinit-declarator before ')' token 36 > C:\Cpp\P6\employee.cpp expected `,' or `;' before ...
You always have to have a type preceding variable name. You have it in declaration but not in definition. Something like the following should fix it: Employee::Employee(std::string n, int id) { //constructor for name and ID setName(n); setID(id); }; Same goe...
5,824,819
5,824,889
Why does this private template function compile? -> Compiler Bug VS 2009
This compiles with out problems in VS 2009? Am I stupid? GCC gives a warning, that the template is private....? What am I missing? #include <iostream> using namespace std; class A { private: template<typename T> A& operator<<(const T & v) { cout << v << endl; return *this; } }; int ma...
This code should not compile - this is a bug (or silly extension) in VS. GCC should refuse it as well. The operator is inaccessible in the scope it is used. Comeau treats this correctly: "ComeauTest.c", line 28: error: function "A::operator<<(const T &) [with T=int]" (declared at line 14) is inaccessible ...
5,825,060
5,825,111
Invalid Template Error passing class function using Boost
Trying to using a template, where the argument is template<class T, boost::function<long (T*)> &f> static long myFunc(const vector<boost::shared_ptr<T>> &inputVector) { // do stuff} This is the call I make long i = myFunc<MyClass, boost::bind(&MyClass::myClassFunc, _1)>(myInputVector); where the signature of the...
Binding arguments to a function is a run-time operation. When you pass a value as a template parameter, the value has to be known at compile time. Pass the boost::function as an argument. template<class T> static long myFunc(const vector<boost::shared_ptr<T>> &inputVector, boost::function<long (T*)> &f) { // do stuf...
5,825,084
5,825,116
Compile error "'struct' type redefinition" although it's the first definition for it
Everything was working well untill I moved some code from the main file to a new class, then I had the following error: error C2011: 'color1' : 'struct' type redefinition struct color1 { color1() { red = green = blue = 0; } color1(float _red, float _green, float _blue) { red = _re...
If the compiler says it's redefined, then it probably is. My psychic debugging skills tell me that you moved the struct from a source file to a header file, and forget the include guards in that header, which is then included multiple times in a source file. EDIT: As a general rule I generally suggest avoiding leading ...
5,825,137
5,826,251
Dynamic Programming Problem
Well, I really don't need help with code itself, but understanding what exactly I am trying to do in order to write the code. In a nutshell, I am given 1000 projects each with a set of resources, and I have a (set ammount) of resources to utilize to calculate what are the best projects I can pick. the pseudocode for th...
I'd return a data structure that indicates both the profit and the solution that gets that profit. Store that exact data structure in valueMap. This will make your code more straightforward. Basically, "Write correct recursive solution. Add memoization to make it fast."
5,825,163
5,825,368
Istream consume at most N whitespace characters
Is it possible to tell a std::istream to only consume a fixed number (namely, 1) of whitespace characters when applying the operator>>? I have a string I'd like to parse into parameters, but some of the parameters are empty, which is causing subsequent calls to operator>> to fail.
Try std::noskipws : std::cin >> std::noskipws; char ws; std::string firstField, secondField, thirdField; std::cin >> firstField >> ws >> secondField >> ws >> thirdField; Or, you could slurp the entire line into a string (see std::getline), and then split it with Boost.
5,825,316
5,825,361
Moving callback function to a class causes an error!
After I moved some OpenGL code from main function to a new class I had the following error on the following row: glutDisplayFunc(OnDisplay); error C3867: 'Room::OnDisplay': function call missing argument list; use '&Room::OnDisplay' to create a pointer to member What was my fault ?
glutDisplayFunc expects a void (*func)(void), but you're passing in a void (Room::*func)(void). Since class methods receive an implicit this parameter, their pointer types are fundamentally different than regular function pointers. There's no conversion possible between them. All you can do is make OnDisplay a static m...
5,825,677
5,825,696
unresolved external symbol althought it's already defined
I've got the following error althought I have a public static member called myMember in myClass class! error LNK2001: unresolved external symbol "public: static float MyClass::myMember" (?myMember@MyClass@@2MA) Note When I double click on the error it does not take me to any line in the code! The code: class MyClass ...
You only declare myMember, define it in the .cpp corresponding to your (presumed) .h containing the class: float MyClass::myMember;
5,825,771
5,826,516
Loading JNI crashes with undefined symbols
I am trying to link my native library to a java application but when I try to run it I get a java.lang.UnsatisfiedLinkError exception complaining about missing symbols(_ZTVN10__cxxabiv117__class_type_infoE) I compiled the shared library with g++ just like any other shared library. This is my first try with JNI and I ca...
Try relinking without the -Wl,-soname,liblzw_compressor.so option. If it works I can't tell you why, other than that months ago I had a very similar undefined symbol error (may have even been the same symbol) and ditching the -Wl option from my link line fixed it.
5,825,892
5,826,017
Is there any advantage to using C++ instead of C# when using Direct3D?
Is there any advantage to using C++ instead of C# when using Direct3D? The tutorials I've found for C++ and DirectX all use Direct3D (which to my knowledge is managed). Similarly, all of the C# tutorials I've found are for Direct3D. Is Direct3D managed? Is there any difference between using D3D in either of the two la...
DirectX is entirely native. Any impression you may have that it's managed is completely and utterly wrong. There are managed wrappers that will allow you to use DirectX from managed code. In addition, DirectX is programmed to be accessed from C++ or C, or similar languages. If you look at the SlimDX project, they encou...
5,825,928
5,826,001
Is it possible to invoke a JS function from a different thread?
I'm trying to make 2 different browsers communicate with each other through native code host (C++) using JS window.external. The syntax is something like: on destination.js: window.external.register("dest", eventCallbak); function eventCallback(senderID, data) { alert("message recieved from " + senderID + " w...
Two browser instances use different instances of JS VM. You cannot in general to take one object from one VM/heap and pass it to another VM/heap. So you will need to invent some kind of marshaling here.
5,825,953
5,825,992
How to define a static member in case there is not header file?
How to define a static member in case there is not header file ? The code: class MyClass { }; int MyClass::staticMember; // Error: class MyClass has no member staticMember! Any help?
This will work: // // Inside .cpp file // class MyClass { static int staticMember; }; int MyClass::staticMember;
5,826,037
5,826,078
OpenGLESv2 Shader glGetAttribLocation returns -1
Hey, I try to code a OpenGL ES 2 engine but at shader creation the function glGetAttribLocation returns -1 which means The named attribute variable is not an active attribute in the specified program object or the name starts with the reserved prefix "gl_". But it IS defined in the shader and doesnt start...
You didn't specify which attribute is not used, but I assume it's "texcoord_vs", simply because you're not using it, and as such it's being stripped by the shader compiler. I suppose you meant to say texcoord_fs = texcoord_vs?
5,826,067
5,826,224
Read (and write) Office document custom properties without automation
I am looking for a solution for reading (and possibly writing) custom properties of Office documents (both old and new formats) without resorting to Office automation. I have found Dsofile.dll which seems to work good for old formats but chokes on new ones with a "class not registered". KB remarks say that a certain "O...
DSOFile is what to use for the binary formats. For the newer formats, you can just use XML (Open XML SDK is a fine choice, but you can also just access the DOCX/XLSX/PPTX file formats with System.IO.Packaging in .NET if you don't want to be all that heavy handed with yet-another-dll). See this article for accessing and...
5,826,125
5,826,162
min_element() within template class
I'm trying to build a home-made min-heap with template class so I can work on Dijkstra or Prim. However the find_min() function does not work with std::min_element(). Any clue will be greatly appreciated. Thanks! the error message from VC2010express, in short, says error C2780: '_FwdIt std::min_element(_FwdIt,_FwdIt)...
std::min_element's 3rd argument is either a functor object, or a function pointer to a comparator. The comparator function must be a free function; you're trying to give it a non-static member function. As there is no reason for compare_node to be a member function, you may as well make it a free function instead. Hav...
5,826,318
5,826,326
How would one get a UTF-8/Unicode string from GetOpenFileName?
I'm developing an application in MinGW/C++ that uses Windows' common dialogs. The need has arisen to collect a file name that might have non-ASCII characters in it. Is there a flag or another option for retrieving a file name in Unicode, or preferably UTF-8?
Call GetOpenFileNameW. You can do this without converting your entire app to Unicode which may be the most expedient solution. Windows API comes in 2 flavours, ANSI and Unicode. The former has functions with an A suffix. The latter have a W suffix. You are currently using the former.
5,826,423
5,826,591
searching for hundreds of patterns in huge Logfiles
I have to get lots of filenames from inside a webserver's htdocs directory and then take this list of filenames to search a huge amount of archived logfiles for last access on these files. I plan to do this in C++ with Boost. I would take newest log first and read it backwards checking every single line for all of the ...
Try using mmap, it will save you considerable hair loss. I was feeling expeditious and in some odd mood to recall my mmap knowledge, so I wrote a simple thing to get you started. Hope this helps! The beauty of mmap is that it can be easily parallelized with OpenMP. It's also a really good way to prevent an I/O bottlene...
5,826,452
5,826,469
Trying to define a function, but I get "variable or field `function_A' declared void"
#include <cstdio> #include <cstdlib> #include <iostream> using namespace std; class Student; void function_A(Student& s) class Student { void function_B() { ::function_A(*this); } int courses; }; void function_A(Student& s) { // line 18 (where error is occurring) s.courses = 1; } int main() ...
Part of your problem is you're using the type Student before it's defined by making it a parameter to function_A. To make this work you need to Add a forward declaration function_A Switch function_A to take a pointer or reference Move function_A after Student. This is necessary so member courses is defined before ...
5,826,728
5,835,422
Android NDK GLES 2.0 Nothing Drawing
I am trying to Draw with GLES 2.0 through the NDK, doing everything except creating the surface in C++, but nothing is drawing on the screen...And I can't figure out why. I have tried/verified many different things and am still at a loss. my last few guesses are these: my textures are somehow now compatible with the sc...
Actually, I'm not sure what was going on exactly, but something I changed fixed the problem =/ I tried going back over the code to re-break it, but couldn't.. but for reference, I can't guarantee what was broken, but I can say for sure, that the problem was neither the texture, nor the shader. Even though the default s...
5,826,977
5,826,997
C++ String Length problems
so im practicing the STL string class, but i can not figure out why the string->length function won't come up with the correct answer of 5, and only 2 (no matter the actual length). Here's the program i'm trying to run but it thinks that there are only 2 items between ->begin and ->end: void testFunc(string _string[]) ...
You're iterating through the first string, which is "Hi" - it has two characters, so you see two entries. If you want to go all STL, you'd need a vector instead of a C-style array (i.e. vector<string>, and use an iterator on that. If you don't want STL: void testFunc(string *strings, int stringCount) { ...
5,827,113
5,827,129
Can two classes access each other?
If I have two classes called A and B, Note: The following doesn't compile. class A { public: static void funcA() {} void call_funcB() { B::funcB(); } // call class B's function }; class B { public: static void funcB() {} void call_funcA() { A::funcA(); } // call class A's function }; Errors: error C2653:...
You have to do this: class A { public: static void funcA() {} void call_funcB() ; }; class B { public: static void funcB() {} void call_funcA() { A::funcA(); } // call class A's function }; void A::call_funcB() { B::funcB(); } // call class B's function This allows A::call_funcB() to see the B declara...
5,827,155
5,827,192
Anyway to get Visual Studio C++ to autocomplete parameter list?
Very specific issue with a specific piece of software, but I hope you fine folks can help! I define a class in a header.h file that has a few method declarations that take parameters class Lazy{ void complainForever(char * complaint, float forever = INFINITY); }; Then I go into the Lazy.cpp file to define that fun...
Why don't you try Visual Assist X. It isn't free though.
5,827,170
5,827,329
Understanding code used to draw quads in OpenGL 3.3+ core using triangles
I'm trying to draw a quad for a background (2D) using OpenGL 3.x+. Quads are deprecated, so the goal is to use two triangles to make a rectangle that fills the screen. It's working, but I'm not 100% clear on everything here. Setup GLuint positionBufferObject; GLfloat vertexPositions[] = { -1.0f, -1.0f, 0.0f, 1...
glGenBuffers(1, &positionBufferObject); says "make a vertex buffer object, and positionBufferObject is its ID." glBindBuffer(GL_ARRAY_BUFFER, positionBufferObject); says "positionBufferObject is now the current GL_ARRAY_BUFFER." glBufferData(GL_ARRAY_BUFFER, sizeof(vertexPositions), vertexPositions, GL_STATIC_DRAW); sa...
5,827,342
5,827,450
cope 3x3 matrix from a bigger one
for(int i=0;i<getNumRows();++i) { for(int j=0;j<getNumCols();++j) { int X = hfilter * threebythree(i,j,getData()); int Y = vfilter * threebythree(i,j,getData()); //cout<<X<<","<<Y<<endl; setValue(i,j, sqrt(X*X+Y*Y)); } } writeToFile(ofilename); } Image Image::threebythree(int gl...
If you're going to all the trouble of building an Image class, why not use it for data? Image Image::threebythree(int globali,int globalj, const Image &data) { Image neighbor; neighbor.setNumRows(3); neighbor.setNumCols(3); neighbor.AllocateMem(); for(int i=0 ; i<=3 ; ++i) for(int j=0 ; j<=3 ; ++j) {...
5,827,375
5,827,406
should I use member variable or declare variable inside functions?
I have a class UI to handle console I/O for my C++ program. It will have 4-5 member functions that will use a variable 'string input' to get the cin input, and some of these functions will be recursive. Now I was wondering if I should declare 'string input' at the beginning of each of these functions, or if it was bett...
If the string input is not persistently associated with your object in the long term, and is just being used locally in the short term, make it a local variable. 1) It's semantically what you mean anyway. 2) If you're calling yourself recursively, you probably want separate variables per recursive call, which local var...
5,827,427
5,855,286
C++ OpenGL Cube not showing up on screen
I have been attempting to use OpenGL with C++ lately and I have come a cross a problem when trying to render a cube with lighting, but it doesn't appear I believe this is due to some kinda of clipping error. Here is my code. The initialization function: glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glEnable(GL_DEPTH_TE...
After your edit: gluLookAt is a function just like glVertex3f and such. Therefore invoke it by just calling: gluLookAt(10.0 , 10.0 , 10.0 , 1.5, -1.0, 1.5, 0.0, 0.0, 1.0 ); Note that there is no void involved in this line of code! What the compiler sees if there is a void in front of this line is a variable declarati...
5,827,479
5,829,261
Forcing QGraphicsItem To Stay Put
I have a QGraphicsScene that is filled with QGraphicsItems, and the user is able to pan and zoom around to inspect all of the various QGraphicsItems. However, I would like to have a QGraphicsTextItem label that always stays put at the top left of the screen. Ignoring the zooms is easy, as I can just setFlags(QGraphics...
Perhaps you just want to put a regular QLabel right on the view instead of trying to make a part of the scene stay in one place as discussed in this question. Note: As mentioned in another answer, this trick will often not work with hardware accelerated views. In these cases, you will need to make the text items a part...
5,827,526
5,827,544
Exception Problems using the STL string and vector class
i'm fairly new to programming and still have no idea why its happening or how to fix this exception im getting when running this program i'm making... How do exceptions occur anyway? Well here's the code: #include <iostream> #include <algorithm> #include <string> #include <vector> using namespace std; ////////////////...
You create a vector with 56 elements in it: vector <string> Map(56); Then you define an array containing five string objects in it: string _lines_[] = {"Hi", "Holla", "Eyo", "Whatsup", "Hello"}; Then you try to read 56 string objects from that array: v 56 elements between begin()...
5,827,719
5,827,739
class has virtual functions and accessible non-virtual destructor
I have two classes: class A { public: virtual void somefunction() = 0; }; class B : public A { public: B(); ~B(); void somefunction(); }; B::B() {} void B::somefunction() { // some code } But with g++ I get errors: class A has virtual functions and accessible non-virtual destructor class B has ...
This happens because your base class A does not have a virtual destructor. For instance, if you had this code: int main() { A* a = new B; delete a; } Then the delete a call would not be able to call B's destructor because A's isn't virtual. (It would leak all of B's resources.) You can read more about virtual ...
5,827,752
5,827,808
C++ STL - why use !(w < *i) rather than (w==*i)
vector<Widget> vw; // populate vw sort(vw.begin(), vw.end()); Widget w; vector<Widget>::iterator i = lower_bound(vw.begin(), vw.end(), w); if ( (i != vw.end()) && !(w < *i) ) // Yes, it is correct! // found w in vw Here is my understanding: The return value of *i from lower_bound is always NOT less than that of ...
Because the implicit interface <algorithm> uses for sorting and that kind of stuff only requires the < operator to be defined on the data type. If they used ==, they would force developers to implement it too on custom types to benefit from these functions. In other words, if you make a sortable type Foo, to use the fu...
5,827,788
5,827,869
Learning C++, What's next? Also what's a recommended compiler?
I've been spending my "inbetween" time at the office looking into C++. I'm primarily a flash & web developer, also working on a bunch of flash games, but I thought it was time to have a look at some non-web-based languages and see if I could get some real games going. I've got the hang of how typing works, arrays, outp...
Graphics can be done using DirectX in Windows, or OpenGL on every platform. It's a whole different discussion upon which to choose. In addition to trying to work with graphics, you could try your hand at developing GUIs. I'd give Qt a shot. Be warned though, Qt is being sold by Nokia, but it's overall a very well know...
5,827,846
5,827,879
How can I check values in a C++ map without getting compiler errors in a "const" member function?
I have a member function that compares data in a C++ map. I declared the member function as constant: bool operator == (UnitSet otherSet) const; but as soon as I use myMap["l"] to access and compare values I get compiler errors about myMap being constant. Is there a way around this while keeping the const directive? I...
std::map unfortunately doesn't have a const overload of the [] operator. This is because whenever you access a key that doesn't exist, the map creates an element for it; if the map was const, that would be impossible. Therefore, there's no way to call it with a constant map. It isn't related to the behavior of your Uni...
5,827,866
5,827,920
Printing one variable based on the contents of another variable
I have a function similar to the following that takes an integer as a parameter, and using this integer I want to to access a specific variable. Of course, I can just casebash using the case/switch statement, or if/else, but this is far too dirty and I'm guessing there must be some form of elegant solution. static unsi...
If you want to access one of the frames based on an integer, then simply put the frames into an array: static unsigned char* frames[30]; frames[0] = (unsigned char*)strdup("first frame's char"); frames[1] = (unsigned char*)strdup("second frame's char"); Then you can directly and efficiently index to frames[i]. In C++...
5,827,903
5,828,158
Can template classes have static members in C++
Can a template class in C++ have static members? Since it doesn't exist and is imcomplete before it is used, is this possible?
Yes. The static member is declared or defined inside the template< … > class { … } block. If it is declared but not defined, then there must be another declaration which provides the definition of the member. template< typename T > class has_static { // inline method definition: provides the body of the function. ...
5,828,165
5,865,936
How to find runs of bold text inside of a RichEdit control?
I can obviously do it one character at a time using EM_GETCHARFORMAT, but it is extremely slow. One idea is to somehow use the ITextDocument/ITextFont interfaces, the other is to use the EM_STREAMOUT message and manually parse the RTF. But I can't decide which approach is better and am very fuzzy on the implementation ...
I've found a solution that satisfies me and think will share it with you: The ITextRange interface contains a very useful method Expand which can be used to find continuous runs of constant character (tomCharFormat) and paragraph (tomParaFormat) formatting. Here is some sample code (warning: code is a proof-of-concept ...
5,828,446
5,828,533
Perl Vs Ultraedit Scripting
I'm wondering if Perl is a good (easy to use and to learn) tool for this: I'd like to do some custom preprocessing on my C/C++ source code. Basically, this's to allow me to insert my own custom annotations to the source code and generate new codes base on it. The required processing is mainly line oriented search/rep...
Yes, Perl is a good tool for what you want. I'd go for Python, it's quick, easy, beautiful and has a good regex interface in the STL; but it's purely a matter of taste.
5,828,485
5,828,549
g++ is giving "unresolved overloaded function type" with template parameters
Reduced to basic form, I'm trying to do something like this with a binary search tree: template <class Item, class Key> class bst { public: Item val; Key key; bst *left; bst *right; private: }; template <class Item, class Key, class Process, class Param> void preorder_processing1(bst<Item, Key> *root, ...
template <class Item, class Key, class Process, class Param> void preorder_processing1(bst<Item, Key> *root, Process f, Param g) This needs to take a const bst<Item, Key> * Additionally, your call to f(root->val, g); will have problems - root->val isn't a bst<Item, Key> const *. You likely mean f(root, g)
5,828,603
5,828,716
how to parse several arguments using command line arguments
i am writing a command line utility in which i want to parse several arguments: right now i am not reading data from address(so please don't get confuse by -addr); my primary objective is to design the framework so that i can parse several arguments as follows. filename read -addr value -addr2 value2 -addrN valueN -len...
consider using the Getopt library or some of its modifications, it can make yout life easier. http://www.boost.org/doc/libs/1_41_0/doc/html/program_options.html
5,828,877
5,829,147
access overloaded template functions
hey guys, i'm confused as to how to access an overloaded template function like this one: template <typename T> friend istream& operator>> (istream& in, Matrix& right) { for(int i=0; i<right.rows*right.cols; i++) cin >> right.elements[i]; } with a function such as: template <typename T> Matrix(T r,...
I am assuming that you are declaring a class template Matrix that has a type argument T, and that you want to use the defined operator>> (you should make this more explicit in the question): template <typename T> class Matrix { int rows, cols; T* elements; public: Matrix( int c, int r ); // Do you reall...
5,829,164
5,829,607
How to crash a system programmatically
If I could write a user program that would crash my OS (not my application), how would I do it? I was thinking somehow switch my usermode program to kernel mode and cause a memory corruption. Is it possible? Note: I am not creating a virus. Just curiosity.
KeBugCheck on Windows is the documented way to get a BSOD. You can also try deleting the root registry key (\REGISTRY) in Windows XP, using the native NT API.
5,829,385
5,830,761
Opencv consecutive frames capture from webcam
I'm developing a realtime opticalflow app with Opencv (C++). I don't understand how capture two consecutive frames to apply Lucas-Kanade Tracking method. This don't work: CvCapture* capture = cvCaptureFromCAM(1); IplImage *imgA=cvQueryFrame( capture ); IplImage *imgB=cvQueryFrame( capture ); I also have tried this, bu...
cv::Mat m1, m2; cv::VideoCapture cap(0); if(!cap.isOpened()) ;// ... throw error here cap >> m1; cap >> m2; // m1 and m2 now contain consecutive frames.
5,829,487
5,829,596
How do I override the bool operator in a C++ class?
I'm defining a ReturnValue class in C++ that needs to report whether a method was successful. I want objects of the class to evaluate to true on success and false on error. Which operator do I override to control the truthiness of my class?
The simple answer is providing operator bool() const, but you might want to look into the safe bool idiom, where instead of converting to bool (which might in turn be implicitly converted to other integral types) you convert to a different type (pointer to a member function of a private type) that will not accept those...
5,829,499
5,830,428
How to let Boost::random and Matlab produce the same random numbers
To check my C++ code, I would like to be able to let Boost::Random and Matlab produce the same random numbers. So for Boost I use the code: boost::mt19937 var(static_cast<unsigned> (std::time(0))); boost::uniform_int<> dist(1, 6); boost::variate_generator<boost::mt19937&, boost::uniform_int<> > die(var, dist); die.engi...
I have to agree with the other answers, stating that these generators are not "absolute". They may produce different results according to the implementation. I think the simplest solution would be to implement your own generator. It might look daunting (Mersenne twister sure is by the way) but take a look at Xorshift, ...
5,829,744
5,829,798
Why does this program call operator () instead of the constructor?
Here is a program that compiles without warning on e.g. GNU C++: $ g++ -o t -Wall -pedantic -Wshadow t.cpp $ ./t.exe Calling barney::barney() Calling foo::operator()() Calling barney::barney() But it completely fails to compile on MSVC++: $ cl /EHsc t.cpp Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 15.00.3...
Because in the fred structure you have a member fred (of type foo) which shadows the definition of struct fred. When you then do: return fred(); ... the fred refers to the object of type foo rather than the fred struct type, and so the foo () operator is called. Notice that the name "fred" refers to two different thin...
5,830,060
5,830,131
class static member function chosen over global function with same name?
Doubt originated from here int g() { cout << "In function g()" << endl; return 0; } class X { public: static int g() { cout << "In static member function X::g()" << endl; return 1; } }; class Y: public X { public: static int i; }; int Y::i = g(); initially I though that as symbol resolu...
Note: I think my earlier answer was wrong. Its not Koenig Lookup i.e Argument-dependent name lookup (ADL). So I deleted my (earlier) answer since I found the relevant section from the Standard which answers your question. Your code is directly from the section §9.4/2 of the C++03 Standard. A static member may be refer...
5,830,338
5,830,439
How does node.js/[my own library/plugin] run on v8?
Does it use any libraries like this: http://code.google.com/p/v8-juice http://ui.ajax.org/#o3 https://github.com/tsa/vu8 Or has it written its own libraries? If v8 is written for executing javascript, why do node.js libraries use C code? Just for the filesystem/event stuff? If so, why was that necessary, doesn't v8 ...
node.js includes its own embedded version of v8 (not sure if it is customized or not, but it could be). Javascript itself provides no interface to things like file system I/O, so that you as the embedder (in this case node) have to provide native code objects to expose that functionality. The browser does the same thi...
5,830,369
5,830,467
c++ .h and .cpp files - about methods
HI. How can I define a bool method in .h file and work with it in the cpp file? I have my.h #include <string> public class me; class me { public: me(); private bool method(string name); //it is ok?? } my.cpp #include 'my.h'; me::me() { method(string name); //can i do this? isn't there another alternative? } method...
There are a number of issues with your code. my.h #include <string> // public class me; // Absolutely not needed. From which language did you get this? class me { public: me(); private: // You need the colon here. bool method(string name); //it is ok?? // No. The class is called std::string. You should pass it by ...
5,830,378
5,832,361
child waiting for another child
is there a way for a forked child to examine another forked child so that, if the other forked child takes more time than usual to perform its chores, the first child may perform predefined steps? if so, sample code will be greatly appreciated.
Yes. Simply fork the process to be watched, from the process to watch it. if (fork() == 0) { // we are the watcher pid_t watchee_pid = fork(); if (watchee_pid != 0) { // wait and/or handle timeout int status; waitpid(watchee_pid, &status, WNOHANG); } else { // we're being...
5,830,413
5,830,455
memory copy from void*
I have following code, char * segbase_char = (char*)segbase; As debugged in gdb, it prints segbase_char = 0x80e2da8 segbase = 0xb7ffd000 Any ideas?
It is possible that optimisation has resulted in code being moved around, such that the load of segbase_char has been delayed. Try compiling with a lower level of optimisation enabled.
5,830,636
5,936,039
Multisampling in a DirectX 9 application on Windows 7
In an application I try to use multisampling for anti-aliasing on some simple 2D geometry. It was developed originally on Windows XP where I had no problem enabling multisampling for my DirectX device and for any additional swap chains. Now, on Windows 7 the multisampling feature seems to not work at all. I've extracte...
Removing the D3DPRESENTFLAG_VIDEO helped to enable multisampling on Windows 7. It was added because the application uses DirectX to display video. But as the flag is not very well documented and seems to be only a hint for the video driver, I don't know which side effects setting or not setting the flag has. It has no ...
5,830,699
5,847,761
GetQueuedCompletionStatus delayed
I have written complex library for managing network communication based on iocp mechanism. Problem is that when server closes the connection by calling API method closesocket() this information is sometimes transmitted to client delayed by seconds or even minutes. My code for detecting connection closure looks like thi...
I tried to experiment with linger parameter as Len wrote but this did not help. Adding call of shutdown() function just before closesocket() helped me. After analyzing packets reaching network interface on client (with WireShark) I have found that RST packet was replaced by FIN packet. Curiously that RST packet was not...
5,830,768
5,831,233
Compiler error when including boost/asio.hpp on C++ Builder 2010
EDIT: SOLVED! I added BOOST_ALL_NO_LIB to my Conditional defines and added the errorcode.cpp from /libs/system/src/ folder to my Project. I recently set up C++ Builder and been playing around with it to get my head around C++. I need to use boost-asio for a project I will be working on, but I have come across a bit of...
Solved as per the edit: I added BOOST_ALL_NO_LIB to my Conditional defines and added the errorcode.cpp from /libs/system/src/ folder to my Project.
5,830,998
5,831,194
http post & get is blocking call?
I see most http codes in php. I'm about to write some http calls in c++ using CURL. Wonder if http is inherently blocking(opposed to non-blocking). IE, when you send get/post message, your thread is blocked until it gets the response? If it's not, is there a way to perform non-blocking http get or post with CURL? Tha...
HTTP is a protocol, so it's not inherently blocking or non-blocking. The only thing resembling 'blocking behavior' in HTTP is that you can't send two requests or two responses at once in the same pipeline - you have to wait for the request to finish before sending another one. So your real question about blocking opera...
5,831,073
5,831,221
Iterator "pointing" to a member of an object
I admit I had difficulties coming up with a reasonable description for this. I cannot think of a good term that would describe precisely what I'm looking for. Perhaps this could be called a slicing iterator. Let's say I have something like this: struct S { int i; char *s; float f; }; std::vector<S> v(1...
If you're looking for an iterator that converts S into its S::f, this could certainly be done using boost (what can't be?): std::cout << *std::min_element( boost::make_transform_iterator(v.begin(), boost::bind(&S::f, _1)), boost::make_transform_iterator(v.end(), boost::bind(&S::f, _1)) ...
5,831,241
5,831,261
How does this method of removing an element from a stack work?
I just started taking a C++ class at my local college and the instructor gave the class an assignment in which we must create a vector and remove an element from the middle of the stack. She provided this example: vect[3] = vect[vect.size()-1]; vect.pop_back(); Now.. I've tested it and it works I'm just unsure how it ...
You want to delete an element from the middle of the vector, so you simply overwrite it with the last element (with index size()-1) - since the last element thus becomes redundant, we can pop_back() it. Finally we have the desired result - the vector size is decreased by one and the old value at vect[3] is gone. Note t...
5,831,353
5,831,484
C++ toString member-function and ostream operator << integration via templates
I'm a beginner C++ developer and I have a question about toString and ostream operator integration via templates. I have such code: struct MethodCheckerTypes{ typedef unsigned char TrueType; typedef long FalseType; }; template<typename T>struct HasToString{ template<typename K>static...
The approach to implementing operator<< by itself is normal. But using parts of the language you do not understand is bad practice (I do not believe that a beginner can write such code). You have two alternatives: to implement a toString member function or overload operator<<(std::ostream&, T). The latter approach e...
5,831,621
5,831,791
how to compile a VC project using g++?
i have source code of vc++ project. Now I am using linux. i know how compile a single file .cpp not a whole project. So how to compile a VC project using g++ ?
A slight advantage of Makefiles would be possible integration with autotools (cough - It might prove handy to get the starting point for feature macros).[2] There is a tool as part of winemaker that is EXCEEDINGLY helpful with fixing up a source tree that was assuming case insensitive names to work on a case-sensitive ...
5,831,765
5,831,797
C++: "... is not a polymorphic type" while using boost::dynamic_pointer_cast
Why do I receive the following error for the following code? 1>C:\Libs\boost_1_44\boost/smart_ptr/shared_ptr.hpp(259): error C2683: 'dynamic_cast' : 'my_namespace::A' is not a polymorphic type 1> D:\[location]\[header_filename].h(35) : see declaration of 'my_namespace::A' 1> C:\Libs\boost_1_44\boost/s...
dynamic_cast works ONLY with polymorphic class. And polymorphic class is that which has atleast one virtual function, even be it the destructor. //polymorphic classes struct A { virtual ~A(); //even virtual destructor makes a class polymorphic! }; struct B : A { void f(); }; //non-polymorphic classes struct...
5,831,863
5,831,915
C++: Why does a struct\class need a virtual method in order to be polymorphic?
Following this question, I'm wondering why a struct\class in C++ has to have a virtual method in order to be polymorphic. Forcing a virtual destructor makes sense, but if there's no destructor at all, why is it mandatory to have a virtual method?
Because the type of a polymorphic object in C++ is, basically, determined from the pointer to its vtable, which is the table of virtual functions. The vtable is, however, only created if there's at least one virtual method. Why? Because in C++, you never get what you didn't explicitly ask for. They call it "you don't h...
5,831,868
5,831,910
Print .pdf filenames from a directory with Boost.regex
This is my code: path Path = "e:\\Documents\\"; boost::regex reg("(*.pdf)"); for(recursive_directory_iterator it(Path); it != recursive_directory_iterator(); ++it) { if(boost::regex_search(it->string(), reg)) { cout << *it << endl; } } But I always get and Abort() error in Visual Studio, after runn...
*.pdf isn't a regex, it's a glob (for file matching). You need boost::regex reg("(.*\\.pdf)"); .: matches any one character *: 0 or more of the previous match \\: to make a single \ for escaping (ignore the regex meaning of the next character)
5,832,041
5,832,147
Handle Alt Tab in fullscreen OpenGL application properly
When trying to implement a simple OpenGL application, I was surprised that while it is easy to find plenty of examples and documentation on advanced rendering stuff, the Win32 framework is poorly documented and even most samples and tutorials do not implement this properly even for basic cases, not mentioning advanced ...
If the application uses some animation loop, suspend the loop, then just minimize the window. If it changed display resolution and gamma revert to the settings before changing them. There's no need to destroy OpenGL context or resources; OpenGL uses an abstract resource model: If another program requires RAM of the GPU...
5,832,196
5,832,461
Risks of running on single byte character app on a MBCS OS
I have an MFC application where the Character Set is "Not Set". What are the risks associated with running this application on a OS that has a Multi Byte Character Set code page?
The "Character Set: Not Set" option defines neither _MBCS nor _UNICODE. That means that you're using the *A series of functions. Those will return MBCS strings, even when _MBCS is not defined. If _MBCS doesn't affect the strings returned from the *A functions, then what does it do? It maps some <tchar.h> tcs* function...
5,832,250
5,832,351
c++ difference between std::string name and std::string &name
I have a lib.h, lib.cpp and test.cpp. I would like to ask what is better? lib.h class c { std::string name; }*cc; lib.cpp { std::cout << "the name is:" << name << std:: endl; } test.cpp main() { c tst; tst.name="diana"; } What should I use? std::string name or std::string *name? How can i work with ...
First, I hardly believe your code will compile while in your main you try to get access to private data member name. About &. It is really hard to define where to start. In short std::string &name is called reference to object of type std::string. Reference is somehow an alias to some other object. The main feature is,...
5,832,464
5,832,517
boost string_algo return value on find failure
I want to find the first space on a line using boost::string_algo's find first: const boost::iterator_range<std::string::iterator> token_range = boost::find_first(line, " "); I can't seem to find anything in the docs that says what this returns if it doesn't find a space, though. Do I need to test token_range.end() ag...
I think you should just test token_range.empty(), like this: const boost::iterator_range<std::string::iterator> token_range = boost::find_first(line, " "); if (!token_range.empty()) { // Found a a match } boost::iterator_range also has a bool conversion operator, so you can even drop the empty() function call, and...
5,832,711
5,832,894
MFC: Confusion in an ON_COMMAND function?
Alright, so here's this function . . ON_COMMAND (ID_COLOR_RED, OnColor) ON_COMMAND (ID_COLOR_GREEN, OnColor) ON_COMMAND (ID_COLOR_BLUE, OnColor) . . . void CMainWindow::OnColor () { UINT nID = (UINT) LOWORD (GetCurrentMessage ()->wParam); m_nCurrentColor = nID _ ID_COLOR_RED; } So, in here the LOWORD of ...
I have no idea what that code does. Primarily because m_nCurrentColor = nID _ ID_COLOR_RED won't compile. You have an underscore (_) between nID and ID_COLOR_RED. That doesn't mean anything to the compiler. Did you mean to type a minus sign (-), instead? But more generally, the ON_COMMAND macro is used to process WM_C...
5,832,890
5,833,124
GCC problem - invalid conversion from 'void (*)(MyObject*, bool)' to 'const void*'
I really don't want to, but I have to emulate COM logic in my program and I'm using standard COM_ADDREF macros, but I keep getting the following error: invalid conversion from 'void ()(MyObject, bool)' to 'const void*'... What should I do? #define COM_ADDREF(pObj, pMaster) ((pObj)->AddRef((pMaster), __FILE__, __LINE__,...
It doesn't look to me like this is the code that's generating that error. When I compile it with g++ (fixing the obvious errors like DWORD and modifying class state in a const function, it just tells me it can't find a matching function. The gist is you're passing a bool as the second argument to COM_ADDREF and the bas...
5,832,995
5,833,051
c++ nonconst-const-overloaded method choosing
I have const-overloaded methods in my class: class A{ public: typedef int data[10]; data& operator[](int index); const data& operator[](int index) const; } This class is implementing copy-on-write for its internal data. I figured that since i am allowing to access data directly, i must create c...
Yes: const_cast<A const&>(anAObj)[5].
5,833,150
5,833,483
Storing values from a vector to a string as comma seperated values
how can I store the values returned from a function to a string as comma seperated values. Can anyone help me..? const myVector &vecList = obj.get_List(); vector<myNumVector *>::const_iterator iter; for (iter= vecList.begin(); iter!= vecList.end(); iter++) { string myNum = (*iter)->get_myNum(); string myNumList = ?...
As can be seen from the links I posted, there are lots of ways to do this. Here is, I believe, the simplest: #include <vector> using std::vector; #include <string> using std::string; #include <boost/assign/list_of.hpp> using boost::assign::list_of; namespace ba = boost::assign; vector<string> victor = list_of ("Cl...
5,833,226
5,833,291
C++,Need help to understand some constructors and functions in a vector class using pointers
Greetings All; I have to develop a C++ class library comprising a collection of numerical techniques for scientific computing. The library should implement Vector class (using pointers) with some basic functionality stated in a header file "Vector.h". #ifndef VECTOR_H #define VECTOR_H template <class T> class CVector ...
Q1: This constructor can be used to fill the vector with the contents of the n elements of the array starting at a. For example: float a[42] = { 31, 41, 59 }; CVector<float> v( 3, a ); Q2: The first is a copy constructor, the second is an assignment operator. The copy constructor is used to copy values into a f...
5,833,527
5,833,693
How do you use the pause assembly instruction in 64-bit C++ code?
Since inlined assembly is not supported by VC++ 2010 in 64-bit code, how do I get a pause x86-64 instruction into my code? There does not appear to be an intrinsic for this like there is for many other common assembly instructions (e.g., __rdtsc(), __cpuid(), etc...). On the why side, I want the instruction to help wi...
Wow, this was a very hard problem to track down, but in case anybody else needs the x86-64 pause instruction: The YieldProcessor() macro from windows.h expands to the undocumented _mm_pause intrinsic, which ultimately expands to the pause instruction in 32-bit and 64-bit code. This is completely undocumented, by the wa...
5,833,766
5,833,919
Running a program from command prompt and using argv in C++
I have written a program that takes the filename from argv[1] and do operations on it . When debugging from visual studio I pass the filename from project options>>debugging>>command arguments and It works fine and prints all results correctly . But when trying from the command prompt , I go to the dir of project/debug...
You don't check if file was successfully opened, whether getline returned error code or not, or if string to integer conversion didn't fail. If any of those error occur, which I guess is the case, nLines will be equal to 0, no cycles will be performed and program will exit with return code 0.
5,834,030
5,834,068
Error [(?testMember@TestClass@@2MA) already defined in TestClass.obj] instead of it's not alrealdy definded !
In the following class: class TestClass { public: int staic testMember; }; int TestClass::testMember; I've got the following compiler error: error LNK2005: "public: static float TestClass::testMember" (?testMember@TestClass@@2MA) already defined in TestClass.obj Note: I've tried to simulate the problem in a se...
Your definition: int TestClass::testMember; ...is probably in the same H file as the declaration: class TestClass { public: int staic testMember; }; Move the definition to it's own CPP file. You need to define it only once.
5,834,508
5,834,712
Usage limitations during the DllMain Attach and Detach process
One colleague of mine has troubles during the DllMain Detach process. His bug seems not to appear in all cases, but fairly often. While trying to help him, I kind of remembered of some usage limitations during the DllMain Attach and Detach process, but I am not sure I remember well since it was 2 year old technical di...
Avoid calling LoadLibrary and related APIs. In addition to Steve's link, here are some good relevant posts from Raymond Chen's The Old New Thing: https://devblogs.microsoft.com/oldnewthing/20040127-00/?p=40873 https://devblogs.microsoft.com/oldnewthing/20040128-00/?p=40853 https://devblogs.microsoft.com/oldnewthing/20...
5,834,617
5,834,636
Error: expected initializer before '.' token
I am fairly new to using classes and the Object Oriented side of C++ and get the error in the title. I am writing a game of Tetris using SDL. I have a class definition in shapes.h class shape { public: SDL_Surface *colour; int rotation1[4][4]; int rotation2[4][4]; int rotation3[4][4]; int rotation4[...
bool I.load() shouldn't it be bool shape::load() ? I is just an instance of type 'shape'. How can you use 'I' inside the function implementation as it knows nothing about the 'I' instance! You probably want to do this: 1. Add a construct with parameter to specify the picture for the instance: class shape { public: //...
5,834,642
5,834,777
How use std::multiset with multiple comparator function?
Good afternoon, I have a C++ class Range which implements a operator < for use by std::multiset<Range> ranges_type. Since the multiset constructor don't specify a a custom comparator functor, it uses the std::less operator <. However, I need to use a second comparator functor for std::multiset ranges_type. Specifica...
Sounds almost like you'd be better if you used something from Boost::MultiIndex rather than trying to force several different comparator functions onto a std::multiset. They have a bunch of different container types (see here.) In particular I'd look at the ordered_indices versions.
5,834,778
5,835,035
How to tell where a header file is included from?
How can I tell where g++ was able to find an include file? Basically if I #include <foo.h> g++ will scan the search path, using any include options to add or alter the path. But, at the end of days, is there a way I can tell the absolute path of foo.h that g++ chose to compile? Especially relevant if there is more ...
This will give make dependencies which list absolute paths of include files: gcc -M showtime.c If you don't want the system includes (i.e. #include <something.h>) then use: gcc -MM showtime.c
5,835,031
5,835,092
Building "Monolithic" Libraries
I have a series of small library "modules" designed to handle very specific tasks. A single module usually consists of just a .h and a .cpp, and possibly another set to provide relevant non-friend, non-member functions that the user might find useful. For example, Foo.h might declare a class called Foo, that Foo.cpp d...
Many compilers cannot "precompile" templates into libraries. My best suggestion is to treat them like header files; header files are not compiled into libraries, they are just included. I compile code into a library when the amount of changes is minimal. This often speeds up the build process since those files don'...
5,835,493
5,835,561
c++: No instance of overloaded function?
// stock.h #ifndef STOCK_H #define STOCK_H // declare Stock Class class Stock { private: string StockExchange; string Symbol; string Company; double Price; int Shares; public: Stock(); Stock(string stockExchange, string symbol, string company, double price, int shares); void displaySto...
You've not included <string> header file in stock.h header file, even though you're using std::string in it. Maybe that is causing this error message (if that is the case, then I would say its really a bad message). Another problem is that in Stock class definition, you've written this: bool Stock::operator > (Stock & ...
5,835,761
5,835,841
Ideas for sharing elements between vectors
I am working on a toy language, following is what I am trying to do, x = [1 2 3 4 5] this defines a vector then, y = rest(x) now y contains all elements of x except first. On the native side x is a vector and when user calls rest on it will make a full copy of it self except the first element. Here is the problem I a...
You could store the [1, 2, 3, 4, 5] in some memory, and make x point to that piece of memory, i.e. template <typename T> struct slice { T* begin; T* end; }; .... int backing_store[] = {1, 2, 3, 4, 5}; // ^-- the expression [1 2 3 4 5] create this .... slice<int> x (backing_store, backing_store + 5); // ^-- the assi...
5,835,777
5,835,852
CRC calculation output
Is 0 a possible checksum for a cyclic redundancy check (CRC)? I'm using boost to calculate a CRC: const unsigned int CrcPolynomial = 0x11021; const unsigned short InitialValue = 0xffff; boost::crc_optimal<16, CrcPolynomial, InitialValue, 0, true, true> Crc; // process some bytes... int x = Crc.checksum(); // <------ ca...
Yes. Take any message, x, and compute its CRC, crc(x). Then crc(x . crc(x)) will be 0 (where . denotes concatenation). In fact, this relationship can be used to verify that a message + CRC has been transmitted correctly (see for instance the second animated diagram at http://en.wikipedia.org/wiki/Computation_of_CRC)....
5,835,829
5,837,137
Issue with Duplicate symbol in link phase of project build in Xcode
I've been building a game application for iOS. The application was working fairly well, but I've done a fairly large restructure today to be a little more model-view-controller 'compliant'. I've built the main game engine in C++, but use Objective-C for managing the viewControllers, views etc. Now, when I compile the p...
I can think of 3 causes for this: 1) Accidentally #including a .cpp file, 2) forgetting #ifndef guards in the header file, 3) forgetting inline when writing the method definition in a header file.
5,835,850
5,836,917
Parsing .txt file for double variable input in C++
Currently working on a snippet to input variables in which a user changes a text file to be used later. Storing these in an array, and later referencing them for some openGL. The input text file looks something like this. something = 18.0; something else = 23.4; ... 6 lines total //the variable of type ifstream: ifs...
To apply what NattyBumppo had to say just change: n[i]=strtod(strtok(buf, ";"), NULL); to: strtok(buf," ="); n[i] = strtod(strtok(NULL, " ;"), NULL); delete buf; Of course, there are a lot of other ways to do it without strtok. Here's one example: ifstream input; input.open("temp.txt", ios::in); if( !input.good() ) ...