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,960,540 | 5,961,224 | Adding a button to the title bar | I am writing a C++ application using Qt4 and looking to implement a GUI similar to Firefox 4. That is, I need to remove the default context menu in the top left corner of the window and replace it with three buttons. If you notice the button in Firefox 4 is right at the top in the title bar and I am uncertain as to how... | It won't be easy and will not be cross-platform. Read this thread in the qt forums.
|
5,960,754 | 5,960,793 | no duplicate function for a lottery program | right now im trying to make a function that checks to see if the user’s selection is already in the array , and if it does itll tell you to choose a diff number. how can i do this?
| Do you mean something like this?
bool CheckNumberIsValid()
{
for(int i = 0 ; i < array_length; ++i)
{
if(array[i] == user_selection)
return false;
}
return true;
}
That should give you a clue, at least.
|
5,960,791 | 5,960,952 | C, C++ Interface with Python | I have c++ code that has grown exponential. I have a number of variables (mostly Boolean) that need to be changed for each time I run my code (different running conditions). I have done this using the argument command line inputs for the main( int argc, char* argv[]) function in the past.
Since this method has become c... | Interfacing between C/C++ and Python is heavily documented and there are several different approaches. However, if you're just setting values then it may be overkill to use Python, which is more geared toward customising large operations within your process by farming it off to the interpreter.
I would personally recom... |
5,960,829 | 5,960,847 | c++ ifstream to char * | my code reads a file with ifstream and parse it, now I changed some things and I don't need to read the file, 'cause is read from another place, so I have a char* instead to ifstream... how can I change my code where I use ifstream.get()?
thanks again
| You just put your char * into an std::stringstream.
std::stringstream buffer(your_string);
You can then use buffer almost like it was an std::ifstream (you cannot open or close it). Ideally, your parse-method would take a reference to an std::istream as parameter, then it would not mind what kind of input-stream it re... |
5,960,979 | 5,961,066 | Using C++ vector::insert() to add to end of vector | I'm writing a little piece of code where I'll have to insert values into a C++ STL vector at a certain place depending on values in the vector elements. I'm using the insert() function to accomplish this. I realize that when I want to add a new element to the end of the vector, I could simply use push_back(). But to ke... | a.push_back(x) is defined to have identical semantics to (void)a.insert(a.end(),x) for sequence containers that support it.
See table 68 in ISO/IEC 14882:2003 23.1.1/12 [lib.sequence.reqmts].
Regarding the running time of vector.push_back(x) vs. vector.insert(vector.end(), x) consider the emphasized part:
Table 68 li... |
5,961,055 | 5,961,341 | JNI what types can I use instead of given (unsigned int, const char*, const wchar_t*, .... ) | Stackoverflow Users !
I am trying to covert some functions that I had written in c++ to java. Exactly I have a .so library witch I have written in c++ and now I must call functions from my Android application. Functions like this:
unsignd int Uninitialize();
---------------------------------------
unsignd int DeviceOpe... | For starters, you'll have to map your types to Java types. As you say,
there is no unsigned in Java, and no wchar_t. Once you've decided
what types to use on the Java side (e.g. int instead of unsigned, or
maybe long; and probably java.lang.String for both char* and
wchar_t*), you'll have to declare your native metho... |
5,961,242 | 5,961,423 | Can you UTF8Encode a System::String^ to a Byte*? |
Possible Duplicate:
Whats the diffrence between an array<Byte>^ and a byte*?
i am translating some c# code to c++ however translating the piece about UTF8Encoding, i get stuck that c++ returns a array^ while i need a byte* as areturn type. I spend a long time on this code trying to get around it but i keep failing. ... | I think there is no way to do a conversion from array to X* without manually copying each element. This would look something like following snippet:
byte* StrToByteArray(System::String^ unicodeString)
{
UTF8Encoding^ utf8 = gcnew UTF8Encoding;
array<Byte>^ encodedBytes = utf8->GetBytes( unicodeString );
con... |
5,961,244 | 5,968,775 | Is it possible to compile System Verilog functions to C or C++? | I work on a high-level simulator written in C++ for some hardware that is written in System Verilog.
The System Verilog code includes a number of functions that contain only logic (that is, nothing time-consuming, no flip-flops). I want to reuse this code in my C++ simulator.
Is there any way to reuse these functions ... | Typically this kind of integration is done in the other direction, meaning calling C/C++ routines from Verilog. Of course, that only makes sense for verification components, obviously that can't be synthesized. The most likely environment to do what you want is a SystemC/Verilog cosimulation, but that implies both the ... |
5,961,301 | 5,961,463 | Quicksort of 3D array based on another 1D array | I have a 3D array containg values and I want to sort it based on the values listed in 1D array.
For example,
The 3d array has the values of:
1 2 3
4 5 6
7 8 9
and the 1D array has the values of:
20
11
12
so if we considered that the 3D array is related the 1D array (rows are related to each other), then the result I... | You can implement a "argument quicksort" that returns the indices that would sort an array quite easily. Here is an implementation in C++:
#include <algorithm>
template <class IndexContainer, class DataContainer>
void arg_qsort(IndexContainer& indices,
const DataContainer& data,
int left... |
5,961,391 | 5,961,521 | zip library for native C++ with remove/modify capabilities | I am looking for a simple zip library (prefers without dll/lib) that will have zip modification capabilities.
The only option I've found so far to update/remove entries is by creating a temp file and writing everything to this temp, and than rename it to the original file.
Does anyone know a better way to update/remove... | libzip has support for replacing: zip_replace(3) and deleting: zip_delete(3) files in a zip archive.
|
5,961,519 | 5,962,360 | Calling TBB 'parallel_for' in python thread | I have a custom c++ module for python that exposes functions, some of which use TBB (tbb21_015oss) to accelerate processing.
Until now, I had no problem when calling a TBB-accelerated function from Python (2.6.2) in a Win32 environment.
But now, I have a problem when calling such a function from a Python thread (create... | With TBB 2.1, each external thread that uses TBB should first create its own task_scheduler_init object; a single global object will not work.
Later versions of TBB relaxed this requirement; now such a thread-specific initialization object is created implicitly if absent.
You might try whether mechanical replacement of... |
5,961,771 | 5,961,836 | Is it possible to call the constructor of a super class, two classes away from the current class in C++ | I have three classes that inherit as follows:
Class_A
Class_B : public Class_A
Class_C : public Class_B
Class_A contains a constructor:
public: Class_A(const char *name, int kind);
Class_B does not contain that constructor.
In Class_C I wish to invoke the constructor of Class_A. Something like:
Class_C(const ... | If you can't change the code that generates B, then you are out of luck, AFAIK. But if the A class contains such a constructor, maybe you can get away with adding a simple member function that sets those two variables and call it from inside the C constructor? May not be as efficient as it gets, but atleast it works.
|
5,962,082 | 5,962,233 | Disabling system calls in C++ | Is it possible to disable system calls when compiling C++ code? And if it is, how would I do that?
And to extend this question a bit. I wish to make program to not be able to interact with operating system, except for file reading and writing. Is it possible to do this?
EDIT: With not be able to interact with OS, I mea... | Yes, it's certainly possible.
Take a look at the source code for geordi to see how it does it. Geordi is an IRC bot that compiles, links and runs C++ code under an environment where most system calls are disabled.
|
5,962,131 | 5,962,310 | C++ application collapsing after some hours | i have an application written in C++ that uses opencv 2.0, curl and a opensurf library. First a PHP script (cron.php) calls proc_open and calls the C++ application (called icomparer). When it finishes processing N images returns groups saying which images are the same, after that the script uses:
shell_exec('php cron.p... | On Unix-alike systems, child processes inherit the open file descriptors of the parent. However, when the child process exits, it does close all of its copies of the open file descriptors but not the parent's copies.
So you are opening file descriptors in the parent and not closing them. My bet is that you are not clo... |
5,962,262 | 5,962,335 | How can I create a variable with the same type as a given function? | I have a C++ function like
int f( const std::string &s, double d );
Now I'd like to create a variable which holds a pointer to f. This variable should have the correct type (int (*)( const std::string &, double ) - but I don't want to write out that type explicitely. I'd like to deduce it from f so that I don't repeat... | C++0x added decltype which does what you want (if I understood correctly).
Another option might be Boost::Typeof which is intended to provide the same functionality until decltype is supported in all compilers.
|
5,962,272 | 5,962,316 | How to extend existing template in C++? | I am working with legacy code of a template that is based on
template<class keyType, class dType> Foo Bar(const dType val)
Somewhere in that code is a place where someone made a debug function like this:
virtual void getDebugStr01(int db_id, OFCString & db_str)
{
//OFCStringStream ss;
if(db_id==0)
{
... | getDebugStr01() should be a member of a class/struct. virtual methods cannot be stand alone.
You can do something like,
Foo Bar (const float f)
{
...
}
|
5,962,285 | 5,973,540 | cmake: compilation statistics | I need to figure out which translation units need to be restructured to improve compile times, How do I get hold of the compilation time, using cmake, for my translation units ?
| I would expect to replace the compiler (and/or linker) with 'time original-cmd'. Using plain 'make', I'd say:
make CC="time gcc"
The 'time' program would run the command and report on the time it took. The equivalent mechanism would work with 'cmake'. If you need to capture the command as well as the time, then you... |
5,962,302 | 5,962,373 | How get smallest n, that 2 ^ n >= x for given integer x in O(1)? | How for given unsigned integer x find the smallest n, that 2 ^ n ≥ x in O(1)? in other words I want to find the index of higher set bit in binary format of x (plus 1 if x is not power of 2) in O(1) (not depended on size of integer and size of byte).
| If you have no memory constraints, then you can use a lookup table (one entry for each possible value of x) to achieve O(1) time.
If you want a practical solution, most processors will have some kind of "find highest bit set" opcode. On x86, for instance, it's BSR. Most compilers will have a mechanism to write raw as... |
5,962,358 | 5,962,392 | Definition and Assignment of Pointers to functions at global and local scope | A quick question I hope. I would like to know why the line commented out below causes an error when placed at the global level while it works fine when placed inside the main function?
Many Thanks
#include <iostream>
using namespace std;
bool compare(const int &v1, const int &v2) {
if (v1 < v2) {
return t... | You can't perform assignments except inside functions. You can however perform initialisations:
bool (*pf5)(const int &v1, const int &v2) = compare;
|
5,962,449 | 5,963,260 | assignment in pthreads application | I have a linux multithread application in C++.
In this application in class App offer variable Status:
class App {
...
typedef enum { asStop=0, asStart, asRestart, asWork, asClose } TAppStatus;
TAppStatus Status;
...
}
All threads are often check Status by calling GetStatus() function.
inline TAppStatus App::GetStatu... | There is no portable way to implement synchronized variables in C99 or C++03 and pthread library does not provide one either. You can:
Use C++0x <atomic> header (or C1x <stdatomic.h>). Gcc does support it for C++ if given -std=c++0x or -std=gnu++0x option since version 4.4.
Use the Linux-specific <linux/atomic.h> (thi... |
5,962,470 | 5,964,641 | Is any way to show text line at the top of QTableView exist? | I need something like on the picture below but I can't find a way to do it using Qt 4.3.3...
| I don't think there is a build-in function that does this . The best way to go is to subclass QTableView and override the draw function to draw some text when there are no elements to show .Use the slot
int rowCountChanged(int,int)
to find out when row count is zero.
|
5,962,503 | 5,962,705 | Qt checkbox/toolbutton with custom/distinct check/unchecked icons | I need to have a checkbox like control where the checked and unchecked states use a custom graphic. I've looked at all the docs for QToolButton and QCheckBox, along with QIcon but couldn't find any combination that does what I want.
I just want to use one icon (pixmap actually) in the unchecked state, and a different o... | Use ::indicator sub-item. the code below works excellent for me...
QCheckBox::indicator {
width: 18px;
height: 18px;
}
QCheckBox::indicator:checked
{
image: url(.../Checkbox_checked_normal.png);
}
QCheckBox::indicator:unchecked
{
image: url(.../Checkbox_unchecked_normal.png);
}
QChec... |
5,962,819 | 5,962,895 | Why does the C++ "Hello World" project generated by Visual Studio look a little strange? | I'm new to C++ programming (although I have experience in Java, C#, and Visual Basic). I have used Visual Studio 2010 to create a default "Hello World" example project, but when I investigate the sample code it generates, it looks a little bit different from the code that I see when looking at C++ tutorials.
In my inve... | There's regular, plain-old, ISO-standards-based C++ which is probably the kind you're seeing in tutorials. If you want to write Windows applications in regular C++, you will probably be targeting the Win32 API (or using a set of classes that wrap the basic functionality of the Win32 API, such as MFC).
Then there's C++/... |
5,962,960 | 5,963,040 | How can I cast or convert boost bind to C function pointer? | Suppose I have this:
void func(WCHAR* pythonStatement) {
// Do something with pythonStatement
}
And I need to convert it to void function(void) like this:
bind(func, TEXT("console.write('test')"))
Now I have struct like this:
typedef void (__cdecl * PFUNCPLUGINCMD)();
struct FuncItem {
PFUNCPLUGINCMD pFunc;
//... | I think that you can't, unless you make the resulting lamba_functor a global variable.
In that case, you could declare a function that invokes it:
void uglyWorkaround() {
globalLambdaFunctor();
}
and set pFunc to uglyWorkaround().
EDIT
Just a sidenote: if you are binding static text to the function call, you may c... |
5,963,102 | 5,963,127 | Convert string to all uppercase leters with std::transform | I'm using transform algorithm and std::toupper to achieve this, but can this be done in one line, like this ?
transform(s.begin(), s.end(), ostream_iterator<string>(cout, "\n"),std::toupper);
I get error on this, so do I have to make a unary function for this and call it with transform or I can use some adaptors ?
| Use ostream_iterator<char> instead of ostream_iterator<string>:
transform(s.begin(),s.end(),ostream_iterator<char>(cout,"\n"),std::toupper);
std::transform transforms each character and pass it to the output iterator. That is why the type argument of the output iterator should be char instead of std::string.
By the wa... |
5,963,132 | 5,963,272 | Making a GCC based Project Build and Run under Visual Studio 2010 | I have been trying to port my C++ based mass data transport protocol project into visual studio 2010 with no success :(
The code I have been working on is fully compatible with Win based systems..well this is what my mentor also says :) But I have not been able to make the project build and run using my existing *.h & ... | I would recommend that you parse the data that you need from the working .mak file that you used previously. Create an empty project & sln, then add the contents of the "src" by using "add->existing files" in the file menu.
At that point open up the project configuration settings and go through the C++ and linker setti... |
5,963,176 | 5,963,484 | How to check that LIB import library fully match its DLL? | I have a DLL with its import library. When I try to reference the import library, I get linker errors that some functions can't be resolved. I think that there is a mismatch in versions of the DLL and its import library.
Is there any way to check that an import library fully match its DLL, without checking tons of func... | The problem is that the header file contains functions that are not defined in the .lib file. Most likely you have a new header file and an out of date .lib file.
Possible solutions:
Contact the library vendor to obtain a .lib file that matches the header file and DLL that you are using.
Create the .lib file yourself... |
5,963,305 | 5,972,524 | CUDA statically allocating data on device | I've been trying to allocate a variable that can be accessed by each kernel function.
My attempt is the code attached below, but it won't compile cause the dArray can't be viewed accessed by the kernel. In C++ you would place the variable at the top or declare static to be accessed in every scope through out the progra... | You can have global variables in CUDA, of type __device__ or __constant__. So, for example, if you initialize a __constant__ pointer variable to the address of a device pointer using cudaMemcpyToSymbol(), you can then access that pointer via the __constant__ variable:
__constant__ int* dArrayPtr;
__global__ void Stor... |
5,963,514 | 5,978,189 | JNI - sending class instances to C++ | I want to send a struct-like object from Java to C++. Since there are no structs in java I guess I have to write a class and then send an instance of that class.
public class soundSource {
int posX;
int posY;
.....
}
But... the jObject I get from JNI method in C++ - how do I extract individual fields?
... | Dennis's answer is correct, however, there's another way you can do this, which might give you better performance, and that is via direct byte-buffers.
Here are the docs you need to read:
JNI NIO support,
ByteBuffer
You allocate the direct byte-buffer either on the Java side or the C side. You then populate the buffe... |
5,963,569 | 5,969,900 | Qt Layout / Widget interactions - Layouts within Layouts | I have an interface in Qt 4.7 that I'm having a little difficulty getting to behave as I'd like.
Basic Description of Desired Behaviour: user makes a selection in a combo box, which causes a query to go to another function which returns a QHBoxLayout object that generally includes several labels, line edits, etc. This ... | I've done this kind of thing before, and you definitely have not only remove the widget from the layout but also delete it.
Normally when I do this I create a layout especially for hosting my widget. So that I can just delete everything from inside the layout, and not have to worry about anything else that might be in... |
5,963,706 | 5,964,746 | Storing pointers to const objects in boost::ptr_unordered_map | I can't seem to make boost::ptr_unordered_map<uint32_t, const Foo> work - the underlying implementation looks like it's casting things to a void*.
Do I just have to bite the bullet and make my methods that wrap access to this do a const_cast<Foo*> when inserting items, or is there something I'm missing here? Is there a... | It looks like this isn't possible.
A workaround is to wrap access to ptr_unordered_map. The insert method should take a const auto_ptr and then do a const_cast<Foo*> to insert it.
If you hand back the auto_type to client code when removing elements, you'll need to unpack the pointer from that and transfer it into a con... |
5,963,840 | 5,963,907 | Return the current object (*this) in C++? | I have the following code:
Code 1
class Student {
int no;
char grade[M+1];
public:
Student() {
no = 0;
grade[0] = '\0';
}
void set(int n, const char* g) {
no = n;
strcpy(grade, g);
}
const Student getObject() {
return *this;
}
v... | Although harry.getObject() is a reference to the original object, you then ruin it with the assignment:
harry1 = harry.getObject();
which performs a copy.
Instead:
Student const& harry1 = harry.getObject();
|
5,963,897 | 6,010,161 | Delete raw pointer argument to boost::bind | Lets say I have heap allocated A*, which I want to pass as argument to boost::bind.
boost::bind is saved for later processing in some STL like container of boost::functions's.
I want to ensure A* will be destroyed at destruction of the STL container.
To demostrate:
A* pA = new A();
// some time later
container.push_ba... | The idea of @pmjordan was already going in the right direction. You replied that you can't use shared_ptr, because you can't take ownership back from it once constructed. But that is not entirely correct: with shared_ptr's custom deleter mechanism, you can. This is how:
Assume these toy defintions for your A and f(A*):... |
5,963,917 | 5,964,038 | Odd(?) behaviour of a temporary std::ostringstream | I was messing around with std::ostringstream whilst looking at this question: sprintf in c++?, and noticed the stringbuilder() wrapper by Nawaz and thought, well that ought to work with std::ostringstream.
So my first attempt was the following:
std::cout << (std::ostringstream("select * from foo limit") << max_limit).s... | You need to move the stream's position to the end of the internal buffer used by ostringstream:
std::ostringstream out("select * from foo limit ", std::ios_base::app);
out << max_limit;
std::cout << out.str () << std::endl;
See the documentation on ostringstream constructor.
|
5,963,954 | 5,964,057 | Fast, templated, C++ Octree implementation | I've been searching high and low (mostly on google) for a fast, efficient, templated (ie. with STL-like properties) octree implementation, without success. I want to use this in the context of a 3D scene graph.
Does such a thing exist, or do people generally roll their own? I'm hoping my friends at stackoverflow will... | Check this one out: http://svn.pointclouds.org/pcl/trunk/octree/
Updated link: https://github.com/PointCloudLibrary/pcl/tree/master/octree
|
5,963,970 | 5,964,009 | Suppress "Operation not permitted" error from socket | I have a small utility application that handles sockets, both TCP and UDP. Occasionally, I get the error "Operation not permitted" printed to stderr. My issues is, I handle the errors based on the return codes of the socket functions (and occasionally errno), and don't print anything. Thus, this message must be coming ... | Are you using any library on top of sockets API? The functions used to work with sockets are not supposed to print anything to stderr. I'd suggest using strace and/or ltrace to check where this message originates from in first place.
|
5,963,979 | 5,964,021 | How do i check the data sent to the IP Address on particular port? | I am sending data to the IP address 127.0.0.1 on port number 5152. Through socket programming i am sending the data ("Hello world") . I am receiving a acknowledgement as sent 51 Bytes. But how do i know the data received is correct or not in the above IP address.
I have created a server application , and i am using a s... | You sent your data - now you need to receive it !
You'll need to create a server that listens on port 5152 on the same box and have it display what it receives from your client.
|
5,964,096 | 5,964,219 | Dynamic 2d shadows - Blending issue | Good day my dear community.
I'm working on dynamic shadows for a game I shall work on, but as it usually happens I bring you a problem, in hope (I'm certain actually) that someone will help.
This is where I am right now:
Notice the red square, I want it to gradually fade away as the light source moves out of the sight.... | How about calculating the range to the center of your red square from the light sources center? Normalise that value to a suitable range and adjust the transparency or colour of the red square? Something like this:
double Range(double x1, double y1, double x2, double y2)
{
double xDist = x1-x2;
double yDist = y... |
5,964,228 | 6,243,885 | Boost.Spirit: Lex + Qi error reporting | I am writing a parser for quite complicated config files that make use of indentation etc. I decided to use Lex to break input into tokens as it seems to make life easier. The problem is that I cannot find any examples of using Qi error reporting tools (on_error) with parsers that operate on stream of tokens instead of... | Sorry for the late reply, but it took me some time to prepare a decent example of what you're trying to achieve. I now added a new lexer example to Spirit: conjure_lexer. It is a modified version of the conjure (Qi) example implementing a small programming language. The main difference is that it is using a lexer inste... |
5,964,409 | 5,964,830 | Static linking failed although the name exists | I'm trying to link to a static library, libcovis.a. Everything looks fine but I still have
undefined reference to `CoViG_PublicDemo::MoInS::reset()'
I checked that the name exists in the library
$nm libcovis.a | grep reset
...
_ZN16CoViG_PublicDemo5MoInS5resetEv
...
I'm using linking arguments -L/path/to/libcovis.... | There are two different issues there, the first of which is the simplest, you have used the wrong compiler options. The -L option tells the linker to also look in the directory when looking for a library. The -l tells it to link the specific library. To link you would then use:
g++ -o test test.o -L/path/to -lcovis
... |
5,964,838 | 5,965,134 | Time Consumption of FlushViewOfFile (Windows) and msync(Linux) | We are interested in the time consumption of FlushViewOfFile and msync. Quoting the UnmapViewOfFile documentation:
To minimize the risk of data loss in the event of a power failure or a system crash, applications should explicitly flush modified pages using the FlushViewOfFile function.
Are FlushViewOfFile() and msyn... | They are expensive in the sense that they will move the cached file from memory to disk. Generally you use memory mapped files to avoid doing that! The normal strategy is to flush as infrequently as your program requirements allow.
|
5,964,839 | 5,965,075 | standard dialable number format (c++ tapi) | I want to programatically make calls on a windows mobile device using standard c++ TAPI lineMakeCall function. The phone number (null-terminated) must be in the "standard dialable number format".
There is a function lineTranslateAddress which should make the conversion to the dialable format.
I am testing my applicati... | Here is the MSDN documentation page describing this format: Dialable Addresses
|
5,965,528 | 5,965,581 | Recommend fast C++ UI library with small memory footprint | I want to write an app that reacts for global shortcuts and accepts commands (the way launchy does).
I'm trying to minimize the time between pressing the shortcut and the moment the window appears on the screen and is fully operational.
Can you suggest a good UI library (with some argumentation) that could be helpful?
... | Fast? Small? Windows-only? Sounds like you want WTL.
Caveat: You'll need to use VC++.
Also, I recommend grabbing the source straight out of SVN, as a new release hasn't been packaged in quite some time despite the fact that the project gets updated with some regularity.
|
5,965,909 | 5,966,312 | arm-eabi-addr2line don't show line number | I am running the arm-eabi-addr2line for my Android project, my command is
/Applications/android-sdk-mac_86/android-ndk-r5b/toolchains/arm-eabi-4.4.0/prebuilt/darwin-x86/bin/arm-eabi-addr2line -C -f -e {my so file} {address}
and found that it always only return the function name but don't show line number, e.g,
XXX::X... | Do you have debugging symbols in your .so? You should also disable optimization (-O0) and inline functions (-fno-inline)
|
5,966,042 | 5,966,485 | error LNK2001: unresolved external symbol _IID_IDirectDraw2 | I work with piece of legacy code which uses direct draw and I'm in rather embarrassing situation.
Not long ago I've updated my system and had to adapt to the new situation (loading ddraw.dll) and everything worked fine.
Today I explored another legacy solution which also uses classes (files) I've changed, but I'm stuck... | Did you add dxguid.lib to your project's linker inputs?
|
5,966,434 | 5,966,469 | C++: Having trouble using map with a static variable in a class, I get undefined symbol | This is the error I get
Undefined symbols:
"Config::fmap", referenced from:
register_function(unsigned int (*)(unsigned int))in Config.o
print_config() in shared.o
ld: symbol(s) not found
collect2: ld returned 1 exit status
Config.h
#include <map>
#include <boost/preprocessor/stringize.hpp>
typedef ... | The definition in the .cpp should be:
function_map_t Config::fmap;
|
5,966,594 | 5,966,882 | How can I use #pragma message() so that the message points to the file(lineno)? | In order to add 'todo' items into my code, I want to put a message in the compiler output.
I would like it to look like this:
c:/temp/main.cpp(104): TODO - add code to implement this
in order to make use of the Visual Studio build output functionality to navigate to the respective line by double-clicking it.
But the _... | Here is one that allows you to click on the output pane:
(There are also some other nice tips there)
http://www.highprogrammer.com/alan/windev/visualstudio.html
// Statements like:
// #pragma message(Reminder "Fix this problem!")
// Which will cause messages like:
// C:\Source\Project\main.cpp(47): Reminder: Fix th... |
5,966,698 | 5,966,859 | error: use of deleted function | I've been working on some C++ code that a friend has written and I get the following error that I have never seen before when compiling with gcc4.6:
error: use of deleted function
‘GameFSM_<std::array<C, 2ul> >::hdealt::hdealt()’ is implicitly deleted because the default definition would be ill-formed:
uninitialized n... | The error message clearly says that the default constructor has been deleted implicitly. It even says why: the class contains a non-static, const variable, which would not be initialized by the default ctor.
class X {
const int x;
};
Since X::x is const, it must be initialized -- but a default ctor wouldn't normal... |
5,966,771 | 5,967,129 | MSXML2: How can I get value of a node? | I have this node
MSXML2::IXMLDOMNodePtr node;
node->Getxml() returns "<level3>333<level4 atribute="444"><level5>555<level6>666</level6></level5></level4></level3>"
node->Gettext(); returns "333555666"
node->GetnodeValue() throws exception if node is not an attribute.
How can I get the value 333 ???
| You have to walk the children of the node you have in hand - you can get a list using childNodes after checking the node has children of course, then you can use Gettext() to extract the individual element texts.
It's quite painful to code to the MSXML DOM, in my experience. Glad to see you are using the built-in sm... |
5,967,128 | 5,967,185 | compiling v8 on windows | When I am trying to compile like this
cl /Iinclude hello_world.cpp v8.lib
I get this error
LINK : fatal error LNK1104: cannot open file 'kernel32.lib'
and when I am trying to do it like this
cl /Iinclude v8.lib Winmm.lib WSock32.lib hello_world.cpp ws2_32.lib
I am getting this error
LINK : fatal error LNK1181: c... | The compiler/linker can't find the Windows lib files. There are lots of ways to resolve this. For example, you can add the paths to the locations of the lib files to the LIB environment variable. Or you can pass the /LIBPATH option to the linker.
Finally, it doesn't look like you are compiling V8 here. It would app... |
5,967,181 | 5,967,484 | C++: Using boost lambda to get maximum values in a std::tr1::unordered_map | I have a std::tr1::unordered_map<int, A> map; where A is a class with a member variable (int x).
I would like to find the key i in map such that map[i].x is maximum.
I know that I can write a functor to go with std::max_element. How do I do this instead, using
boost lambda (I am trying to learn it) ? I do not have ... | boost.lambda uses boost.bind to access member variables. It comes up a bit wordy:
typedef std::tr1::unordered_map<int, A> map_t;
map_t m;
A max_a = std::max_element(m.begin(), m.end(),
bind(&A::x, bind(&map_t::value_type::second, _1))
< bind(&A::x, bind(&map_t::value_type::second, _2))
... |
5,967,412 | 5,967,492 | Issue with C++ constructor | EDIT: This question came up and I think I aced it! Go StackOverflow!! :D
I have exams coming up, and one of the questions on last year's exams was to spot the problem with implementation of the following constructor and to write a corrected one.
Rectangle::Rectangle(string col, int len, int br)
{
setColour(col);
... | I don't see anything wrong, though you could make it more efficient by using an initialization list (otherwise your private members of both classes get initialized twice):
Rectangle::Rectangle(string col, int len, int br)
: Polygon(col), length(len), breadth(br)
{
}
Notice that the initialization list can call the c... |
5,967,914 | 5,967,966 | Downcasting a base type | In C++, is it Undefined Behavior if a Base class object is instantiated as a base object, and subsequently downcast to a derived object?
Of course, I would assume it definitely must be undefined behavior, because the Derived class object might have member variables which the base class doesn't. So these variables wo... | Yes, it's still undefined behavior, because you're lying to the compiler about the real type of d.
See the standard 5.2.9/8:
An rvalue of type “pointer to cv1 B”,
where B is a class type, can be
converted to an rvalue of type
“pointer to cv2 D”, where D is a class
derived (clause 10) from B, if a valid
stand... |
5,968,076 | 5,971,032 | Passing parameters to _beginthreadex | I'm attempting to do some basic parallelisation using _beginthreadex, and passing parameters as per an example I was given, but it won't work.
Any ideas?
#include <iostream>
#include <process.h>
void MyThread(void *data)
{
std::cout << "Hello World!";
}
int main()
{
_beginthreadex(NULL, 0, MyThread, NULL... | Your code has two errors in it, neither of which are related to the parameter to the thread function --- NULL is fine for that, as you surmised.
The problems are in the signature of the thread function, and the error you are getting points this out. Firstly, it must be a __stdcall function, and secondly it must return ... |
5,968,117 | 5,968,140 | count specific number of elements | For example, if I have an array of 5 inputted elements, how would I count how many times a specific value was entered if that value has already been established in a variable.
INPUT:
4
4
4
1
2
If click is defined as 4 then how would I count how many times click is used in the array?
Hopefully that makes sense.
Thanks
| This is how you would do it with C style arrays.
int i;
int count = 0;
for(i = 0; i < ARRAYSIZE; ++i)
{
if(array[i] == click)
++count;
}
ARRAYSIZE is the size of your statically allocated array, array your array variable and click the value you are looking for. In count the count of the variable is saved.
|
5,968,202 | 5,968,248 | Syntax checking for Visual Studio 2008 | Is it possible? For instance,
if I type
std::cout << "cool"
without the semicolon
are there any vis studio plugins which will catch that (the way eclipse does) or similar syntactical errors and show me the error visually?
| You can try VisualAssistX, which enables a more sophisticated intellitype system than the standard VC.
|
5,968,273 | 5,968,583 | C++ Template friend odd behavior | I'm seeing something I can't explain in the following code. Under VS6, VS9, and GCC T2::foo2() gives the error: 'bar' : cannot access protected member declared in class 'C1'. But if you remove C1::bar(), it compiles and runs correctly, even though T2 is still accessing the protected C1B:bar(), which you would think w... | In your example, the type of the parameter S in foo2 is C1. The friend relationship exists between T2<S> and T1<S>. Although C1 derives from T1<C1> it does not become a friend of all the friends of T1<C1>.
In the expression pT1->bar, bar is found in C1 and, as the friendship is not passed down to the derived class, i... |
5,968,334 | 5,984,893 | iPhone-Cocos2d-Box2d game #include <list> problem | I have a Cocos 2D game under development which also implements Box 2d and integration required me to change my .m classes to .mm
Now I am trying to use a code that draws Fruit Ninja style swiping effect using the code at https://github.com/hiepnd/CCBlade
When Compiling I get error at the line #include < list >
(CCBlade... | (after reading description in the comments)
the problem is likely that some translation that is not c++ or objc++ is including <list> via inclusion of CCBlade.h
check your build transcript for the failed file: -x objective-c here, the flag -x specifies the language. if it is not c++ or objc++, you'll get the error you... |
5,968,371 | 5,968,465 | creating a new tree from the existing trees as left and right | My code is similar to the one given in this thread.
template<class T>
class BinarySearchTree
{
private:
struct tree_node
{
tree_node* left;
tree_node* right;
T data;
tree_node( const T & thedata, tree_node * l = NULL, tree_node * r = NULL )
: data( thedata ), le... | First of all: your call of the constructor is not correct, it should be like this:
BinarySearchTree<T> newTree(object,tree1,tree2);
I would suggest, to implement a so called copy constructor, a constructor, taking an instance of the same class as argument:
BinarySearchTree(const BinarySearchTree& other)
{
root = o... |
5,968,511 | 5,968,761 | JNI and static interface | Is JNI's "method signature" different if method is defined to return (static) interface ?
In my Java class I have this method:
public SharedPreferences.Editor getSharedPrefsEditor() {
return mActivity.getPreferences(Context.MODE_PRIVATE).edit();
}
SharedPreferences.Editor is a static interface in SharedPreferences... | Nested/Inner classes don't use the standard namespace nomenclature in JNI signatures. The inner class is actually translated to a normal class at the same level as the outer class by the Java compiler with the name "Outer$Inner". I think you want "()Landroid/content/SharedPreferences$Editor;".
|
5,969,008 | 5,969,058 | C++ type qualifier problem | As part of my Computer Software Development degree, one of my labs consists of creating a calculator class template and a fraction class.
The problem is with my fraction class. My task is now to overload the plus operator to allow two fractions to be added together.
Fraction.cpp:
#include "Fraction.h"
const Fraction F... | You need to qualify your accessors as const too:
int GetNum(void) const { return _num; }
BTW, qualifying the return type as const int does not really make sense, it will be an int anyway. Your compiler should emit a warning.
|
5,969,093 | 5,969,220 | Errors while compiling MPI | I am trying to compile a code in C++ using code from : https://stackoverflow.com/questions/5953979/sending-and-receiving-array-using-mpi-part-2.
I use the following command to compile: mpiicpc -o <filename> xxxx.cc -lmpi
After I compile, all my errors seem to refer to the two functions i have defined in my source code... | MPI_Isend() requires a lot more arguments than what you've supplied. Here's your line:
MPI_Isend(C, Rows, MPI_DOUBLE, my_rank+1, MPI_COMM_WORLD);
Where's the tag? Where's the request?
Similarly, your MPI_Waitall() doesn't have any arguments at all! You need the array of requests, the number of requests, and an array o... |
5,969,418 | 5,969,467 | Keep forked process alive if parent/child exits abnormally (C++) | I am trying to execute another command line process in parallel with the current process. However, I realize that the command line program sometimes abnormally exits, and that kills my main program as well.
// MAIN PROGRAM
pid = fork();
char *argv[] = { stuff.. };
if (pid == 0) {
int rc = execv("command line progra... | In your real code do you have an else here:
if (pid == 0) {
int rc = execv("command line program...", argv);
// possibly more child stuff
}
else {
// parent stuff
}
It's always a good idea to post real code when asking questions here.
|
5,969,867 | 5,970,014 | Is this const_cast undefined behavior? | I was wondering whether the following is undefined behavior
// Case 1:
int *p = 0;
int const *q = *const_cast<int const* const*>(&p);
// Case 2: (I think this is the same)
int *p = 0;
int const *const *pp = &p;
int const *q = *pp;
Is this undefined behavior by reading a int* as if it were a int const*? I think it is ... | Qualification-wise, it's fine. With each expression split into a statement:
int *p = 0; // ok
int **addrp = &p; // ok
int const *const *caddrq = addrp; // ok, qualification conv. according to §4.4/4
int const *q = *caddrq; // ok
Note that the rules of const_cast (§5.2.11/3) are identical to those of qualification conv... |
5,969,996 | 5,970,348 | Covariant Return Type With Template Container | Is it possible to make the following work? Basically I want Ptr<B> to be an acceptable return type replacement for Ptr<A>.
template<typename T>
class Ptr {
public:
explicit Ptr (T * ptr) : ptr(ptr) {}
T * ptr;
};
class A {
virtual Ptr<A> foo () {
return Ptr<A>(NULL);
}
};
class B : public A {... | According to the standard:
The return type of an overriding function shall be either identical to the return type of the overridden function or covariant with the classes of the functions. If a function D::f overrides a function B::f, the return types of the functions are covariant if they satisfy the following criteri... |
5,970,087 | 5,970,236 | Understanding Vertex Array Objects (glGenVertexArrays ) | I am confused with the point in generating/creating a Vertex Array Object (VAO) with:
glGenVertexArrays(GLsizei n, GLuint *arrays);
and
glBindVertexArray(GLuint);
Because I can still create a buffer object, say for vertices, and describe that buffer object with glVertexAttribPointer and glEnableVertexAttribArraywitho... | Performance improvements.
In many cases, setting up your attributes on the host require a high number of API calls, and an important amount of validation inside the implementation.
Doing all those once, and using the VAO allow that work to be amortized.
See, for example, Graham Sellers' analysis for actual data.
|
5,970,202 | 5,982,247 | boost::xtime nsec only gives a 1 second resolution on Ubuntu | When I use Boost's boost::xtime_get function to get the current time, the nsec field gives a resolution of only a second. I'm not expecting nanosecond resolution, but why is it this poor? All the Googling I've done seems to imply that I should get a few milliseconds resolution on Linux. I can't seem to find an alter... | boost::xtime_get hasn't been an officially supported part of Boost.Thread since Boost 1.34.1. Boost.Thread was rewritten from scratch in 1.35, and xtime_get only remains for backwards compatibility with pre-1.35 code.
Even in 1.34.1, it was documented as:
This is a temporary solution that will be replaced by a more ro... |
5,970,333 | 5,970,420 | How to determine if a C++ class has a vtable? | A friend of mine sent me the following challenge earlier today:
Given the following code, propose an implementation of OBJECT_HAS_VTABLE so the program prints AnObject has a vtable = 0, AnObjectWithVTable has a vtable = 1.
class AnObject
{
int m_a;
void DoSomething() {}
public:
AnObject() {m_a = 0;}
}... | The standard method is to use std::is_polymorphic from C++11/C++03 TR1/Boost to determine if a class (and its bases) contain any virtual members.
#include <type_traits>
#define OBJECT_HAS_VTABLE(T) (std::is_polymorphic<T>::value)
|
5,970,523 | 5,970,543 | Non-virtual trivial destructor + Inheritance | Given that a class and all its subclasses need no more than the default destructor to release their resources if stored in a variable of the exact type (or pointer to the exact type), can a subclass leak memory if referenced by a base class pointer and then deleted by that pointer?
Example:
#include <memory>
class A {... | "Leak memory"? Why are you talking about leaking memory specifically?
The code you posted produces undefined behavior. Anything can happen in this case: memory leaked, hard drive formatted, program crashed, etc.
P.S. I know that there's a popular urban legend out there that performing polymorphic destruction without a ... |
5,970,845 | 5,974,490 | CMake: how to determine all the .DLL/.SO files that are need for an executable? | Let's assume my program needs several DLL's to work. I should provide that DLLs to the user in my distribution. For now I need QtCore4.DLL, QtGui4.DLL, msvcp90.DLL, msvcr90.DLL, mylib.DLL, Kernel32.DLL...
Would be nice if CMake could get full list of DLLs (or .SO) files. Then I would remove items like "Kernel32.DLL" fr... | You can use Dependency Walker on windows (or the cmd-line dumpbin tool from visual studio). However this is not really a CMake solution and there is not really standard solution with Cmake.
There is, however, the InstallRequiredSystemLibraries module, which you can use to get the system dlls (msvc[r|p]90.dll with msvc ... |
5,970,899 | 5,972,136 | How to forward declare boost::ptree::iterator | I'd like to use boost ptree in my project but since ptree.hpp causes about another 1000 header files to be included this increases compile times drastically (e.g. from 1s to 7s) and as it's needed in over 20 different cpp files this is not acceptable (pre-compiled headers don't improve things much). So I'm thinking of ... | Your problem is a good candidate for the Pimpl idiom, aka compiler firewall, aka Handle-Body. See also this article. The solution you're proposing closely resembles that idiom.
To hide ptree's iterator from your clients, check out the any_iterator technique presented in this article.
You can find implementations of any... |
5,971,003 | 5,971,159 | parsec parser for c++ functions? | is there any open source parser implementation for c++ functions with parsec?
can't find any, dont want to use libClang, becuase installation failes
| No.
Why? C++ is very, very difficult to parse. So while there are pure Haskell parsers for C (e.g Language.C) there is no C++ parser implemented yet, other than the libclang binding which you are already aware of.
References:
haskell/libclang, a C++ parser using clang
haskell/language-c, a C parser in pure Haskell.
... |
5,971,286 | 5,971,778 | How do I use boost.lambda with boost.thread to get the thread's return value? | I'm trying to do something like this:
using namespace boost::lambda;
using boost::thread;
int add(int a, int b) {return a+b;}
int sum, x=2, y=6;
thread adder(var(sum) = add(_1, _2), x, y);
adder.join();
cout << sum;
I get a compile error:
cannot convert parameter 1 from 'boost::arg' to 'int'
| You’re really close actually! The problem is that you’re directly calling add() with Lambda’s placeholders—it’s not being evaluated lazily inside the lambda, but right away.
Here’s a fixed version:
using namespace boost::lambda;
using boost::thread;
int sum, x=2, y=6;
thread adder(var(sum) = _1 + _2, x, y);
adder.joi... |
5,971,371 | 5,972,867 | Help with declaring and using dynamically allocated Array in C++ | I need to declare an array of arrays and so using the code below to accomplish that:
int ** maxc = new int *[proc_num];//memory allocated for elements of rows
for (int i = 0; i < proc_num; i++)
{
maxc[i] = new int[n];//memory allocated for elements of each column.
}
The problem is, the ... | You may have problems with getting the declarations correct, but your real problem is not using standard containers to do the work for you.
This code:
int ** maxc = new int *[proc_num];//memory allocated for elements of rows
for (int i = 0; i < proc_num; i++)
{
maxc[i] = new int*[n];//memory allocated fo... |
5,971,597 | 5,971,609 | Why won't GCC let me use a template parameter for another template's parameter? | I have written the following template function for summing the contents of a std::vector object. It is in a file by itself called sum.cpp.
#include <vector>
template<typename T>
T sum(const std::vector<T>* objs) {
T total;
std::vector<T>::size_type i;
for(i = 0; i < objs->size(); i++) {
total += (*... | typename std::vector<T>::size_type i;
http://womble.decadent.org.uk/c++/template-faq.html#disambiguation
|
5,971,736 | 5,971,755 | c++ inline function? | Why should i do something like this:
inline double square (double x) { return x*x;}
instead of
double square (double x) { return x*x;}
Is there a difference?
| The former (using inline) allows you to put that function in a header file, where it can be included in multiple source files. Using inline makes the identifier in file scope, much like declaring it static. Without using inline, you would get a multiple symbol definition error from the linker.
Of course, this is in add... |
5,971,877 | 5,971,905 | Including a namespace in Visual Studio 2010 C++ | I am looking to use the Aes Class from System.Security.Cryptography.
How do I set up the project so that I can create an Aes object?
Here is the reference: http://msdn.microsoft.com/en-us/library/system.security.cryptography.aes.aspx
Thank you
| That's a .Net class; you cannot use it in native C++.
Instead, use C# or C++/CLI.
Alternatively, use the native CAPI or CNG (Vista or later) interfaces instead in native C++.
|
5,971,979 | 5,971,995 | Converting to const in C++ | C++, OS X, Carbon API.
I need to pass in a const FSSpec to a method FSpOpenDF
I have as follows:
const FSSpec fsSpec = fFileSpec.GetFSSpec();/* is declared as FSSpec GetFSSpec() const; */
err = ::FSpOpenDF(fsSpec, 1, &refNumber);
But I get an error that is:
error: cannot convert 'const FSSpec' to 'const FSSpec*' for ... | Try this:
FSSpec fsSpec = fFileSpec.GetFSSpec();
err = ::FSpOpenDF(&fsSpec, 1, &refNumber);
You seem to understand the need to take the address of an object when calling a function wanting a pointer, as you do it with refNumber; the same merely needs to be done with the fsSpec object since a const FSSpec* is expected.... |
5,972,151 | 5,972,189 | Why does (i|o)fstream take a const char* parameter for a file name? | Why does the constructor and open method of the std::(i|o)fstream classes take the name of a file as a parameter in the form of a const char* instead of an std::string? It seems like the creators of the STL would want to use what they had written instead of using the type they wrote a class to replace.
| Class std::string implements the concept of "run-time-sized resizable string". This is when this class should be used - when you need a string whose size is only known at run-time and which is run-time resizable as well. In situations when you don't need these features using std::string is an overkill. Apparently, the ... |
5,972,223 | 5,972,324 | Mysterious array value after initialization in C++ | For some reason, the value of the first element of the bucket array is being initialized to the size of the array, and growing in size after function calls.
Header file:
#ifndef TABLE
#define TABLE
#include <iostream>
#include <cstdlib>
typedef struct {
double successful , unsuccessful[2] ;
} Perform ;
using nam... | The problem is that you are trying to initialize statically allocated arrays. You need to either use dynamically allocated arrays or declare your statically allocated arrays big enough to hold all the data you will need. Of course, since you are using c++, you should consider using STL vectors.
Here's how you will ne... |
5,972,515 | 5,972,541 | C++ File IO - can't find methods for File IO related stuff | #include "Shader.h"
#include <cstring>
#include <iostream>
#include <cstdlib>
using namespace std;
static char* textFileRead(const char *fileName)
{
char* text;
if (fileName != NULL)
{
FILE *file = fopen(fileName, "rt");
if (file != NULL)
{
fseek(file, 0, SEEK_END... | You're using C file IO in a C++ program.
You included iostream.h, so use it.
http://www.cplusplus.com/reference/iostream/
|
5,972,546 | 5,972,617 | Is std::string part of the STL? | (When I say STL, I'm talking about the template library that revolves around containers, iterators, algorithms and functors.)
This question came to mind after thinking that a std::string mostly behaves like a normal container, with begin and end functions (including iterator), a size function and the possibility to use... | No, not really. And yes, kind of.
There are varying definitions of "the STL", including:
The actual HP/SGI STL, the original library, parts of which the C++ Standard Library was based on. They included containers, iterators and algorithms. Strings were not a part of this.
The parts of the C++ Standard Library that wer... |
5,972,702 | 5,972,890 | ffs does not name a type in C++ | I get compilation error when i try to compile the following..... Please comment.
Here is my code:
ffs.h
#ifndef FFS_H
#define FFS_H
#include <iostream>
#include <string>
#include "commands.h"
class ffs{
private:
Filesystem *filesys;
Superblock block;
... | You can't use ffs as your class name, it already has a meaning in c++ (albiet an obscure one). Just pick a different name.
|
5,972,763 | 5,972,778 | Returning Arrays C++ | I can't seem to understand why this won't work.
Global variable:
int genericSet[] = {1,2,3,4};
int main()...
int* function() {
return &genericSet;
}
Why would it give me an error while trying to return this array? Is it because it's a global variable, if so why would that matter? How would I normally return ... | Your function type doesn't match the return type. Your function is int*, but what you're returning is of type int**.
|
5,972,818 | 5,972,846 | string concatenate question in C++ | I want to concatenate a fileName including path and file names. Then I can open and write it. But I failed to do so.
char * pPath;
pPath = getenv ("MyAPP");
if (pPath!=NULL)
//printf ("The current path is: %s",pPath); // pPath = D:/temp
string str = "test.txt";
char *buf = new char[strlen(str)];
strcpy(buf,str);
ful... | string str = "test.txt";
char *buf = new char[strlen(str)];
strcpy(buf,str);
Should rather be
string str = "test.txt";
char *buf = new char[str.size() + 1];
strcpy(buf,str.c_str());
But after all, you don't even need that. A std::string supports concatenation by operator+= and construction from a char* and exposes a ... |
5,972,931 | 5,972,993 | Costs of using the JNI on android | I'm writing an application (on android) that uses both java code, and native code. Every so often, a sound will need to be played. Unfortunately, the native code doesn't have APIs (or at least stable/official ones) for audio, but only it knows when a sound needs to be played. I thought up two ways to do it:
Have a ... | Please take a look at NDK sample from Tegra Resources.
Android SDK & NDK sample applications and documentation (NV_EVENT, accelerometer, audio, JNI performance, OpenGL ES 2.0 and multitouch)
It includes JNI Audio sample what you want to implement. OpenGL ES 2.0 sample and JNI Performance testcode are also included.... |
5,973,147 | 5,974,379 | Strategies for managing the OpenGL state machine | I'm currently getting to grips with OpenGL. I started out with GLUT but decided to "graduate" to the SFML libraries. SFML actually provides even less GL utilities than GLUT, but is portable and provides some other functionalities. So it's really just me, GL and GLU. Yes, I'm a sucker for punishment.
I wanted to ask abo... |
So it's really just me, GL and GLU
I see nothing bad in that. I'd even get rid of GLU, if possible.
With other settings, I explicitly set
anything that needs setting before
calling glBegin() and take nothing for
granted.
Also this is a good strategy, but of course you should keep expensive state switches to a... |
5,973,159 | 5,973,174 | C++ use `const int` as looping variable? | I want to write code that compiles conditionally and according to the following two cases:
CASE_A:
for(int i = 1; i <= 10; ++i){
// do something...
}
CASE_B: ( == !CASE_A)
{
const int i = 0;
// do something...
}
That is, in case A, I want to have a normal loop over variable i b... | Assuming, you aren't over-simplifying your example, it shouldn't matter. Assuming CASE_A can be evaluated at compile-time, the code:
for( int i = 0; i <= 0; ++i ) {
do_something_with( i );
}
is going to generate the same machine code as:
const int i = 0;
do_something_with( i );
for any decent compiler (with opti... |
5,973,427 | 5,973,485 | error: passing xxx as 'this' argument of xxx discards qualifiers | #include <iostream>
#include <set>
using namespace std;
class StudentT {
public:
int id;
string name;
public:
StudentT(int _id, string _name) : id(_id), name(_name) {
}
int getId() {
return id;
}
string getName() {
return name;
}
};
inline bool operator< (StudentT s1,... | The objects in the std::set are stored as const StudentT. So when you try to call getId() with the const object the compiler detects a problem, mainly you're calling a non-const member function on const object which is not allowed because non-const member functions make NO PROMISE not to modify the object; so the comp... |
5,973,474 | 5,973,503 | SHGetSpecialFolderPath() Not Declared in This Scope | I am not able to compile my program SHGetSpecialFolderPath() not being declared in the scope of the program, while the correct header is being included (according to MSDN)
http://msdn.microsoft.com/en-us/library/bb762204(v=vs.85).aspx
Here are the headers for my project:
#include <iostream>
#include <iostream>
#include... | From the MSDN page:
The Microsoft Internet Explorer 4.0
Desktop Update must be installed for
this function to be available.
With Windows 2000, this function is
superseded by ShGetFolderPath. You can
use this function on earlier systems
by including the redistributable DLL,
ShFolder.dll.
Perhaps this is yo... |
5,973,649 | 5,973,687 | whats wrong with my functions | void getLottoPicks()
{
int i,k, num[7], num1;
bool nodup(int num[7],int k, int num1), noover= true;
for(i=0; i<7; i++)
num[i]=51;
cout << "please enter the seven numbers you think will win the lottery: "<< endl;
for (i=0; i<7;i++)
{
cin >> num[i];
if(num[i] < 1 || num[i... | I think this line is wrong:
if (num[k] = num1)
I think what it should be is:
if (num[k] == num1)
|
5,974,018 | 5,974,157 | Putting a class constructor overload INSIDE another overload of the same class | Hey so i'm working on a stopwatch class using windows GetTickCount() and the STL, but have run into a problem in that when implementing the Stopwatch(int DecNumb) constructor into the overload Stopwatch(int DecNumb, char command[]) the "accuracy" data type is not set correctly in the latter constructor.
(it seems to r... | Stopwatch::Stopwatch(aDecNumb);
This does not call the other constructor; it isn't even valid C++.
You can't call one constructor from another constructor for the same object. Only one constructor is called during the creation of an object (not including base class or member constructors, of course).
You don't really... |
5,974,069 | 5,974,143 | specific problem with custom comparators and templates | I'm sorry for asking so much, but I've encountered another problem I have no idea how to solve... From what I gather, gcc fails to resolve myComparator class type, probably because the following code is not compliant with the standard. The question is if I am missing something or is there a workaround for this problem,... | You've to use typename as:
typename T::myComparator cmp;
//^^^^^^^
typename is required because myComparator is a dependent name.
See this C++ FAQ at stackoverflow itself:
"Where and why do I have to put template and typename on dependent names?"
|
5,974,070 | 5,974,102 | GCC issue with template | I want to use the below garbage collector, but when I would compile I get a lot of error with GCC but not with VSC++, i.e this.
list<GCInfo<T> >::iterator p; ---> Expected ';' after expression
And here is the library.
http://www.devarticles.com/c/a/Cplusplus/A-Simple-Garbage-Collector-for-C-plus-plus/3/
| Assuming T is a template parameter, you need a typename:
typename list<GCInfo<T> >::iterator p;
^^^^^^^^
For more about when and why typename is required, see the Stack Overflow C++ FAQ "Where and why do I have to put template and typename on dependent names?"
|
5,974,090 | 5,974,170 | To build 3d editor with OpenGL and Qt which methods/shell I use? | I want to build simple 3d editor , using OpenGL and Qt.
First what is the correct way to approach such project ? to follow this example :
http://qt.gitorious.org/qt-labs/wolfenqt/
or this is more newer and better way :
http://doc.qt.io/qt-5/examples-widgets-opengl.html
I will use the latest Qt .
Where to start ?
| What you should more care about than which toolkit to use, are the data structures you're going to manage your models with. Also such mundane things like picking are to be considered.
How about you take a look how other 3D modelers do it? The source code of Blender-2.5x is full of beautiful ideas.
|
5,974,176 | 5,974,328 | I got an error: expected constructor, destructor, or type conversion before '&' token when overloading operator= | I wrote things like that:
template <class T>
MyStack<T>::MyStack()
{
STACK_SIZE=20;
STACK_CURRENT=0;
data=new T[STACK_SIZE];
}
template <class T>
MyStack<T>::MyStack(int thesize)
{
STACK_SIZE=thesize;
STACK_CURRENT=0;
data=new T[STACK_SIZE];
}
template <class T>
MyStack<T>::MyStack(const MySta... | Out-class member function definitions should also mention type argument:
template <class T>
MyStack<T>& MyStack<T>::operator=(const MyStack<T>& obj)
// ^^^ you forgot this ^^^ this too!
Just see these demos:
http://www.ideone.com/BEMYn (error)
http://www.ideone.com/f6Qzu (fixed)
|
5,974,468 | 5,974,591 | gcc problem - no matching function call | Can anybody please help me make this work?
Donor-enumerate() doesn't work, gcc gives no matching function error.
template < class T >
struct mesh;
template < class T >
struct meshBone
{
friend struct mesh< T >;
private:
T *_obj;
};
template < class T >
struct mesh
{
template < class U >
void enumerate... | In C++03 you cannot use a local type as a template type argument.
object_replacement is a local type (it is local to mesh<T>::connect(T*, mesh*)) and you try to use it as the template argument U of mesh<T>::enumerate<U>. gcc gives this rather unhelpful error message that there is "no matching function."
The "no local ... |
5,974,728 | 6,110,605 | lineTranslateAddress c++ to managed c# | I have an application that programatically makes calls to different numbers. The application is written in c# (managed) and I use pInvoke for the c++ TAPI functions. Everything works fine except the fact that I need to convert the phone number to a the dialable format.
To do this conversion, I have to use the C++ funct... | I used this code example, and it works
[DllImport("coredll", SetLastError = true)]
extern public static int lineTranslateAddress(
IntPtr hLineApp,
int dwDeviceID,
int dwAPIVersion,
string lpszAddressIn,
int dwCard,
int dwTranslateOptions,
byte[] lpTranslateOutput
);
|
5,974,823 | 5,974,840 | Supposed "syntax error" in my code,"missing ';' before '.'" | I'm relatively new to this level of coding and am really hitting my wall on this error:
[Line 65] error C2143: syntax error : missing ';' before '.'
Obviously this would usually mean a syntax error in my code, but I can't find it flippin anywhere. Any assistance (or a second set of eyes to see my error would be appre... | This:
RacingCar.setSpeed(10);
should be:
setSpeed(10);
which is shorthand for:
this->setSpeed(10);
|
5,975,002 | 5,975,300 | Overloading c++ typecasting (functions) | Using C++ style typecastings (all 4) look exactly like some function template. e.g.
template<typename TO, typename FROM>
TO dynamic_cast (FROM p);
will be used as,
dynamic_cast<Derived*>(p); // p is Base*
Why is it not allowed to overload them by language standard for custom usage ? (like we can overload the keywords... |
Why is it not allowed to overload them by language standard for custom usage?
I suppose that's because the standard committee, when introducing these, thought the semantics of all four of these casts are well defined, and applicable to all types they should be. And mostly, this is true.
The only counter example I kn... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.