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
7,467,240
7,467,391
Appropriate use of global const variables in C++?
I am working on a program for my CS class. It is a simulation of a delivery company's activities at an airport. This is a very simple, small program consisting of a few header and source files and a main.cpp source file that orchestrates the simulation. There are certain given constant values, such as the frequency of...
Regarding the size and purpose of your program (as I understand it from your description) it probably doesn't matter, but since it has an educational context, I'd suggest to "do it right". In such a situation I would go for a Config struct (or class, if you want to make it a bit smarter, see below) which carries the co...
7,467,263
7,467,495
Is methods overriding in C++ always done in a derived class's header?
Sorry for the Noob question .I have been learning C++ for a while and from the book "Visual C++" by Ivor Horton I see that when extending some class the methods overriding is done in the header of the derived class.I haven't found any example where it can be done in .cpp files.So my question is if the .cpp files can o...
You can use .h and .cpp as you wish. You can have both declaration and definition in both .h and .cpp's. Not that you should, but you can. cpp's are compiled by the compiler, if you include your .h in a cpp, it will also be compiled. So to answer your question, yes, you can override in the cpp. Example: A.h class A{ pu...
7,467,340
7,467,473
When to call the update() on widgets?
When does the update() method needs to be called? Do I have to call it at all? All I am doing with my widgets are setGeometry() and raise().
setGeometry() and raise() should automatically cause a paintEvent on the corresponding widgets. I think most of Qt's own widgets call update() where appropriate. On custom widgets you call update() whenever something that is visible changes. For example, if you have your own Label class (that does not inherit from QLab...
7,467,343
7,467,430
Pointer dereferencing overhead vs branching / conditional statements
In heavy loops, such as ones found in game applications, there could be many factors that decide what part of the loop body is executed (for example, a character object will be updated differently depending on its current state) and so instead of doing: void my_loop_function(int dt) { if (conditionX && conditionY) ...
The function pointer approach let's you make the transitions asynchronous. Rather than just passing dt to the updater, pass the object as well. Now the updater can itself be responsible for the state transitions. This localizes the state transition logic instead of globalizing it in one big ugly if ... else if ... else...
7,467,918
7,469,671
Opensource dll injector
I have developed a tool that changes the appearance of certain programs. To do it I need to inject a dll in some processes. For now I use basically this approach. The problem is often people cannot inject the dll because they don't run the target process as an admin or other things I don't understand (someone couldn't ...
The method is quite common and reliable. Just try adding HANDLE hToken; LUID sedebugnameValue; TOKEN_PRIVILEGES tkp; if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken)) puts("Failed to Enable Debug Options!"); if (!LookupPrivilegeValue(NULL, SE_DEBUG_NAME, &sedebugnameVal...
7,467,931
7,467,953
warning: extra tokens at end of #endif directive
I am compiling a quite a big project using VxWorks6.8 C++ compiler. I am getting following warning warning: extra tokens at end of #endif directive #ifndef _OM_NO_IOSTREAM #ifdef WIN32 #ifndef USE_IOSTREAM #define USE_IOSTREAM #endif USE_IOSTREAM #endif WIN32 I am getting a quite a lot of these warnings. Why i am g...
should be: #endif // USE_IOSTREAM #endif // WIN32 endif doesn't take any arguments. Such comments are placed only for readability EDIT: and you miss closing #endif // _OM_NO_IOSTREAM at the end
7,468,151
7,468,166
Assigning pointer to uninitialized variable changes it value?
I'm playing with c++ in VisualStudio2010 Please explain why IT happens: int a, b; int *p, *q; cout << a << " " << b; prints out "0 0". Well it's understandable, uninitialized integer should be 0; but int a, b; int *p, *q; p = &a; cout << a << " " << b; output is "1792816880 0" So if I assign pointer to uninitialized ...
Well it's understandable, uninitialized integer should be 0 No. There is no guarantee of that, it depends on the storage class, If your int is local variable it has a auto storage and it need not be 0. Accessing Unitialized variables causes Undefined Behavior and Your code is causing an Undefined Behavior. Once the...
7,468,167
7,468,231
Preserving specified primitive size
If I have a class as follows: class MyData { public: MyData( const AnotherObject& obj ); int getA() { return A; } int getB() { return B; } private: int A : 16; int B : 16; } Will the fact that I have specified the variables A and B to take up only 16 bits be rendered pointless by the getters? If ...
The getters will convert the 16 bit value to the size of the int on the system value and will return 32-bit copies (if the size is 32 bits). What is it that you're trying to achieve? Why not use int16_t from <cstdint>?
7,468,286
7,468,325
warning: deprecated conversion from string constant to 'char*''
Possible Duplicate: How to get rid of deprecated conversion from string constant to ‘char*’ warnings in GCC? I use following function from library which i cannot change: HRESULT DynamicTag(char * pDesc, int * const pTag ); I use it as follows. I have created the object of the class provided by the library that imp...
Dealing with unknown library When passing literals and not other const string, and you are not sure if the library is modifiying the string, is easy to create a stack allocated temporary copy of the literal in C++ (inspired by How to get rid of `deprecated conversion from string constant to ‘char*’` warnings in GCC?): ...
7,468,395
7,468,599
gluLookAt() makes blank screen
I don't have much OpenGL experience. I am trying to draw a teapot and move a camera around the teapot. To this end I am using the gluLookAt function. The problem is that when I call gluLookAt the screen is blank and I can't see my teapot. #include "openGLer.h" void openGLer::simulate(grid* toSim, int* argc, char** arg...
Have you set up your projection matrix correctly? Otherwise, your call to gluLookAt will cause the teapot to be too far away and therefore be clipped by the far plane. Try adding this to your initialization code (and also your resize handler to fix the aspect ratio when the window is resized). I've set the far plane at...
7,469,009
7,471,835
Can I specify which HID my C++ program listens to
I am trying to create an application that reads keyboard input from a HID. The OS I am trying to acheive this on is Windows 7. In what way would I specify to my program that it needs to listen to just one HID device (I have a normal keyboard, and an RFID reader as my two devices) Could some one tell me the best route t...
Did you register for HID input with RegisterRawInputDevices() ? Because in that case, you tell Windows for which devices you want "raw" input. [edit] Rough sketch: int count = 0; GetRawInputDeviceList(0, &count, sizeof(RAWINPUTDEVICE); std::vector<RAWINPUTDEVICE> devs(count); GetRawInputDeviceList(&devs[0], &count, si...
7,469,100
7,471,570
Qt mouse leave event while button is pressed
I need to detect if the mouse pointer leaves my custom widget even if a mouse button is pressed. According to this post, Qt does not cause a leaveEvent in case a button is pressed, at least not in version 4.4. I am working with 4.7.3, but still do not get a leaveEvent in the described case. I also tried with the variou...
Well, I did something similar to @gregseth. Write your own MouseLeaveEvent that is invoked from MouseMoveEvent when the mouse's position is outside of the widget's boundary. As Qt's documentation says "Mouse move events will occur only when a mouse button is pressed down"
7,469,116
7,474,641
Writing a wrapper class for an ActiveX control
I am given a video calling software which implements an activex control to render the video in a web browser. As activex works only in IE i am given the task of implementing a cross-browser version of the activex control using FireBreath framework. I need to write a wrapper class for the activeX control. I am new to ac...
The closest I know of is this: https://github.com/firebreath/FBAXExample It's an example of hosting an activex control inside a FireBreath plugin. You'd be better off (and a lot cleaner) if you can do a complete port, but it may be possible to do it with just a wrapper; you may also want to look at the WebView library ...
7,469,273
7,469,602
how to resolve errors with the use of va_list?
I have implemented Ruby C extension(i.e. Invoking C function from ruby script) Following is the variable argument function implemented in C from file "cImplementation.c" #include<stdio.h> static VALUE cFunction(VALUE self, VALUE exp, const char* fmt, ...) { //1st Trial to get expected output char buff[256]; ...
You should use rb_scan_args to get the function arguments. They can't be passed directly to vsnprintf. Maybe try following the example here: http://www.eqqon.com/index.php/Ruby_C_Extension_API_Documentation_(Ruby_1.8)
7,469,279
7,469,370
What does the C++ standard say about the difference between casting from type a to type b, and instantiating/Constructing type b?
Possible Duplicate: What is the difference between (type)value and type(value)? If you have a function that takes an argument of type b, but at the call site you only have a variable of type a. Is there a difference between casting the function parameter from a to b, and constructing type b. The specific example I ...
Writing a C-style cast (T)x, where x is of type U, more or less tries the following in order: If T and U are of class type, look for a conversion operator U::operator T() const or a one-argument constructor T::T(U). If T and U are primitive types, apply the standard value conversions (int to double, etc.). reinterpret...
7,469,296
7,469,508
Is there any built-in function that convert wstring or wchar_t* to UTF-8 in Linux?
I want to convert wstring to UTF-8 Encoding, but I want to use built-in functions of Linux. Is there any built-in function that convert wstring or wchar_t* to UTF-8 in Linux with simple invokation? Example: wstring str = L"file_name.txt"; wstring mode = "a"; fopen([FUNCTION](str), [FUNCTION](mode)); // Simple invoke. c...
The C++ language standard has no notion of explicit encodings. It only contains an opaque notion of a "system encoding", for which wchar_t is a "sufficiently large" type. To convert from the opaque system encoding to an explicit external encoding, you must use an external library. The library of choice would be iconv()...
7,469,468
7,469,608
defaulted default constructor ? in n3290 draft
A point from n3290 draft §12.1 (Constructors) ¶5: An implicitly-declared default constructor is an inline public member of its class. A defaulted default constructor for class X is defined as deleted if: X is a union-like class that has a variant member with a non-trivial default constructor, any non-static d...
I think this excerpt from Wikipedia explains this: Explicitly-defaulted and deleted special member functions In C++03, the compiler provides, for classes that do not provide for themselves, a default constructor, a copy constructor, a copy assignment operator (operator=), and a destructor. The programmer can overrid...
7,469,563
7,469,584
Getting type names at compile time in C++
I want to get the type name and print it for debug purposes. I use the following code: #include <cxxabi.h> inline const char* demangle(const char *s) { abi::__cxa_demangle(s, 0, 0, NULL); } template<typename T> inline const char* type_name() { return demangle(typeid(T).name()); } It works well, but it I supp...
I can't see typeid(T).name() incurring a runtime overhead. typeid(expr) yes, if expr is of a polymorphic type. It looks like the demangling probably happens at runtime, but there's not an awful lot you can do about that. If this is only for debugging then I really wouldn't worry about it too much unless your profiler i...
7,469,606
7,503,670
Type for large currency values in C++
What type should i use in C++ to store large currecy values like 5231451.3245114414? It should allow to store 10 or even more decimal digits.
Thanks you all for your answers. I found the most appropriate solution myself. It's just one file that does everything i need - C++ wrapper class for the OLE Automation type DECIMAL. It's really light (no additional heavy libraries or files) and powerfull and can handle REALLY BIG numbers.
7,469,858
7,469,904
Is there a way to change a member of a const struct?
I want to change a member of a const function argument. imagine this snippet from a texture class I am working on: template<> void mySuperTexture::loadPixels<float>(uint32 _width, uint32 _height, float * _pixels, const Settings & _settings) { if (_settings.pixelDataType == PixelDataType::Auto) { _settings.pi...
You have two options: Do a const_cast <> () Mark the member as mutable But, as you want to update const-y and non-consty things, I guess you want to overload the function with a non-const version: template<> void mySuperTexture::loadPixels<float>(uint32 _width, uint32 _height, float * _pixels, Settings & _settings) ...
7,469,940
7,955,672
STLPort, Intel compilers, build errors (though app runs fine!)
Compiling my project against STLPort I get some weird build errors. Weird, because the project runs just fine (and 20-30% faster) though you'd think the build errors would be fatal. Can anyone enlighten me as to what I'm doing wrong and how to shut these up? Linking... (Intel C++ Environment) ipo: error #11017: Cannot...
IPO is inter procedural optimization complaining that it can't open libraries which weren't compiled in the current build. These errors aren't fatal; the output still gets built but IPO obviously doesn't optimize the libraries it can't optimize.
7,470,169
7,470,231
How to set core file name using c++ code?
How can I set the core file name using c++ code in linux ? Linux dump core file on binary crash , is it possible to set core dump file name ?
On my system (Ubuntu 10.04 with kernel 2.6.32), man core gives no indication that the naming can be chosen on a process-by-process basis. In can, however, be changed system-wide by modifying /proc/sys/kernel/core_pattern: By default, a core dump file is named core, but the /proc/sys/kernel/core_pattern file (since...
7,470,244
7,470,305
command prompt tutorials on linux
I have a program I am trying to port to linux. The program is a command prompt program that displays memory on screen, you can move around the memory using the arrow keys. Im new to linux and don't really understand how the terminal works. What Im looking for is some good tutorials or a chapter in a book to teach me ...
I suggest you need ncurses
7,470,273
7,470,322
C/C++ pointer tricks (saving pointer to int, and translating back)
As title says, I'm currently doing some small hacks with pointers in C++, but something isn't working out here's what I got: uintptr_t texture_pointer = (int)((void*) &texture); Where texture is a class; this seems to work fine, as I'm getting a pointer value out, and I have insured that I'm getting the same value int...
This line: Texture texture = *(Texture*)((void*) texture_pointer); creates a new Texture object as a copy of the original one. Obviously, this has a different address to the old one. You could do this: Texture &texture = *(Texture*)((void*) texture_pointer); (i.e. create a reference to the old one). But in general, ...
7,470,310
7,471,341
Generating Mini Text Dump LInux
Following question describe for windows How to create minidump for my process when it crashes? But how can I create mini crash text dump on linux ?
You need to write a signal handler. Here is a slide deck on how to do it: http://www.scribd.com/doc/3726406/Crash-N-Burn-Writing-Linux-application-fault-handlers Here is the code form the slide deck: https://github.com/gby/libcrash
7,470,311
7,470,373
Why is variable capturing in lambdas so complex?
I was wondering about the new C++11 lambda functionality, a wonderful addition in my humble opinion, but I really don't get the whole variable capturing part. In short my question comes down to "why did the committee decide for this and did not just use [&] functionality (possibly with a keyword then)?" At first I thou...
You need by-reference for efficiency. You need by-value to allow the function object to leave the scope of the local variable which it captures. std::function<void()> get_foo (const std::string & bar) { return [=] () {something with bar;} }
7,470,346
7,474,049
How to use STLPort in my kernel?
I am developing a kernel in C++. But I do not want to write a stdlib; for that purpose I have downloaded STLport http://www.stlport.org/, but I don't know how to install and use it. I am using Linux for building my kernel. How can I use c++ standard libs in my kernel? And I do not want to port all libs from STLport. Ho...
In order for STL to work you have to port several things like static initialization (for i.e. std::cin and std::cout) and stack unwinding... you'd have to port i.e.: libsupc++ and have that in your kernel. Basically all this stuff shouldn't be in the Kernel in the first place. DON'T use Vectors use static arrays becau...
7,470,472
7,516,917
lost messages on zeromq pub sub
I'm trying to implement the pub sub design pattern using zeromq framework. The idea is to launch a subscriber and afterwards to launch the publisher. The subscriber will listen to 100 messages and the publisher will publish 100 messages. So far so good... However what actually happens is that even that the subscriber i...
See http://zguide.zeromq.org/page:all#Missing-Message-Problem-Solver and search for "slow joiner" on that webpage. Basically, it takes a little time (a few milliseconds) for the connection to be set up, and in that time lots of messages can be lost. The publisher needs to sleep a little before starting to publish, or (...
7,470,612
7,471,042
gcroot Collection - element access
I'm making bridge from .NET to C++ and using Collection as a public element like this : gcroot<System::Collections::ObjectModel::Collection<BModel::Device ^> ^> Devices; I'm using gcroot because my c++ class is not managed (it's MFC) but I'm having trouble with accessing it. When I am doing : Devices[x]->devicename ...
While the member access operator, -> is overloaded, it appears as if the subscript operator [] isn't, unwrap your gcroot first. using namespace System::Collections::ObjectModel; Collection<BModel::Device ^> ^d = Devices; d[0] //... this should work The above represents an implicit cast (this is why you cannot use auto...
7,470,913
7,470,986
Why is gcc destroying my object instantly despite its scope? (and how do I make it not do that?)
I wrote a small profiling class with an accompanying guard class to use like this: { ProfileGuard pg("SampleName"); // Code to profile ... } But then I noticed that sometimes gcc optimizes the code so that pg is destructed instantly. Apparently it detects that pg and the other code will not influence each...
Apparently it detects that pg and the other code will not influence eachother. How, since that’s patently untrue? They do influence each other (e.g. through output order). GCC doesn’t do this. Perhaps you accidentally used an anonymous (and hence temporary) object? ProfileGuard("SampleName"); Now, this will be destr...
7,471,005
7,471,220
How to set precision for adDecimal parameter to avoid "invalid precision" error?
I have a table on my MSSQL server with a column defined as decimal(8,2). From my c++ app I define the following parameter to be passed to the sp. pParam1 = pCommand->CreateParameter ( _bstr_t ("Thing"), adDecimal, adParamInput, 8, (_variant_t) thing); pCommand->Parameters->Append (pParam1);...
The default is (18,0). In VBScript it would be: pParam1.Precision = 8 pParam1.NumericScale = 2 For C++ it is amazingly similar: pParam1->Precision = 8; pParam1->NumericScale = 2;
7,471,023
8,123,463
Serializing to a binary archive using boost. Input Stream Error
I try to serialize to a binary archive then load this archive using the code show below. The issue I have is that when loading the file, I get an "input stream error". #include "project.h" // Std #include <fstream> // Boost #include <boost/archive/binary_oarchive.hpp> #include <boost/archive/b...
I had the same problem, when i added the binary flag to the fstream ctors everything worked.
7,471,045
7,471,963
Setting the Height of a QPlainTextEdit Delegate in a QTableView
I'm working here on a project and currently I'm stuck on the following problem. It is about a QTableView which has a column called "Description", the cells of this column contain a QPlainTextEditDelegate. I'm failing on setting the Height of the QPlainTextEdit everytime it is entered. Right now it behaves like a QLineE...
You should reimplement QAbstractItemDelegate::sizeHint method to return expected height when you create your editor. I don't think that it's necesary to emit QAbstractItemDelegate::sizeHintChanged signal after creating editor, but documentation doesn't say anything. If it doesn't work without it, you should emit sizeHi...
7,471,157
7,471,553
Qt model/view using model item : is specific view item required?
I'm about to implement something similar to : http://doc.qt.nokia.com/latest/itemviews-simpletreemodel.html I have a type, aosl::Object, that contains all the data of a node in a tree of Objects. I want to display some informations in a QTreeView. So it seems I need to implement a class inheriting from QAbstractItemMod...
QAbstractItemModel's external interface is operating soley on QModelIndex and QVariant - no internal structure is exposed to view class. As long as your class (aosl::Object) can provide all information required in implementation of your QAbstractItemModel decenant you don't need to wrap it into QObject, or anyhow else....
7,471,206
7,471,424
Negate boost is_directory in std algorithm
boost::filesystem::recursive_directory_iterator end, begin(directory); auto num_of_files=std::count_if(begin, end, std::not1(boost::filesystem::is_directory))); I am trying to negate the function is_directory on the above directory iterator but am hitting a brick wall. I have tried specifying the template f...
std::not1 needs a function object as its argument. This function object can be obtained with std::ptr_fun, so this should work: auto num_of_files=std::count_if(begin, end, std::not1(std::ptr_fun((bool(*)(const boost::filesystem::path&))boost::filesystem::is_directory))); (the number of parentheses is probably...
7,471,227
7,471,296
C++ Container performance question
What would have better performance, a stl vector, or a dynamic array that's just realloc'd everytime I want to add something to it? Would using vectors::iterator be faster then using a for loop on an array? And if someone could explain why, that would be great.
What would have better performance, a stl vector, or a dynamic array that's just realloc'd everytime I want to add something to it? Stl vectors have insertion in amortized constant time (because reallocation is not done all the time and reservations occur by factor 1.5 (minimum)). Therefore according to your descript...
7,471,287
7,471,365
What is a DLL.a file and how do I load one into my VC++ project
I have recently stumbled upon an open source project that I would like to take part in, but I've noticed that they have DLL.a files. I've never seen this file type before and as a programmer for a decent 5 years I've learned not to assume something that I don't understand. Any advice would be greatly appreciated.
These are archive files, which are static libraries intended for use on a Linux system. They won't work with Visual Studio, you'll need to find the Windows libraries (if they exist).
7,471,339
7,471,384
boolean type manipulation
this code #include <iostream> using namespace std; int main(){ bool t=false; cout<<t &&(!t)<<endl; return 0; } shows me error like this invalid operands of types 'bool' and '' to binary 'operator<<' What is wrong? I can't understand this, please explain it to me. I think that && and ! is defined in c++. S...
"invalid operands of types 'bool' and '' to binary 'operator<<'" This means that the second << operator is trying to execute on (!t) and 'endl'. << has a higher precedence than && so your cout statement executes like this: (cout << t ) && ( (!t) << endl ); Add parenthesis to fix this: cout << (t && (!t) ) << endl ;...
7,471,540
7,472,121
Are there any cpp functions or objects (excluding inherited from c) that are not thread safe even when each thread operates on its own data?
Sorry for the long title, but I think it explains well what I'm interested in. For example C function strtok is not thread safe in worst possible way :) , it uses a global state. So even if it is called on different data it is not thread safe. So my question is are there functions in "C++ minus C" that have same prob...
Thread safety is only really covered by C++11; C++03 didn't specify multi-threaded behavior. In C++11, the relevant bits are 1.10/8 "Certain library calls synchronize with other library calls performed by another thread. For example, an atomic store-release synchronizes with a load-acquire that takes its value from the...
7,471,615
7,471,672
What would cause a C++ .exe and .dll to only work on the machine it was built on?
I am using VS2010 and am working with this project. http://www.codeproject.com/KB/audio-video/Asio_Net.aspx Initially, I downloaded the demo binary and it would crash on my machine. After reading through some of the comments, it said to download the source, build it, (after getting the ASIO SDK), and it should work on ...
Assuming you mean that you've included this dll - Bluewave.Interop.Asio.dll then there only a couple of explanations I can think of: One of it's dependencies is missing from the machine. You can use something like Dependency Walker to find out what's missing. The dll is not in a location the exe can see (unlikely but ...
7,472,002
7,472,076
What is the use of declaring a function which takes and return "ostream&" rather than overloading operator<<?
I've come across functions that, rather than overloading the operator << to use with cout, declare a function that takes an ostream and returns an ostream Example: #include <iostream> class A { private: int number; public: A(int n) : number(n) {} ~A() {} std::ostream& print(std::ostream& os) const; friend st...
It would make a lot more sense if operator<<() actually looked like std::ostream& operator<<(std::ostream& os, const A a) { return a.print(os); } Then operator<<() wouldn't need to be a friend.
7,472,181
7,472,584
c++ loop through registry recursively is slow
Have an annoying problem with my code, probably I am doing something wrong because my Python implementation is much faster! C++ implementation problems: Iterating over "HKEY_CLASSES_ROOT" takes a lot of ram, I assume it's because c++ implementation uses lots of variables. Fixed It's also slow, much slower than python ...
There is leak of resource in your code. You open hkey but you close hKey (note the difference in case of k and K). On a side note, you store the opened registry key into hkey itself. And it happens that hkey is the passed in parameter, shared among all calls to RecurseOpenRegEx. That is why "somehow i need to reassign ...
7,472,245
7,479,043
do I need to define an PyMODINIT_FUNC for Boost.Python to expose a C++ class?
I have libboost installed via Ubuntu. The boost version is 1.42. I've followed the example on the Boost website: #include <string> struct World { void set(std::string msg) { this->msg = msg; } std::string greet() { return msg; } std::string msg; }; then created the idl: #include <boost/python.hpp> using n...
ok, I found out why this wasn't working. My C++ class was in one file, and my IDL was in another. Because it didn't look like python OR C++ to me, I thought it belonged in separate file. So the IDL stuff was never getting picked up. Once I put it all together in World.cpp, everything worked as expected! Very smoothly, ...
7,472,731
7,472,858
What do you do when your application starts to run out of memory?
I have a C++ graphics app that does heavy computations on models. There is a leak or two which I've traced to CG and/or my ATI graphics card (I'm 100% SURE!!). The machine I have has 16 GB ram, and when I've used 4.49 GB RAM (TOTAL system usage, with app only using ~1.9GB), vector.resize() starts returning 0 new elem...
(Windows Assumed) A 32-bit Windows application is limited to about 2.0 GB of user-mode memory (or 3.0 GB if certain boot-time parameters are set). When your application used up 1.9 GB of memory, the well ran dry. Reference: http://msdn.microsoft.com/en-us/library/windows/desktop/aa366778(v=vs.85).aspx#memory_limits
7,472,976
7,473,143
c++: Is there something like "boost/std typetraits conditional" that generates a value (not a type) at compile time?
I am currently doing the following to generate a value at compile time, which works: //if B is true, m_value = TRUEVAL, else FALSEVAL, T is the value type template<bool B, class T, T TRUEVAL, T FALSEVAL> struct ConditionalValue { typedef T Type; Type m_value; ...
I think it's the simple answer: Because the operator ?: can select values quite well. Types are harder to select, that's why boost constructs exist for that. For pathological cases, the boost::mpl magic Luc suggested is fine, but it should be quite rare.
7,473,079
7,473,823
How to raise StopIteration from swig C++ code?
I'm trying to extend a C++ library by implementing the python iteration protocol on a class. The problem is that trying to raise a StopIteration exception from the next() method makes the program SegFault. The method I've used for raising the exception from the C++ code (in python.i) is the one described here: http://w...
So the right answer seems to be that the next() method must return a PyObject* and also use SetNone. So it would look like this: PyObject* next(PyObject* self) { if (i < n) { \\ go on iterating } else { PyErr_SetNone(PyExc_StopIteration); return NULL; } } Thanks to aix for the link!
7,473,106
7,473,176
C++ Type changes during derived class construction - virtual function question
C++ type change during deletion I've read that when you construct a derived type, the type changes depending on which constructor is being called. So, if you create a derived object and call a virtual function using a base pointer, normally it would map to the implementation in the derived class. If you called the vi...
To keep it short and simple, you can have a Rule: The virtual mechanism is disabled in Constructors and Destructors A virtual function call in Base class will always call the base class version of the function, the same in derived class results in call to the Derived class version of the function. First of all, is th...
7,473,202
7,473,904
Dynamic code execution on WinRT in Windows 8 (either C++ or .NET/C#)?
Does WinRT under windows 8 metro allow you to dynamically load and execute code? For example, is it possible to download a dll into memory or to isolated storage and run code from it? Could code that JIT compiles a scripting language to native assembly language (e.g. third party browsers) be able to do the same in WinR...
You question is a bit unclear... so some general pointers: .NET app using among other things WinRT (but NOT the new UI model!) In this case everything is possible that you today (perhaps not OLEDB) but Reflection etc. .NET app built for Metro UI AFAIK this is not possible (see http://blogs.microsoft.co.il/blogs/sasha/...
7,473,226
7,473,471
c++ win32 change trackbar background color
I have a win32 API, developed in c++ and i can't find any useful information regarding how can i change the background color of a Trackbar component in windows Vista and above? I am looking for a equivalent to .NET attribute called BackColor.
Winforms implements it by handling WM_CTLCOLORSTATIC for a TrackBar control. The example code in the linked SDK article should do the trick.
7,473,434
7,473,662
random shuffle operation
i have following code #include <iostream> #include <cstdlib> using namespace std; int main() { int a[] = {2, 1, 4, 3, 5, 6, 7, 9, 8, 10, 11}; int n = sizeof(a) / sizeof(int); int k=0; for (int i = 0; i < n; i++) { k = i + rand() % (n-1-i); int s = a[i]; a[i] = a[k]; ...
n = 11. When i = 10, that's a k= i+rand() % 0; Mod by zero is undefined and can operate a number of different ways. I've seen it equivalent to mod infinity, so it would be returning k as i+rand() which would lead to your out-of-bounds error.
7,473,522
7,473,653
Question about the overloaded operator <<
Trying to study C++ function templates. As a part of which I have this code below. It works fine, but I have questions as below :- 1] Why is the operator << overloading function need to be friend ? If I remove the keyword friend it gives compilation error saying : operator << has too many parameters. 2] Why does the o...
Why is the operator << overloading function need to be friend ? If I remove the keyword friend it gives compilation error saying : operator << has too many parameters. << alters the stream’s state, and hence ideally it should be implemented as member of it's left operand’s type. However, its left operands are stream...
7,473,596
7,474,474
Going down from C++ to C: alternative to std::map?
I am looking for minimalistic alternative for std::map<long, int>, which would go into Windows kernel driver, so it should be quite fast.. it is expected to hold a relatively small (~200 in working set) amount of keys and a large amount of inserts. Looking for solution that can cut key search cost.
Already done for you. See the RtlXxxGenericTable and RtlXxxGenericTableAvl calls. RtlInitializeElementGenericTable RtlDeleteElementGenericTable RtlEnumerateGenericTable RtlEnumerateGenericTableWithoutSplaying RtlGetElementGenericTable RtlInsertElementGenericTable RtlLookupElementGenericTable RtlNumberGenericTableEleme...
7,473,924
7,474,675
How to return two or more tables from lua function?
I would be really appreciative if someone explain me how lua-C stack works when lua function called from C returns two tables or table which has nested table inside when I am trying to do it it seems to look fine but only at first glimpse: if ( lua_istable(L, -1) ) printf("its OK\n"); if ( lua_istable(L, -...
Note that when lua_next returns 0 is has popped the key, and pushed nothing, so at the end of the while loop you have your two tables on the stack. The lua_pop after your while loop is popping the top table off the stack. The subsequent for loop is starting at index -2 which is past the table, and could contain anythi...
7,473,978
7,474,173
libusb not visible in IDE
I m using Code blocks in Ubuntu Linux. I would like to write programs with the library libusb. I have this file in the system, but the complier in the IDE cannot find this file. I add in "build options" this file, it's not help. What is the solution to this problem? #include <libusb.h> Update: dpkg -L libusb-dev shows...
Seems like libusb-dev is missing. Or Execute dpkg -L libusb-dev to list all the files in libusb-dev package to find out what is appropriate include file name and it's location. Most likely you will end up changing your include to: #include <usb.h> Also, it is not enough just to add a header to the program - you need ...
7,474,341
7,474,403
c++ win32 where to draw a meter
I need to draw a meter using simple rectangles in a win32 app using c++. What would be the best method to draw a meter in a window (it should be redrawn, every 10ms)? Should i draw it directly into the window (on message WM_PAINT) or use some other component and draw into that?
Create a timer and respond to the WM_TIMER message by invalidating the part of the window that contains the meter using InvalidateRect. This will automatically generate WM_PAINT messages, but will keep them from piling up if the program falls behind.
7,474,504
7,474,665
Compiling a Win32 GUI app (without a console) using MinGW and Eclipse
I'm using the eclipse IDE with MinGW as my compiler, to make a Win32 GUI app. I want to get rid of the console, but compiling the program with -mwindows option has no effect and the console is still there. Using the -Wl,--subsystem,windows flag also produces no effect. What am I doing wrong ?
For gcc on Windows, two things should be considered to build a non-console Windows app: Compiler option -mwindows Have WinMain() It is possible, however, to manually specify -Wl,-subsystem,windows to the linker and include gdi32 and comdlg32 into the build. This is exactly what -mwindows automates. Reference.
7,474,557
7,474,619
glutGetWindow - Expression must have class type
Good Afternoon, So I'm working with C++ (Visual Studios C++ 2010 to be exact) and am working on a seemingly easy task; Draw a picture onto the middle of the window. If you readjust the window size, the picture/bitmap will be redrawn into the middle of the newly sized window. I figure to get the middle of the window, I ...
glutGetWindow doesn't return object of any class type. It's signature is this: int glutGetWindow(void); And you need is this (see doc): int glutGet(GLenum eWhat); Example, int width = glutGet(GLUT_WINDOW_WIDTH); //Width in pixels of the current window. int height = glutGet(GLUT_WINDOW_HEIGHT); //Height in pixels of t...
7,474,646
7,495,045
Boost Log linkage error on VS2010
I am trying to build and run the Boost.Log library on VS2010. I took the latest files from the trunk in their SVN. I dragged all header and source files into a win32 .exe project, setup all of boost's (1.47) include\lib directories. After playing for a while with the .mc file I managed to generate header and .rc files ...
Boost.Log is a compiled library; it needs to be built. You can build it with bjam the same way the rest of boost is built. The file name being searched for is a result it boost's auto linking. Check out for various options.
7,474,728
7,474,863
QTimer basic program help
I'm trying to create a simple game that uses a timer but I can't seem to get it working. It throws this error: "no matching function for call to 'QObject::connect(QTimer*&, const char*, Time*&, const char*)'" now matter what I do do I can't fix it please help. I have only just started coding the game when I ran into th...
Your implementation of Time does not declare it to be a QObject, so you can't not connect slots or signals from it. You need to inherit from QObject (or probably QWidget if you want to draw on the screen) and then include the statement Q_OBJECT which instantiates a few needed things. class Time : public QWidget { Q_O...
7,474,765
7,474,812
Passing function pointers of class members
Service::serviceCtlHandler(DWORD OpCode) { //... } Service::ServiceStart { //... serviceStatusHandle = RegisterServiceCtrlHandler("Service", &Service::serviceCtrlHandler /*incompatible*/); //... } How do I get a compatible pointer?
You'll need to make your serviceCtlHandler function static, which means it won't be able to access any object members. This is because RegisterServiceCtrlHandler is expecting a function pointer which is not tied to an object and will not receive an implied this pointer. If you use RegisterServiceCtrlHandlerEx instead, ...
7,474,810
7,474,891
Formatting C++ output problem
Let me examplify my problem , I've a function like: void printer(int width, int hight){ for(int i=0;i<width;++i) std::cout<<" & "; for(int i=0;i<hight;++i) std::cout<<" ^ "; std::cout<<std::endl; } my problem is function printer should always output of both for loop in same width e.g: output could look (w...
Question is unclear. Are you looking for something like the following ? void printer(int amps, int carets, int overallWidth){ for (int i = amps + carets; i < overallWidth; i++) std::cout<<" "; // leading padding for (int i=0;i<amps;++i) std::cout<<"&"; for (int i=0;i<carets;++i) std::cout<<"^"; std::...
7,475,043
7,475,442
What kinds of input streams can you call seekg on?
I have a function (legacy) that reads the first few lines of a file to determine its type, then closes and reopens the file so it can re-read the entire file using the correct interpreter. The gist is: void readFile(const char *filename) { ifstream is(filename); Filetype ft = determineFileType(is); is.close(); ...
The only real answer one can give is that it works where it works. In the case of std::stringbuf, it should work everywhere. In the case of std::filebuf, whether it works or not depends on the system; it will generally work if the filebuf is opened on an actual file, but will usually fail (perhaps silently, if the sy...
7,475,115
7,475,176
Windows Ctrl-C - Cleaning up local stack objects in command line app
I'm writing a console application Windows that creates some objects in the main thread and kicks those off into a loop, only exiting when the user uses the Ctrl-C interrupt. Now, I've read a bit about how to write a proper interrupt handler in articles like this: http://msdn.microsoft.com/en-us/library/ms685049%28VS....
You make your loop on a condition variable. When you receive ctrl-C (SIGINT) you set the condition variable to false and return. The loop will then exit normally. bool finished = false; int main() { DBClient db; DataPuller p; while (!finished) { // ... do stuff until Ctrl-C comes in...
7,475,282
7,475,685
HUGE_VALF Undefined under Windows
I'm attempting to compile a code base originally intended for Linux / Unix platforms under Windows. The code uses the HUGE_VALF variable seemingly without reference to a header that would define it. The MS VC9 compiler I'm using on Windows throws: error C2065: 'HUGE_VALF' : undeclared identifier. What is the reco...
Most implementations define HUGE_VALF to be +Infinity, but it is really only required to be a "large positive value". A reasonable implementation: #if defined(_WIN32) && !defined(HUGE_VALF) # if defined(__cplusplus) static float _X_huge_valf = std::numeric_limits<float>::infinity(); # define HUGE_VALF _X_huge_valf # e...
7,475,398
7,475,451
Visual Studio 2010 C++ SDL game works on the computer it was compiled on, but not on any other
I have coded a game of noughts and crosses in C++ using SDL and Visual Studio 2010. I have built it in Release and it works no problem if I run the .exe on the computer I compiled it on (Windows 7 64bit Home Premium). I tried to run it on my laptop (Windows 7 x86 Home premium) and it opens up an SDL window and immedia...
The first problem is likely an issue with the resource not being at the correct location. The second problem is that with the new Microsoft C runtime DLLs you cannot just include it, you need to deploy the appropriate redistributable for Visual Studio 2010. You can find that (x86) here. There is also a separate x64 ve...
7,475,415
7,475,486
More efficent way of generating this random distribution?
Is there a more efficent, possibly more mathematical and less algorithmic way of achieving a similar random number distribution to this? unsigned int weighted_random_UINT() { float r2 = 1; while(rand() % 4 != 0) // 3/4 chance { r2 *= fmod( ((float)rand()/RAND_MAX)+1, // random float betw...
I think you don't have to loop through it, but once is enough, like so: unsigned int weighted_random_UINT() { float r2 = ((float)rand()/RAND_MAX)+1; // random float between 1 and 2 unsigned int k = 0; while(rand() % 4 != 0) // 3/4 chance {k = k < UINT_MAX ? k + 1: UINT_MAX;} return (unsigned int)fpo...
7,475,479
7,484,948
Reading a cubin structure from a pointer
I am trying to read the contents a c++ structure(in windows) which has the following format typedef struct __cudaFatCudaBinaryRec { unsigned long magic; unsigned long version; unsigned long gpuInfoVersion; char* key; char* ident; ...
As of CUDA 4.0, the format of this struct drastically changed. The value of magic is now different and gpuInfoVersion is now a pointer to a struct that contains the actual data. For more information, you might want to read this thread.
7,475,553
7,475,593
Don't understand static boolean behavior
I have a header file that has some static variables for all of my files to use. I have a boolean variable in there initialized to 0 - //in utility.h static bool read_mess = false; that I want to change to true if --view-read-messages is in the command line arguments so that I can do something like this when I get a m...
static in this context means "local" (to the translation unit). There will be multiple copies of read_mess in your program, one per translation unit which is not the same thing as a header file. (In your case you can most likely approximate "translation unit" as .cpp or .c or .cc file). Probably what you meant to do wa...
7,475,665
7,476,073
Is this example of the use of the C++ 'explicit' keyword correct?
In a GoogleTechTalks video on Youtube, Bjarne Stroustrup talks about the upcoming C++0x standard. In the video he mentions the following example: #include <iostream> struct Sick { Sick(double d) { std::cout << d << "\n"; } explicit Sick(int i) { std::cout << i << "\n"; } }; int main() { Sick s1 = 2...
In his discussion, Stroustrup mentions that a direct initialization, such as Sick s2(2.1); will consider only constructors marked explicit if there are any explicit constructors. That's not my experience with several compilers (including GCC 4.6.1 and MSVC 16/VS 2010), and I can't find such a requirement in the stand...
7,475,711
7,476,194
Click Coordinates after Window Movement
Not being entirely familiar with programming GUIs in C++ and whatnot, I'm running into a problem where my program will not respond to a left-mouse click after moving/dragging the application window. What should I do to make it work properly? Here is how I am handling the left-click message in the callback function: cas...
The mouse location is included in the message as the LPARAM. POINT point; point.x = GET_X_LPARAM(lParam); point.y = GET_Y_LPARAM(lParam); As documented at MSDN, the point is relative to the upper left corner of the client area. Therefore if you move the window, point will still be relative to your window. GetCursorPo...
7,475,726
7,475,738
about c++ try -catch
I read code in a large project, that includs a lot of code like: try { } catch(...) { } Literally, in the parenthesis after "catch", there is "..." in it. Not something like "exception e". This makes me a little worry. Is this practice good or safe? thanks.
No, this is a terrible practice. If you catch(...), you have no idea what you've caught. It catches all C++ exceptions (and on some platforms with some settings, it catches other exceptions too, like structured exceptions in Visual C++). If you have no idea what exception was thrown, you have no idea what the state of...
7,476,117
7,476,187
Cannot access protected member
Possible Duplicate: cannot call base class protected functions? I don't understand the following, when Derived inherits from Base, it gets access to its protected members which can be accessed through Derived functions. But if, Base class tries to access its own members from Derived class (which itself allows access...
A common misunderstanding. Inside Derived::foo(), you can access protected base members of objects of class Derived. However, *b is not of type Derived. Rather, it is of type Base, and so it does not have anything to do with your class. It's a different matter if you take a Derived* as an argument -- then you will inde...
7,476,145
7,479,000
Converting from v8::Arguments to C++ Types
I'm playing with creating Node.js modules in C++, but I'm stumped on the v8::Arguments class. Lets say I have a Javascript class for sending emails, which has a method with this signature: Mailer::sendEmail(Array recipients, String sender, String message); Which would be called like this: mailer.sendEmail(["joe@gmail....
The best way I can find to convert to and from JS types and C++ types, is using v8-juice, which provides type casting methods. Specifically I'm using v8-convert, which is a spin off of v8-juice, that includes only the conversion methods. Converting args[0] to std::list is one line: std::list<std::string> values = cvv8:...
7,476,276
7,476,381
Pattern searching in Binaries
I read about some algorithms that can be used to find a string pattren in long text as fast as possible. I am looking for using aho-corasick algorithm in executable files, What functions or win api can be useful to make a binary ready to start searching?.
Here's one free C++ implementation for Windows: link (look for "Aho-Corasick source code" towards the bottom of the page).
7,476,340
7,476,731
Creating static library that uses Boost ASIO and does not expose it
I'm trying to create a library that uses Boost ASIO (UDP multicast, asynchronous) and does not expose it. Basically I am following the async udp example, except I have made the io_service object a static private member of the library. The code works fine if directly compiled into an executable. If I try and make a st...
You cannot change the class's definition between the library and the application like you show; this would result in (among other things) the application and library disagreeing about the size of the object, causing buffer overflows when you try to initialize these objects. If you want to hide the private implementatio...
7,476,439
7,476,480
Large data processing technology & books
I am looking for good resources on how to query large volume of data efficiently. Each data item is represented as many different attributes such as quantity, price, history info, etc. The client will provide different query criteria but without requirement to change the dataset. By simply storing all data into MS SQL ...
Did you consider NoSql solution as MongoDb ?
7,476,620
7,476,763
Object oriented programming concepts and resource management
So I have a FileReader class, it looks like this: #define DISALLOW_COPY(type) \ type(const type&); \ void operator=(const type&) class FileReader { FILE *file; DISALLOW_COPY(FileReader); protected: unsigned char *data; long size; public: FileReader(const char *filename); ~FileReader...
You could possibly make FileReader * a private member and overload your constructor. public: Image(); Image(const char* fileName); So, the consumer for your Image class decides what happens. In the second constructor you initialize your FileReader * and then destroy it in the destructor only if was initialized...
7,476,710
7,476,752
c++ and ublas: creating an array of c_vectors with different sizes
Is there a way to create an array of ublas c_vectors with different sizes? For example array[0] would return an ublas::c_vector< double, 3 > (size=3) and array[0](0) would access its first element array[1] would return an ublas::c_vector< double, 7 > (size=7) and array[1](0) would access its first element etc
I think you can use std::vector<boost::any>, and then push ublas::c_vector of different sizes into it. std::vector<boost::any> v; v.push_back(ublas::c_vector<double,3>()); v.push_back(ublas::c_vector<double,7>()); v.push_back(ublas::c_vector<double,9>()); //etc Elements should be cast back to the appropriate types, us...
7,476,775
7,476,798
Why do I get a different value at run-time when type-casting a string to DWORD?
std::cout << (DWORD)"test"; If I compile and run this I get different output values each time, but I can't figure out why. Any ideas? PS: I'm using Windows 7 64-bit and I'm compiling with Microsoft Visual C++ 2010 Ultimate.
"test", in your code, is effectively a pointer to the start of the string. When you cast it to a DWORD, your casting the pointer to an integer type, and writing out that number. As the memory location which is storing "test" can change with each run, the value you see will change.
7,477,015
7,477,110
size_t, void* and hbitmap data type equivalents in MIDL
What MIDL data types should I use to declare interface method parameters of C++ data types like size_t, void*, HBITMAP and other types of winapi handles (HANDLE, HFONT, etc.)?
size_t is implementation defined, but using Visual Studio's CRT, it's an unsigned 32-bit integer when compiling for 32-bit architectures and an unsigned 64-bit integer when compiling for 64-bit architectures. You'll want to use unsigned __int3264, which is 32 bits on a 32-bit architecture and 64 bits on a 64-bit archit...
7,477,271
7,477,942
Create a static lib from matlab code
I'm already aware that you can create a stand alone executable and a shared lib from matlab. However, it would be better for our configuration management process (version and distribution) to use a static lib that then is included in the dll I'm building (in C++). This may not be possible at all, but I'm curious. Has a...
With a little google-fu I found this: Generating Static C/C++ Libraries from MATLAB Code It looks like you can create them from projects or from the command line.
7,477,310
7,477,329
Why can't I create a vector of lambdas (of the same type) in C++11?
I was trying to create a vector of lambda, but failed: auto ignore = [&]() { return 10; }; //1 std::vector<decltype(ignore)> v; //2 v.push_back([&]() { return 100; }); //3 Up to line #2, it compiles fine. But the line#3 gives compilation error: error: no matching function for call to 'std::vector<main()::<lamb...
Every lambda has a different type—even if they have the same signature. You must use a run-time encapsulating container such as std::function if you want to do something like that. e.g.: std::vector<std::function<int()>> functors; functors.push_back([&] { return 100; }); functors.push_back([&] { return 10; });
7,477,381
7,477,493
Oh, no! My text is flickering?
Basically, I'm trying to create an application that features a bunch of colored rectangles with text written on them that you can click, making it doing stuff. It runs pretty well, except for the fact that the text on each of the buttons (Created using DrawText()) is constantly flickering. Is there anything I can do to...
From your comment above, you describe calling the draw procedure of your application object form your main message loop. This is almost certainly the source of your problem. Not only will it lead to flickering, it sounds like you are running your application at 100% CPU utilization which is not good. What you should do...
7,477,449
7,477,842
OpenCV Contours Moments?
What are moments of a contour? Could someone explain this in simplistic, non-mathematical terms? Possibly with an example? The official explanation is "integration over all the pixels in a contour". I have no idea what integration. And also what can contour moments be used for?
Moment of 0th degree for a black/white image with black=0 and white=1: this is simply the sum of the pixels, i.e. the number of white pixels. Moment of 1st degree for x-axis and some particular point X on the x-axis: this is the sum of the white pixel distances from X. I.e. it is the sum of their positions wrt. X. If y...
7,477,514
7,477,738
How to auto-generate settings/options dialog box?
Using Visual Studio 2010 C++ with MFC. The number of configurable settings in my application is slowly creeping up. I managed to design a settings class where adding a single line will add a setting to the program and support reading/writing that setting to my ini file. However, I still need to go into my gui editor...
You want the CMFCPropertyGridCtrl class. It was introduced in one of the MFC updates, but I'm not sure whether or not they come pre-installed with Visual Studio 2010; you may need to install something extra.
7,477,912
7,478,518
Using zlib with a Visual C++ CLR Windows Forms Application
I've been trying to do this for a long time, and that is to get the zlib library to work with my program. I'm using Microsoft Visual C++ 2008 Express Edition with a CLR Windows Forms Application. The thing is I'm worried that zlib is to old to work with what I'm using. All the examples (the very few examples) of zlib I...
It is not a problem, C++/CLI was made to handle tasks like this. You have to tell the compiler that the zlib header isn't managed code with #pragma managed and tell the linker to link the import library. Like this, in a sample console mode app: #include "stdafx.h" #pragma managed(push, off) #include "c:/temp/deleteme...
7,477,978
7,478,375
NaN ASCII I/O with Visual C++
I want to read and write NaN values from/into text files using iostream and Visual C++. When writing a NaN value, i get 1.#QNAN. But, reading it back outputs 1.0 . float nan = std::numeric_limits<float>::quiet_NaN (); std::ofstream os("output.txt"); os << nan ; os.close(); The output is 1.#QNAN . std::ifstream is("ou...
With C++03 you can fairly easily work around the issue with the aid of a helper class and your own operator: #include <iostream> #include <sstream> #include <string> #include <limits> struct FloatNaNHelper { float value; operator const float&() const { return value; } }; std::istream& operator>>(std::istream& in,...
7,478,008
7,478,157
Mapping an integer to an array
I recently started with C++; I'm an hobby programmer, and I know a bit of Python. I programmed a little snake. I wanted to insert another snake guided by the computer. I decided to put the possible direction that the snake can take in an enum: enum directions{UP, DOWN, RIGHT, LEFT, IN, OUT, FW, RW,NONE}; void fill_map...
Just a shot in the blue, here is how I would design this. #include <map> enum EDirection { NONE = 0, UP, DOWN, RIGHT, LEFT, IN, OUT, FW, RW }; typedef std::map<EDirection, V4> DirectionMap; typedef std::pair<EDirection, EDirection> DirectionPair; typedef std::map<int, DirectionPair> PairMap; ext...
7,478,028
7,478,149
PersonalVec.hpp:12: error: expected unqualified-id before ‘;’ token error
I got this error and I can't figure out why. #include <vector> #include <cstdlib> #ifndef PERSONALVEC_HPP_ #define PERSONALVEC_HPP_ template <class T,class PrnT> class PersonalVec { public: PersonalVec() {} ~PersonalVec() { //TODO: delete vector. } void push_back(T& obj) { i...
Both rand and vector are in the std namespace. Use private: std::vector<T*> _vec; and std::rand()
7,478,284
7,478,520
how to add boost documentation to qt creator
I am currently starting to use the boost library in qt creator(2.3.0), but the autocomplete feature doensn't work properly. I am wondering if anyone knows what tweaks I need to do in order to acces the autocomplete feature. #include <iostream> #include <boost/regex.hpp> int main() { boost::regex re; std::strin...
The autocompletion does work with Qt Creator. In fact QtCreator can autocomplete boost code where some other IDE fails. Somethimes though the code completion tend to bug, try to reload your project and you should be fine. And of course, like most of the IDEs, no project means no code completion.
7,478,388
7,478,400
Remove function in Release build only
Is there any methods to remove a line of code from a Release build, but leave it in the Debug build without ugly #if statements? For example, is there some way to achieve the equivalent of the below code without using all these if statements? #if DEBUG Log.Log("I am in debug mode"); #endif If I have a conditional,...
Define another macro in a common, shared header. #ifdef DEBUG #define LOG(m) Log.Log(m); #else #define LOG(m) do {} while(false); #endif Then replace your calls to Log.Log with LOG.
7,478,459
7,478,496
Can you tell if a C++ pointer has been destructed?
I have a global singleton that is used by many objects in my program. This is causing crashes when the program is shutting down - it is used in the destructors of some objects, after the singleton itself has been destructed by end-of-program. Is there a portable way to tell if a pointer has had 'delete' called on it?...
No, it is not possible to tell if the object pointed to by a C++ pointer has been destroyed. You can use smart pointers, which handle it automatically.
7,478,604
7,478,676
Subclass recursive method call
In my FileProc class, I have four functions: ReadFile(TemplateList<char> &ReadList){} ReadFile(TemplateListAdv<char> &ReadList){} ReadFile(CharList &ReadList){} ReadFile(CharListAdv &ReadList){} Which are all supposed to call a centralised method (which they are converted to): ReadFile(TemplateListEditor<char> &ReadLi...
Your question isn't very clear. But I'm assuming you have something like this: class A { ... }; class B : public A { ... }; void readFile(A &a) { ... }; void readFile(B &b) { readFile(b); // Recursive call readFile(static_cast<A&>(b)); // Non-recursive call } Function overloads are determined at compile-ti...
7,478,791
7,478,807
C++ global variables across DLLs
I wrote something to simulate the getopt.h library for a Windows application, and part of this is a global variable. This worked fine when I compiled the program as a single application; however, when I split off the getopt library and linked against it, my program started getting segfaults. Investigating this, it see...
What's probably happening is that you haven't setup the dllexport/dllimport correctly. The result is that you're ending up with different copies of the same variable. (one in the DLL and one outside) Within the DLL, you need to compile with dllexport to expose the variable to the client application. Then in the client ...
7,478,889
7,478,929
Building errors with visual studio
I have a solution for a previous c++ project provided to me. When I open the solution in visual studio and try to build, I get the error: 1>------ Build started: Project: Test Proj, Configuration: Release Win32 ------ 1>Build started 9/19/2011 8:28:56 PM. 1>InitializeBuildStatus: 1> Touching "Release\Test Proj.unsucce...
That's not a linker error, it's a compile error. c:\users\mycomp\downloads\stp\testp\code\Angel.h(38): fatal error C1083:... ^^^^^^^^^^^ I bet on line 38 of Angel.h, you're trying to include... ...Cannot open include file: 'GL/glew.h': No such file or directory ...
7,479,149
7,479,182
Aligning output to the terminal using C++
I am having a lot of trouble aligning my output to the terminal. I want to print a vector of vectors viz vector< vector<double> > myvec; to the output where myvec[i] occupies the ith row on the terminal. The vectors composing myvec have size 3 This is the way I am trying to print it. for(unsigned int i=0; i<myvec.s...
You can use setw() to set the minimum number of characters you want to be written and left to output the data to the left. Like this: cout << setw(8) << left << myvec[i][0]; This should fill the empty space with spaces but if not, then you can do: cout << setw(8) << left << setfill(' ') << myvec[i][0]; You will need ...
7,479,265
7,504,836
How to Apply Mask to Image in OpenCV?
I want to apply a binary mask to a color image. Please provide a basic code example with proper explanation of how the code works. Also, is there some option to apply a mask permanently so all functions operate only within the mask?
You don't apply a binary mask to an image. You (optionally) use a binary mask in a processing function call to tell the function which pixels of the image you want to process. If I'm completely misinterpreting your question, you should add more detail to clarify.
7,479,328
7,480,670
Are there any smart IDEs for perl in linux environmnent and also for c++?
Currently I am using CentOS 5.5 and I am looking for intelligent IDEs for Perl and C++ coding.
Why don't you give Komodo Edit a try? Komodo is a good C++/C/Perl/Python/PHP/JavaScript/.. IDE, and it has a precious feature: vi emulation!
7,479,524
7,479,748
Question on virtual operator* on C++
I was trying to make virtual operator on C++ class Data { virtual Matrix operator* (Matrix &_matrix); virtual Scalar operator* (Scalar &_scalar); }; class Matrix : public Data { private: vector<vector<double>> data; public: // ... Matrix operator* (Matrix &_matrix); }; class Scalar : public Data {...
Class double dispatch problem - See Meyer's (forget which one). You need the operator to be virtual on both the lhs and rhs, so you need two virtual calls: class Matrix; class Scalar; class Data { public: virtual Data* operator* (Data& data) = 0; virtual Data* operator* (Matrix &matrix) = 0; virtual Data* ...
7,479,698
7,479,815
Lockless increment if greater than
Is anybody aware of a lockless way to perform what is logically equivalent to a compare_and_swap_if_greater_than()? We have compare_and_swap(), which is really compare_and_swap_if_equal(). The best I have right now is to use a spin mutex, but I think withclever uses of history variables, loops, and compare_and_swap() i...
How about this: public static void CompareAndSwapIfGreaterThan(ref int location, int newValue) { while(true) { var currentValue=Thread.VolatileRead(ref location); if(newValue<=currentValue || Interlocked.CompareExchange(ref location, newValue, currentValue)==currentValue) { return; } } }