question_id
int64
25
74.7M
answer_id
int64
332
74.7M
title
stringlengths
20
150
question
stringlengths
23
4.1k
answer
stringlengths
20
4.1k
6,618,532
6,619,683
How to get a fixture's Shape's points from a Body* in box2D?
Hey i'm trying to integrate Box2D and SFML, and my class takes in a Body pointer, which i need to use to get all the points of a fixture so i can form a graphical representation of the body out of them. How do i get these points?
You can iterate over the fixtures in a body like this: for (b2Fixture* f = body->GetFixtureList(); f; f = f->GetNext()) { .... } Once you have a fixture you will need to check what kind of shape it has, then cast to that shape type to access the shape data: b2Shape::Type shapeType = fixture->GetType(); if ( shape...
6,618,862
6,619,622
Ubuntu Deployment Problem for a C++ Project
I am trying to deploy my application from development environment to users' computer, but I have some issues. First, I compile and run it on my development computer (higher version Ubuntu11.04): Ubuntu11.04$ make Ubuntu11.04$ ./MyApp Program runs okay. Then I copied the binaries MyApp to two lower-version machines (us...
Did you see Link with an older version of libstdc++ I have never installed an older version of g++, but I have included a libstdc++.so in my release and that has worked for me. Best solution I have seen is get your development stuff to work on the oldest possible system. We compile some stuff on Red Hat 9 and it work o...
6,619,033
6,619,122
Why are destructors not virtual by default [C++]
Why doesn't C++ make destructors virtual by default for classes that have at least one other virtual function? In this case adding a virtual destructor costs me nothing, and not having one is (almost?) always a bug. Will C++0x address this?
You don't pay for what you don't need. If you never delete through base pointer, you may not want the overhead of the indirected destructor call. Perhaps you were thinking that the mere existence of the vtable is the only overhead. But each individual function dispatch has to be considered, too, and if I want to make m...
6,619,144
6,619,776
Changing dialog boxes
win32 API: So let's say I have a dialog box with 2 menu items, "Menu Item A" and "Menu Item B" When I click "Menu Item A" I want the main screen of the current dialog to change to dialog A's screen When I click "Menu Item B" I want the main screen of the current dialog to change to dialog B's screen. How would I do thi...
The usual way to do this is to have two child 'container' dialogs as children of your outer frame window; let's call them dialogA and dialogB. These contain the controls for the two respective dialogs. When you want to switch from one to the other, use ShowWindow() to show one dialog and hide the other. In Win32, hidin...
6,619,263
6,619,505
FD_SET Problem/Networking
hi right now im trying to know if a client or the server disconnected and then send an error but i cant seem to make it work and ive got no idea how to do this so i really need help plz here's my code #ifdef _WIN32 || _WIN64 if(select(0,&fd_read,NULL,&fd_close,&time)==-1){ printf("Error ...
What Richard said, in addition, the third fd_set passed to select() is not about closed FDs, but rather about some exceptional condition that requires special attention (which exactly, is defined by the underlying driver, for example, TCP sockets use it for "urgent" data. You detect a remote close by the return code fr...
6,619,282
6,619,291
Calling function x from within function y and vice versa in the same program
int right(int n) { if(n>0) { n--; top_lim ++; cout<<"R"; right_lim--; if(right_lim < size) return(right(n-1)); if(top_lim>0) --> return(up(n - 1)); } else { return 0; ...
Add a forward declaration at the top of your code: int up(int); (Make sure to compile that code with full optimizations! :-) )
6,619,315
6,619,379
Why didn't they add an operator version of iota?
The iota template function was added to the standard library to fill an iterator range with an increasing sequence of values. template<typename ForwardIterator, typename Tp> void iota(ForwardIterator first, ForwardIterator last, Tp value) { for (; first != last; ++first) { *first =...
With lambdas, the second version doesn't save much, you can just use std::generate. template<typename ForwardIterator, typename Tp, typename Operator> void iota(ForwardIterator first, ForwardIterator last, Tp value, Operator op) { std::generate(first, last, [&value,&op](){auto v = value; op(value); return v;}); } In...
6,619,345
6,619,507
Deallocating Dynamic 2D Array with Template
I am having an error in my C++ application that I am having trouble debugging. I have looked online, and I appear to be doing all of my allocation/deallocation the correct way. Here is my code: template <typename T> class Matrix { private: int _rows; int _cols; T** _matrix; public: Matrix(int r, int c); ...
With your edit, the issue here is still the lack of a copy constructor and assignment operator (see my answer to your last question). The problem is that when you pass the Matrix by value into a function, the copy constructor is invoked to make the copy, but since you haven't defined one C++ will use the default copy ...
6,619,360
6,619,476
Cannot convert 'this' pointer from 'const Line' to 'Line &' explanation?
This method: bool Point::Intersects(const Line& line) const { return (line.ContainsPoint(*this, false)); } causes this error: cannot convert 'this' pointer from 'const Line' to 'Line &' This change: bool Point::Intersects(const Line& line) const { return const_cast<Line&>(line).ContainsPoint(*this, false); } ...
You actually provided the answer yourself, in a sense. In your Intersects method, the parameter line is declared const. This restricts how you can use this variable. Specifically, you can only call const methods on it, and you can only pass it to methods expecting a const Line object. However, you pointed out that Cont...
6,619,362
6,619,470
Best way to store stream data
I'm making a game message system and using boost::serialize to convert message data into streams and sending it. This works fine for transmitting messages instantly as I can send off the reference to the stream. However I would like to queue up messages as well in some circumstances. I am not sure what the best way to ...
Try std::queue<std::vector<char> >. The stringstream you tried before isn't copyable, so just copy the bytes. You could also use string as the value type in the queue, since that's probably what you'll be getting out of the stringstream.
6,619,530
6,619,649
C++ Need help iterating through cards, locating pairs and flush's
The program below is suppose to be looking for "Pair's" and "Flush's". It iterates through 10 Trials consisting of 10,000 hands, each hand consisting of 5 cards. The result should (of course it doesn't right now) consist of 10 rows reflecting unique results for each trial. I am stuck...thanks in advance. #include "card...
With a lot of guessing what exactly should happen... 1) Is it made sure, that myDeck.getCard() does not draw the same card twice? Or does it not matter for your task? 2) What is myDeck.addCard(myCards[c]) exactly doing? 3) Why do you increment the loop counter a second time? c++ If this is made sure, you are only compa...
6,619,633
6,619,673
Creating a window in Qt outside of main()?
Is it possible to make a window in Qt outside of the main() function like it's done in the tutorials? What's wrong with they way I did it here? There are no errors when I try to compile, but the window just never shows up. Thanks. main.cpp #include <QtGui> #include "Calculator.h" int main(int argc, char *argv[]) { ...
Curiously, you have two separate errors here :) window is a local variable in the constructor that goes out of scope (and thus is destroyed) once the constructor exits. You must use a persistent object (one that lives after the function exits), such as a member of Calculator. In main, the code Calculator calculator();...
6,619,762
6,619,783
Custom Comparator for Priority Queue of a pair<int, pair<int, int> >
#include <iostream> #include <queue> using namespace std; template< typename FirstType, typename SecondType > struct PairComparator { bool operator()( const pair<FirstType, SecondType>& p1, const pair<FirstType, SecondType>& p2 ) const { if( p1.first < p2.first ) return true; if( p2.first < p1.first ) ...
pair<int, pair<int, int> > a = q.top; Should be changed to: pair<int, pair<int, int> > a = q.top(); ^
6,619,796
6,619,842
Can I replace code in main() into a constructor of a global object?
Assuming that init is the last global object being initialized before main() (and we don't need any command line argument), can I do something like: struct int_main { int_main () { //... start code execution } }init; int main () { } Asking the question in this way, because I am interested in knowing if main...
You would have a hard time catching any exception from the int_main constructor. Also you would have a hard time returning a process exit code with complete unwinding of the stack. That's mainly what main provides in C++: a place to catch exceptions, and a means to return normally (not just exit) with a specified proce...
6,619,804
6,620,351
Over-the-Air / Over-the-Wire automated Software Update (hot-code-loading) strategy
Have a Linux system (as part of my project), where I might have to do hot-code-loading, i.e. update parts of the software, over-the-air (s.a. downloading the software over WiFi) or over-the-wire (over LAN). There are 2 parts of this software, one part written in C++ and another in Erlang. The C++ part talks to some ext...
Don't know about any existing libraries for this. Code loading in C/C++ is in most cases done using dynamic libraries which you can load from code using dlopen. Then you can find addresses of symbols using dlsym. Notice that C++ does name mangling which can make it hard to find symbols. Often best to create normal func...
6,620,069
6,620,086
boost::split: how to split a string with a character?
I'm stuck with this simple problem. Say I have a string which is consisted from characters [0-9]. What I would like to do is split the string by the single characters using boost::split. std::string str = "0102725"; std::vector<std::string> str2; boost::split(str2, str, boost::is_any_of(SOMETHING)); I'm looking for SO...
boost::split is overkill for that. for (size_t i=0; i < str.length(); i++) str2.push_back(std::string(1, str.at(i)));
6,620,080
6,620,239
Lua and c++ errors windows
Hey I'm trying to load a Lua file into my c++ project but there are some errors I don't know how to fix... I have downloaded the libraries from Lua and I've got them in my include folder. The dll's are in my project and the libs are on the lib folder of my compiler so it shouldn't be a linker error. The errors I'm gett...
I fixed it. I downloaded Lua for mingw32. I had the VC++ version. Oh well
6,620,178
6,620,214
What language are the C and C++ standard libraries written in?
C and C++ by themselves can't actually do anything, they need the libraries to work. So how were the libraries created? Assembly language?
C and C++ libraries are almost universally written in C and C++, as are C and C++ compilers. In fact, many compilers are even used to compile themselves! How is this possible? Well, obviously the first C compiler couldn't have been initially developed in C. However, once a C compiler exists, then it can be used to comp...
6,620,348
6,620,386
safe way to get a singleton instance from multithreads
Method 1 DataCenter* DataCenter::getInstance() { static DataCenter instance; return &instance; } Method 2 DataCenter* DataCenter::getInstance() { if (!m_instanceFlag) { m_instance = new DataCenter(); m_instanceFlag = true; } return m_instance; } I am working on a ...
1.You do need to guard it and even if you don't, of course, OS wouldn't do it for you. Use following code for thread-safety: DataCenter* DataCenter::getInstance() { MutexLocker locker(DataCenter::m_mutex); if(!m_instanceFlag) { m_instance = new DataCenter(); m_instanceFlag = true; } ...
6,620,497
6,620,633
Why is single virtual inheritance not enough to resolve the dreaded diamond problem?
struct B { int i; }; struct D1 : virtual B {}; struct D2 : B {}; // <-- not virtual struct DD : D1, D2 {}; Having coded above, still the compiler demands D2 also to be virtual: DD d; d.i = 0; // error: request for member `i' is ambiguous What I don't understand is, once you have prompted compiler that B is virtual w...
B is not virtual with respect to DD - it is virtual with respect to D1. At the time D2 is created, it contains a full copy of B. So now DD has two implementations of B: one as part of D2, and one at the end (pointed by D1). And having two copies of i, using it is indeed ambiguous. Had D2 also used virtual inheritance, ...
6,620,521
6,653,486
Windows ListView control (or similar) that can have multiple columns of checkboxes?
OK, so my Windows application involves a window that, among other things, has a list of objects in a pane. Each object has 8 boolean values that need to be determined — so I'd like a list of the objects, with eight columns of checkboxes after. I'm not using MFC, should that be relevant. ListView looks the way I want it...
Well, I've taken the plunge and started using MFC; the CGridCtrl I downloaded seems to be working pretty well, though I still have a lot of work on it. I'm going to call this the answer, then, since there doesn't seem to be another forthcoming.
6,620,780
6,621,568
Confusing segmentation fault
EDIT: I basically revamped the whole question so I could provide an executable example... I have been getting a segmentation fault that I can't figure out. Here is a compacted version of my code. I maintained the original class hierarchy even though some of the classes have no relevant methods since I think that it has...
You're doing a C-style cast between unrelated types. This is not safe. The fact that you need to do this at all probably indicates a problem in your design, but try replacing this: vector<Data>* transData = ((SimpleVector4<Data>*) translation)->SimpleVector4<Data>::getData(); with this: vector<Data>* transData = dyna...
6,620,791
6,621,004
exporting classes to DLLs
hello im a bit confused with DLLs right now so i came here to ask where there are alot of pros in programming so ive got this class called GUI.h and the GUI.cpp class GUI { public: GUI(void); virtual ~GUI(); void Draw(float x,float y,float z); void Texture(int num); bool Shut...
You don't specify a compiler or operating system, but if this is Windows and Microsoft C++, then you can use __declspec(dllexport) on a class to export it from a DLL. You then use __declspec(dllimport) on the same class when you include the header to be consumed elsewhere. However, I tend to recommend against exportin...
6,621,196
6,674,636
How to set centers of shapes/fixtures/bodies in Box2D
Hey i'm trying to integrate SFML and Box2D, and SFML has made setting centers for sprites, shapes, etc. very easy. Box2D, on the other hand, I'm having trouble with as i can't figure out how to set or even find the center of a shape or fixture. It seems to me that when adding vertices manually to a b2_PolygonShape the ...
Ok I realized that SFML and Box2D really weren't all that different, but i just wasn't thinking about how shapes are made/ rendered correctly in world coordinates. Unless otherwise specified, (0,0) is always used as the refrence point/ center of the object when its position is being moved around/ drawn, and each vertex...
6,621,233
6,621,311
Is it possible to calculate number factorial at compile time, but without enums
I want to calculate factorial at the compile-time. I found some way to solve the problem, but I want to know if there any another solution for this problem without using enum s. Here the solution using enum s. #include <iostream> template <int n> struct fact { enum{value = n*fact<n-1>::value}; }; template<> struct...
While there are alternative notations, It's written that way because more compilers accept that enum-style notation. The language supports const integral-type class members with an inline initialization, but some compilers aren't compliant with the standard in that regard. On compilers that are compliant in this regard...
6,621,379
6,621,515
Qt QLabel HTML font size fails badly
In my Qt application (uses Qt 4.7.0 from Ubuntu 10.10 Linux repository) i tried to use Qt::RichText QLabels using the following HTML: label_1->setText("<font size=64>size=64</font>"); label_2->setText("<font color=red size=10>size=10</font>"); label_3->setText("<font color=blue size=14>size=14</font>"); Fo...
Okay, so font size is supported but have you tried CSS-style font-size:64pt? CSS is better because the size has explicit units.
6,621,494
6,651,035
Qt: open context menu on mouse press
I'm trying to change the default behavior of context menus: Instead of opening on the release event of the right mouse button, I want it to open on the press event, and it's actions to be triggered on the release event). On one widget I could overload the mousePressEvent() and fire a custom contextmenu event, but I wan...
I was trying to implement a widget base on top of QWidget with a custom way to handle context menu to suit your needs when I realize that using ActionsContextMenu policy with actions directly own by the widget does exactly the behavior you are expecting. (Qt 4.6.2 & 4.7 on linux, didn't try on windows yet but I don't k...
6,621,517
6,621,560
Why aren't there convenience functions for set_union, etc, which take container types instead of iterators?
std::set_union and its kin take two pairs of iterators for the sets to be operated on. That's great in that it's the most flexible thing to do. However they very easily could have made an additional convenience functions which would be more elegant for 80% of typical uses. For instance: template<typename ContainerType,...
Are there convenience functions like this hiding somewhere that I just haven't found? Not in the standard library. If not, can anyone thing of a reason why it would be left out of STL? The general idea with algorithms is that they work with iterators, not containers. Containers can be modified, altered, and poked ...
6,621,618
6,622,111
Error in last line of msxml program
I'm using MSXML 4.0 for parsing my xml. The program works fine, but just before the program terminates I get the following exception Unhandled exception at 0x00417be5 in db2.exe: 0xC0000005: Access violation reading location 0x00b1c740. at comip.h at _Release() method at line m_pInterface->Release(); Here's my co...
You are implicitly using COM after you have called CoUninitialize. This is done in the destructor of MSXML2::IXMLDOMDocumentPtr, which calls the function IXMLDOMDocument::Release. CoUninitialize must be the absolute last COM function ever been called. Make these changes, and it will work. I've made sure that CoUninitia...
6,621,752
6,622,024
Comparing variadic templates
If I have two variadic template arguments, A and B, how can I ensure at compile-time that the types of all of the members of A are also the types of a subset of B (in the same order)? Contrived example: template<typename...A> struct Foo { template<typename...B> static void bar() { } } ... Foo<Apple, Orange>:...
For a general subset I don't know, but if you can guarantee that B is of the form A..., More..., then this may do: #include <functional> #include <tuple> template <typename ...A> struct var_equal : std::false_type { }; template <typename A1, typename ...Aother, typename B1, typename ...Bother> struct var_equal<std::t...
6,621,812
6,622,093
Naming Conflict in C++: How to access a struct member called "class"
I came across a naming problem while working with the xlib library: I'm using a struct which has a member called "class". I assume this library is mostly used in plain C programs. So there's no problem. But I'm programming in C++ and here the name "class" is a keyword and cannot be used to denote variables. So, if I'm ...
You say that you're using XLib. I can only find two places in my Xlib.h where class is used as a structure member: Visual and XWindowAttributes. In both cases, the offending member is wrapped like this: #if defined(__cplusplus) || defined(c_plusplus) int c_class; #else int class; #endif Similar hackery appears...
6,622,007
6,622,085
Multiple definitions of main
how do I correctly implement Lua in a C++ program? I downloaded the Lua source, put the .c files in my src folder and the .h files in my include folder, included lua.h in my program's source code (with extern "C"{} of course) and hit "Build". That's how all the tutorials tell me to use Lua with a C++ project. But now I...
Check to make sure you didn't include luac.c, lua.c, and the source for any other programs that are included with Lua in with your source code. Lua's source includes a few extra utilities (i.e., luac), and chances are you've just included them in the project and forgotten to remove them, thus resulting in having more ...
6,622,041
6,622,110
Compiling error: "cannot find -lQtCore4"
Yesterday I downloaded the Qt4 Opensource library for linux. After running ./configure ./make ./make install And inserting this into my .bashrc-file: PATH=/usr/local/TrollTech/Qt-4.7.3/bin:$PATH export PATH After this, I ran cmake in order to produce a Makefile for me. CMakeLists.txt: project(VTKToVTFx) cmake_minim...
In the unix[like] world, the slash is the path seperator, not the backslash. \usr\local\TrollTech\Qt-4.7.3\bin evaluates to usrlocalTrollTechQt-4.7.3bin. edit: Also, your CMakeLists.txt seems a bit foul. Have a look at http://qtnode.net/wiki/Qt4_with_cmake . Instead of target_link_libraries(VTKToVTFx QtCore4) use som...
6,622,290
6,622,774
Emulating CLOS :before, :after, and :around in C++
CLOS has a neat concept of :before, :after, and :around methods. The :before methods are called before the primary method. The :after methods are called after the primary method. The :around methods are called around the :before+primary+:after sequence. The :before, :after, and :around methods are chained rather than...
This is what I could do, but it's still a bit ugly. Basically I put the actual work in a separate hook so you don't have call the pre/post hooks in the processing method. In the inheritance chain you have total control both on whether you want to add pre/post hooks and the ordering of the hook calls (call the parent's...
6,622,320
6,622,351
How to find out if a Boost header can be used as header-only or not?
I am using the Boost headers in my project which is compiled by g++. I downloaded the Boost source and didn't build it so there are no library files to link. When I read the Boost website (http://www.boost.org/doc/libs/1_40_0/) it says Boost.Thread requires its corresponding library, but I am happily using the <boost/t...
The Boost documentation states whether a given library is header only or not. If you're using a library which isn't specified header only, and are not linking against the corresponding library, it's undefined behavior. The fact that it happens to work (or seems to work) isn't really relevant.
6,622,379
6,622,533
Avoiding new() in initialization of static members?
The code in question is as follows: header: class Vec3d : public Object { public: static linearalgebra::Vec3d* X_AXIS; static linearalgebra::Vec3d* Y_AXIS; static linearalgebra::Vec3d* Z_AXIS; static linearalgebra::Vec3d* AXES[3]; static int f(); }; implementation: Vec3d* Vec...
Is it ok in C++, if these pointers are never freed? Define "OK". Will your program function? Yes. Is it a good idea? No! It seems to me that you would be better off with this: class Vec3d : public Object { public: static linearalgebra::Vec3d xAxisMemory; static linearalgebra::Vec3d yAxisMemory; static lin...
6,622,452
6,623,089
Alias template specialisation
Can alias templates (14.5.7) be explicitly specialised (14.7.3)? My standard-fu fails me, and I can't find a compiler to test on. The text "when a template-id refers to the specialization of an alias template" implies yes, but then the example appears to refer to something else, implying no. NB. I'm working from n3242,...
What the Standard means by "specialization" is the transformation of a generic template to a more specialized entity. For example, instantiating a non-member class template yields a class that's not a template anymore. The term "specialization" is two fold, and can refer to a generated specialization (which is a specia...
6,622,670
6,623,199
statement in boost lib, (void)p; what does it mean?
I came across following piece of code in Boost Library for offset_ptr. under boost/interprocess/offset_ptr.hpp typedef PointedType * pointer; ... //!Constructor from other pointer. //!Never throws. template <class T> offset_ptr(T *ptr) { pointer p (ptr); (void)p; this->set_off...
One way to find out is to put a break point on that line of code and step through to find out what it does. You can even reformat the code to allow you to set the break point on that particular statement (there's no law against editing these files - just don't change the actual code). However, my guess is that the poin...
6,622,682
7,189,356
Thrift - different Handler instance for each Socket
Im developing a 'proxy' server in Thrift. My problem is, that each connection incomming to the proxy uses the same instance of the Handler. The client implementation of the proxy is in the Handler, so all the clients communicate throuh the same connection to the end server. I have : n clients -> n sockets -> 1 handler ...
I have managed to solve this problem. There was a solution already implemented in Java. I have used the same idea and implemented it in C++. First thing I did is I created a TProcessorFactory instead of the TTransport class. This handles the TProcessors for each connection. It has a map structure in it, so its' get fun...
6,622,848
6,622,998
Issue Running Sample In Mac Pro X86_64 Of V8 Engine?
Recently, I have a try to build and run sample hello world program of google v8. My xcode version is 4.0.2GA, x86_64. The guide's link: get Started But when run the command: g++ -Iinclude hello_world.cpp -o hello_world libv8.a -lpthread The errors show: ld: warning: ignoring file libv8.a, file was built for archive whi...
It should be obvious you are trying to link with a .a that was build for another architecture. Check out How do I determine the target architecture of static library (.a) on Mac OS X? to learn how to check the target architecture of that .a. Once you know that you can either retarget you project, or create a new libv8...
6,622,962
6,623,009
generic way to print out variable name in c++
given a class struct { int a1; bool a2; ... char* a500; ... char a10000; } I want to print or stream out "a1 value is SOME_VALUE" "a2 value is SOME_VALUE" "a500 value is SOME_VALUE" ... "a10000 value is SOME_VALUE" the type of the member variables are not the same (mainly, int, bool, char*, etc,...
The feature you're looking for is typically called reflection. It is not part of C++, since in compiled languages the information you're after (human-readable variable names) is generally not kept by the compiler. It is not needed to run the code, so there's no point in including it. Debuggers can often inspect either ...
6,623,175
6,705,606
Problem deploying a project that uses Intel Parallel studio
So I have this small application of mine I'm trying to deploy using visual studio. I have Intel parallel studio 2011 added to visual studio, and I'm compiling this program using Intel within VS because I'm using OpenMP task construct which is not supported in VS2010. I added a deployment project to my solution and bui...
I guess you need to install the redistributable libraries on the target machine.
6,623,375
6,623,402
C++ template specialization on functions
I'm playing around with template specialization, and I've found an issue I can't seem to solve; this is my code: template<int length, typename T> void test(T* array) { ... test<length-1>(array); } template<typename T> void test<0>(T* array) { return; } So what I'm trying to do, is to pass the length, of w...
Partial specialization of function templates is not allowed. Herb Sutter explains why in his article "Why Not Specialize Function Templates?". To work around this limitation you need to use class templates instead. You can then write a regular function template that uses that class template. That specific error you're ...
6,623,591
6,623,647
Lifetime issues of QString
I have a class like this: class SomeClass { public: QString data; SomeClass(const QString &); }; and in the .cpp file: SomeClass::SomeClass(const QString &_data) { data = _data; } then I use it like this: SomeClass c("foobar"); This will call QString("foobar") and will pass it to the construc...
All is OK. When you destroy your temporary QString data is modified, so copy would be performed. Data modification means that it will be modified at any side, in string that references data or in string that contains data.
6,623,596
6,623,632
ERROR LNK2019 ( Unresolved external symbol) IN VS2008 WITH ITK AND FFTW
I am performing a project with ITK for processing medical images. After a lot of work there is no further compilation errors, but in the linking process I am having the following info : 1>------Generation started: proyect: prueba_r01, configuration: Debug Win32 ------ 1>Linking… 1>Creating library C:\Documents and Set...
Change the function header in the cpp file to: fftw_complex* prueba_r01::multiply_matrix_2D(fftw_complex* out, fftw_complex* H, int a, int b) You forgot the class name (prueba_r01::) in the implementation, therefore it doesn't find the function body
6,623,628
6,623,662
Race condition on x86
Could someone explain this statement: shared variables x = 0, y = 0 Core 1 Core 2 x = 1; y = 1; r1 = y; r2 = x; How is it possible to have r1 == 0 and r2 == 0 on x86 processors? Source "The Language of Concurrency" by Bartosz Milewski.
The problem can arise due to optimizations involving reordering of instructions. In other words, both processors can assign r1 and r2 before assigning variables x and y, if they find that this would yield better performance. This can be solved by adding a memory barrier, which would enforce the ordering constraint. To ...
6,623,879
6,624,033
C++: optimizing function with no side effects
Is there a way in C++ to declare that a function has no side effects? Consider: LOG("message").SetCategory(GetCategory()); Now suppose that the LOG macro in release builds creates a NullLogEntry object that has SetCategory() defined as an empty function. So basically the whole expression could (and should) be optimi...
There is no standard way of doing so, but some compilers have annotations that you can use to that effect, for example, in GCC you can use the __attribute_pure__ tag in a function (alternatively __attribute__((pure))) to tell the compiler that the function is pure (i.e. has no side effects). That is used in the standar...
6,623,888
6,623,981
Is there any difference between the Java and C++ operators?
If you take Java's primitive numeric types, plus boolean, and compare it to C++ equivalent types, is there any difference what concerns the operators, like precedence rules or what the bit-manipulation operators do? Or the effect of parenthesis? Asked another way, if I took a Java expression and tried to compile and ru...
For an expression like: a = foo() + bar(); In Java, the evaluation order is well-defined (left to right). C++ does not specify whether foo() or bar() is evaluated first. Stuff like: i = i++; is undefined in C++, but again well-defined in Java. In C++, performing right-shifts on negative numbers is implementation-de...
6,624,022
6,624,123
Does allocating memory and then releasing constitute a side effect in a C++ program?
Inspired by this question about whether the compiler can optimize away a call to a function without side effects. Suppose I have the following code: delete[] new char[10]; It does nothing useful. But does it have a side effect? Is heap allocation immediately followed by a deallocation considered a side effect?
It's up to the implementation. Allocating and freeing memory isn't "observable behavior" unless the implementation decides that it's observable behavior. In practice, your implementation probably links against a C++ runtime library of some sort, and when your TU is compiled, the compiler is forced to recognize that cal...
6,624,049
6,633,132
passing thrust::device_vector to a function by reference
I'm trying to pass device_vector of structures struct point { unsigned int x; unsigned int y; } to a function in a following manner: void print(thrust::device_vector<point> &points, unsigned int index) { std::cout << points[index].y << points[index].y << std::endl; } myvector was initialized properly pr...
Unfortunately, device_reference<T> cannot expose members of T, but it can convert to T. To implement print, make a temporary copy of each element by converting it to a temporary temp: void print(thrust::device_vector<point> &points, unsigned int index) { point temp = points[index]; std::cout << temp.y << temp.y...
6,624,470
6,646,804
Unable to use lambda in initialization list of template in C++
I have a class with a std::function constructor parameter. class ClazzA{ public: ClazzA(function<void()> foo){} ClazzA(){ ClazzA([](){}); } }; If I have an instance of this class as a member of another, I have to call constructor in initializer list. I can pass a lambda as an argument, and it is a...
This is a MSVS C++0x implementation problem (see comments under question). Problem solved.
6,624,667
7,280,062
Can I use libcurls CURLOPT_WRITEFUNCTION with a C++11 lambda expression?
I tried to use a C++11 lambda expression with CURLOPT_WRITEFUNCTION, but the program crashes at runtime with an access violation. I'm not sure how to look further into this due to lack of C++11 knowledge, but maybe someone else has an idea how to make this work. The function: #ifndef CURL_GET_H #define CURL_GET_H #inc...
libcurl is plain C library, you need to set a callback that can be called from a such. This means funny C++ things need to be "C'ified" first to work. Like into an old-style function pointer. This is also addressed in the libcurl FAQ entry "Using C++ non-static functions for callbacks?" See also: C-style Callbacks in C...
6,624,668
6,624,719
Is this implementation of a Blocking Queue safe?
I'm trying to implement a queue which blocks on the Pop operation if it's empty, and unblocks as soon as a new element is pushed. I'm afraid I might have some race condition; I tried to look at some other implementation, but most I found were done in .NET, and the few C++ I found depended too much on other library clas...
It’s not thread safe: {//RAII block CGuard g( m_csQueue ); bool wait = m_Queue.empty(); } /// BOOM! Other thread ninja-Pop()s an item. if( wait ) m_eElementPushed.wait(); Notice the location of the BOOM comment. In fact, other locations are also thinkable (after the if). In eith...
6,624,819
6,625,042
C++ vector of objects vs. vector of pointers to objects
I am writing an application using openFrameworks, but my question is not specific to just oF; rather, it is a general question about C++ vectors in general. I wanted to create a class that contains multiple instances of another class, but also provides an intuitive interface for interacting with those objects. Interna...
My question is simple: why did using a vector of pointers work, and when would you create a vector of objects versus a vector of pointers to those objects? std::vector is like a raw array allocated with new and reallocated when you try to push in more elements than its current size. So, if it contains A point...
6,624,844
6,625,239
how to carry out few different set of instruction for string datatype in a template?
I have a template member function in a class that is called for all bool, double, int and string. I want to carry out few instructions that are common to all the above mentioned data types. But for String last few lines of code is different. So can any one suggest me a better way to carry out this in a same template fu...
The solution, as often, is to factorize the common behavior and provide a mean to specialize some parts of the algorithm (see the Template Method pattern). Here, you can do this quite easily by moving the last lines of your function in a function of its own, which can be specialized for certain data types. Remember tha...
6,624,859
6,624,973
problem with I/O exception in c++ ("cin" statement)
In the following program: int main(){ std::cout<<"enter numbers to be divide"<<std::endl; int a,b,c; while(true){ try{ if(!(std::cin>>a>>b)){ throw std::invalid_argument("please enter proper interger"); } if(b==0){ throw std::run...
When std::cin>>a>>b encounters a non-numeric character, two relevant things happen: the offending character is not consumed; the fail bit of std::cin is set. The latter prevents all further reads from std::cin from succeeding. This includes those inside your invalid_argument catch block and those inside subsequent it...
6,624,861
6,625,065
How do I create a lambda function to match a boost::function parameter without using C++0x?
How do I create a lambda function using boost or the stl to match the boost::function parameter expected by F in the third snippet of code in main? #include <iostream> #include <boost/function.hpp> void F(int a, boost::function<bool(int)> f) { std::cout << "a = " << a << " f(a) = " << f(a) << std::endl; } bool G(...
#include <functional> // STL #include <boost/lambda/lambda.hpp> // Boost.Lambda #include <boost/spirit/include/phoenix_core.hpp> // Boost.Pheonix #include <boost/spirit/include/phoenix_operator.hpp> // Boost.Pheonix also ... // Use STL bind without lambdas F(0, std::bind2nd(std::equal_to<int>(), 0)); F(123, ...
6,624,942
6,625,128
Makefiles, moving from VC6 to Visual Studio 2010
I'm trying to migrate some projects from VC6 to Visual Studio 2010 but I'm running into issues with makefiles - at the moment they don't work! (Which was expected). Any ideas or pointers how they should be written now (before it was a line beginning with msdev... which cannot be found now, is there an up to date equiva...
The VS2010 app name is devenv. From the command line, as long as you've run the right vcvars32.bat file, just type devenv /? to get the command line build help. Essentially, it's: devenv solutionfile.sln /Build "Release" So once you upgrade your projects and create a solution, you should be ok. There may be a way to bu...
6,625,046
6,625,132
catching unknown exception
In the release version of my code one line is throwing an exception and I don't know what type of exception it is so I can't catch it correctly or figure out the problem. I using the catch(...) but that's pretty much worthless. here is some pseudo code try { m_mmwIPC = gcnew NiftyIPC(gcnew String("Monitor"), tru...
Not really, it could be an int, a const char* or a RhubarbPie über-smart pointer. However: Try catching std::exception too. That will catch a lot of C++ native exceptions. Your exception is probably a .NET one, so try to catch that one, not the MFC Base exception. (It looks like you're doing C++/CLI. In that case, .N...
6,625,149
6,625,371
SCTP: any cross-platform library?
I'm investigating SCTP protocol. Its features look attractive. What I worry is its support from community. Is there any good cross-platform (at least Linux and Windows) C++ (or at least C) SCTP library? Does it support async methods?
Not sure how well tested/working this is (never got to use it myself), but I looked at http://code.halssoftware.com/index.php/p/boostasiosctp/source/tree/master/boost a while ago. Let me know if that does anything for you.
6,625,249
6,625,322
dialog box controls - detect changes
I want to detect when any control on a dialog box is changed by user action. For example, when data is entered in a text box, a date is entered in a date-time picker, a check box is checked or unchecked, etc. Up to now I have ignored such notifications and simply retrieved the state of the controls when the user push...
You can test whether a checkbox has been checked with the BN_CLICKED notification code which you'd get through WM_COMMAND. switch( uMsg ) { ... case WM_COMMAND: { switch( HIWORD( wParam ) ) { case BN_CLICKED: { if( Button_GetCheck( lParam ) == BST_CHECKED ) { ... } break; } ...
6,625,483
6,625,557
Pass a member function to create a free function boost pointer
I try to get this code running. I am almost there but I got stuck with the line: _f = std::bind1st( std::mem_fun(f, x); First of all please understand that I don't want to change any code, but the constructor. Why? Because I want to learn. Eventually I want to write a wrapper class Func, that can handle free...
It seems you just forgot a paren: _f = std::bind1st(std::mem_fun(f), x); Although I would initialize with Func(X *x, int (X::* f) (int)) : _f(std::bind1st(std::mem_fun(f), x)) { std::cout << _f(5); // Call x.foo(5) }; (It doesn't matter in this case, but this style is safer in the long run.)
6,625,522
6,625,729
Clear part of terminal screen in C++ unix?
I want to output stuff onto the terminal window and then only clear part of it (like first half or quarter etc) and not the rest. Is there a way I can do this? I was using system("clear"), but that clears everything. I'd prefer to NOT use ncurses. Any help is appreciated.
If you need a general solution, then it will somehow involve going back in the terminal, by using special characters, overwrite the part that you want to delete with blanks and restore the part, that should still be visible. You can find out, how to go back in the terminal in this post. It includes some examples, that ...
6,625,844
6,625,948
templates accepting two iterators
Why ordinary algorithm template is designed so that it accepts two iterators instead of pair of these iterators ? Consider this example: #include <iostream> #include <iterator> #include <vector> using namespace std; template <typename Range, typename OutputIterator> void copy2 (Range r, OutputIterator o) { copy...
Really? There isn't one. The Standard library only has the notion of iterators because, as far as I know, nobody came up with ranges before it was Standardised. Many people think that it could be vastly improved by using ranges. Secondly, you can easily improve the verbosity of #2 with a little extra pre-written boiler...
6,626,030
6,626,067
Optimizing conversion algorithm
I have recently been working on a exercise in a book I have been reading. The task was to create a program that prints all the numbers between 1-256 in their binary, octal and hexadecimal equivalents. We were only supposed to use methods we had learned so far in the book, which meant only using for, while and do..while...
Break out the functions for each output type, then loop through the integer list and output each in turn by calling the function for each different format. for (int i = 1; i <= 256; ++i) { printBin(i); printHex(i); printOct(i); } Fundamental problem is that a function this long needs refactoring to be more mod...
6,626,201
6,626,264
create instance of unknown derived class in C++
let's say I have a pointer to some base class and I want to create a new instance of this object's derived class. How can I do this? class Base { // virtual }; class Derived : Base { // ... }; void someFunction(Base *b) { Base *newInstance = new Derived(); // but here I don't know how I can get the Deriv...
Cloning struct Base { virtual Base* clone() { return new Base(*this); } }; struct Derived : Base { virtual Base* clone() { return new Derived(*this); } }; void someFunction(Base* b) { Base* newInstance = b->clone(); } int main() { Derived* d = new Derived(); someFunction(d); } This is a pretty typic...
6,626,467
6,626,729
using mem_fun with function that has more than one argument
I am trying to work with the boost:function class. In the example below, everything works fine for the foo()-call, but if I want to do the same with the sum()-function, the gcc-compiler complains about this line: _f2 = std::bind1st(std::mem_fun(f), x); Does mem_func only accept functions with one argument (except for ...
You can use boost bind: _f2 = boost::bind(f, x, _1, _2);
6,626,672
6,626,831
Befriending a template class: Compile error
I'm trying to use the Pointer to Implementation Idiom to hide the fact that I am using a Concurrency::unbounded_buffer (from VC++ 2010). The problem is, I'm doing it with templates and got stuck in a compile error. Here's the code: BlockingQueue.h #pragma once namespace DRA{ namespace CommonCpp{ //Forward declarat...
Your problem is incorrect syntax of the template function definition. The second class keyword should be removed. template<class Element> void BlockingQueueImpl< /*class*/ Element>::Push( Element newElement ){ send( m_Queue, newElement ); } And yes, you should not separate template declaration and its implementati...
6,626,759
6,627,128
Why the template with default template arguments can't be used as template with less template argument in Template Template Parameters
myTemplateTemplate expects the second template parameter is a template with one argument. myDefaultTemplate is a template with two arguments, and the second argument has default type int. In VS2008, I get the compile error:the template parameter list for class template 'myDefaultTemplate' does not match the template p...
From the standard (see 14.3.3 paragraph 1 - [temp.arg.template): A template-argument for a template template-parameter shall be the name of a class template, expressed as id-expression. Only primary class templates are considered when matching the template template argument with the corresponding parameter; part...
6,626,802
6,627,149
How to execute unary function objects of different parameter type in sequence?
I'm designing a mechanism that will execute a set of unary function objects in sequence. These function objects are assigned during runtime, and the problem is: the parameter type of these function objects are different. What I want to do is something like this: class command_sequence { private: /* some kind of contai...
Since it appears that the argument to the unary function is fixed at the time you add it to the sequence, you could make your sequence accept zero-argument function objects using boost::function, then boost::bind the required parameter, e.g. class command_sequence { public: void add( boost::function<void(void)> fun...
6,626,964
6,627,125
Calculating Pi using for loop
I have just made a program which calculates pi. However, even with 10 million iterations my result is kinda off. I get 3.1415927535897831, whereas already early on is it wrong. It is supposed to be 3.141592653589793238... So my question is: What is the required amount of iterations to get at least an accurate answer a...
You are using the Leibniz series, which is very, very slow to converge. In an alternating series such as the one you are using, the first omitted term provides a good estimate of the error in the estimate. Your first omitted term is 4/2000005, so you should expect less than six significant digits of precision here. Not...
6,626,992
6,627,516
Reading in UTF-8 Files
I'm using VS 2008 and need to read text files that have UTF-8 Chinese characters. The file is organized like this: Each line contains a document, and the documents are tab delimited (index 'tab' doc title 'tab' doc body). So what I need to do is separate the rows on tabs then separate the third column (doc body) by spa...
You'll need to convert your UTF-8 file into UTF-16 (wstring) before you can do any of the parsing. As you're using Windows, you can use MultiByteToWideChar to accomplish this http://msdn.microsoft.com/en-us/library/dd319072(v=VS.85).aspx There's some links to source code within.
6,627,086
6,627,579
How is macro replacement performed in complex situations?
Consider the following sample code. #define T(q) L##q #define A(p) T("x" T(#p)) wchar_t w[] = A(a); Is this code well-formed? What is the value of w? Is the behavior different in C and C++? Is it different in C++0x? I've browsed through the C++03 standard and it seems to me, that the code should be valid with w having...
g++ expands to L"x" T("a") Macro cannot be recursive and they are pre-processed only in one shot, so T(#p) would not be expanded again. If you wanted L"xa" then following can be done: #define A(p) T("x")#p #define T(q) L##q (It's actually L"x""a".)
6,627,167
6,627,233
std::set::insert, how bad can I hint?
I'm doing lots and lots of inserts of std::pair<int, int> into a std::set, and it's taking longer than I'd like. When I wrote the code I figured I'd look at using the hint iterator form of insert later if it turned out to be a bottleneck; well, now it's profiled and it is a bottleneck. So I want to use the iterator hin...
I suggest just reading what the compiler reads: the header file for #include <set>. On my system (GNU libstdc++ 4.5.1) I can read the following self-explanatory text: /** * @brief Attempts to insert an element into the %set. * @param position An iterator that serves as a hint as to where the * ...
6,627,180
6,627,274
Shared library, library dependancy
Is it possible to provide a shared library - which links against another shared library during its creation - transparent to the end user? As an example of what I mean: Shared Library Build g++ ... `pkg-config gtk+-2.0 --cflags` ... `pkg-config gtk+-2.0 --libs` Desired User Build g++ file.cc -lfoo Where libfoo.so.0 i...
If you have a shared library libABC.so which links to libXYZ.so then, while creating your libABC.so, you have to link with libXYZ.so ld --shared -o libABC.so -L. -lXYZ While compiling the application, gcc app.c -L. -lABC don't forget to, export the library path export LD_LIBRARY_PATH=.
6,627,209
6,627,557
Problem with gdb while trying to use with an executable
I have an executable that was built in Qt. When I try to use the command, "gdb my_executable", I am able to set breakpoint only for the functions that are in the main.cpp file, For all other functions, I get the message, No source file named filename.cpp Make breakpoint pending on future shared library load? (y or [n]...
Compile all your sources with the -g option. This will include debugging information in your .o files, like information about what the source file name is and what line number corresponds to each instruction.
6,627,429
6,627,566
Lua, C++, any good introductions that go deeper than lua_open()?
I googled a lot now, but all I find are "Hello World" examples for Lua with C++. Situation: Game, big game. Has an in-game console, currently hard-coded in C++ (object-oriented and all), has a lot of if-else-if-else... blocks to check for the commands that the user entered in the console. Each command can change member...
Get a copy of Programming in Lua if you haven't already. The section describing interop with C (and hence C++) is almost 100 pages, and much more than a 'hello world'. There's no specific C++ binding information in the book, but if your C++ compiler has any RTTI capabilities,that can be helpful. That's how we integrate...
6,627,651
6,627,748
enable_if method specialization
template<typename T> struct A { A<T> operator%( const T& x); }; template<typename T> A<T> A<T>::operator%( const T& x ) { ... } How can I use enable_if to make the following specialization happen for any floating point type (is_floating_point)? template<> A<float> A<float>::operator%( const float& x ) { ... } ED...
Use overloading instead of explicit specialization when you want to refine the behavior for a more specific parameter type. It's easier to use (less surprises) and more powerful template<typename T> struct A { A<T> operator%( const T& x) { return opModIml(x, std::is_floating_point<T>()); } A<T> opM...
6,627,701
6,633,085
MFC C++ Reference INI file in application folder after deployment
Hoping for some help here, as I am tearing my hair out!I'm using Visual Studio 2010. I have an MFC C++ application to deploy. I have a config.ini file that I'd like referenced when the exe starts. At the moment the user cannot double click on a *.myfile and it open, because the application does not "start in" the appli...
Thanks for all the input and prompts. It helped me get to this solution. Hopefully it helps some others to have the info in one place. This solution is a very simple one and probably not for full commercial deployment! In VS2010 in the FileSystem (Setup) put the config file in the User's Application Data Folder \ Prod...
6,627,716
6,632,030
boost spirit qi rules' attribute question
I have the following code can not compile, however I do not know where is the problem: #include <boost/config/warning_disable.hpp> #include <boost/spirit/include/qi.hpp> #include <boost/spirit/include/phoenix_core.hpp> #include <boost/spirit/include/phoenix_operator.hpp> #include <boost/spirit/include/phoenix_fusion.hp...
This has been discussed at length elsewhere (for instance here). If you change your print function to take a vector<char> it will work: void print (std::vector<char> const& s) { std::cout << "Get string [" << std::string(s.begin(), s.end()) << ']' << std::endl; } There is one more err...
6,627,774
6,627,817
How do I need to configure Eclipse to create a C++ program?
I installed Eclipse for C/C++ Developers. After installing it I also installed PyDev. I managed to create a C++ project (The Hello World project that comes with it). But I cannot compile/run it. When I created the project there was nothing in the toolchain list. So I think I will need to install a toolchain. But I cann...
No compiler, no executable. Check MinGW This is one of the first results i got in google for eclipse and mingw: http://max.berger.name/howto/cdt/cdt.jsp
6,628,290
6,628,315
C++ header include conflict
I am working on a traffic simulation program for school. My Simulation class reads in a list of vehicles from an XML file, so I have included Vehicle.h in my Simulation class. I want my vehicle to be able to hold a pointer to the simulation object so that it can use the simulation's searchRoads function. So I included ...
Either, You are missing inclusion guards, leading to multiple inclusion of header files Or You are creating a Circular Dependency of your headers. You should be rather using Forward Declaration. Post details of your code for more detailed answer.
6,628,442
6,629,246
Can tr1::function swallow return values?
The boost::function FAQ item 3 specifically addresses the scenario I am interested in: Why are there workarounds for void returns? C++ allows them! Void returns are permitted by the C++ standard, as in this code snippet: void f(); void g() { return f(); } This is a valid usage of boost::function because void...
I believe tr1 addresses this issue. N1836 (the latest tr1 draft) says: A function object f of type F is Callable for argument types T1, T2, ..., TN and a return type R, if, given lvalues t1, t2, ..., tNoftypesT1, T2, ..., TN,respectively,INVOKE(f, t1, t2, ..., tN)is well-formed([3.3]) and, if R is not voi...
6,628,468
6,628,992
Change multiple inheritance into deriving from a template
Say I have a bunch of code for all controls, yet I need subclasses that interact with my software suite to use those common methods. I really want my subclass to derive from the control, not the class with the common code. (A MyEdit should derive from Edit, not from MyControl). Also, the suite interacts with controls u...
I can't say I quite followed your question, but in regards to: However I'm not sure this will work, because the template templatizes Edit, but it doesn't necessarily create one does it? When I create the template will I actually be able to create the Edit? I would go for template<class Controlled_t> class ...
6,628,517
6,628,612
C++: make one matrix point to another
all. I have an interesting question, posed to me by my C++ professor. It is also used in some programming job interviews, apparently. Here's the situation. I have a two-dimensional array (matrix) of int's: int array1[][2] = {{11, 12}, {21, 22}}; I would like to create a second two-dimensional array, array2, that point...
Since this is C++, you can create an alias array using a reference, that's exactly what they do. int array1[][2] = {{11, 12}, {21, 22}}; int (&array2)[2][2] = array1; for(int i=0; i<2; ++i) for(int j=0; j<2; ++j) array2[i][j] -= 11; Although the problem is more likely a C problem with the expectation tha...
6,628,522
6,628,555
Replacing a set object with a new set object
I have a class with a private field: std::set<std::string> _channelNames; .. and an optional setter function: void setChannelNames(std::set channelNames); In the setter function, how do I replace the private _channelNames field with the one passed from the setter function? I tried: void Parser::setChannelNames(std::s...
You just have to specialize template. You cannot use std::set without specialization. void Parser::setChannelNames(const std::set<std::string> & channelNames) { this->_channelNames = channelNames; }
6,628,638
6,628,699
deserializing a csv stream to a vector of structures
I have a Visual Studio 2008 C++ project where I would like to be able to take a list of comma-separated values stored in a std::stringstream and put them in a vector like this: struct Foo { std::string A; std::string B; std::string C; } typedef std::vector< Foo > FooList; std::stringstream csv; // conta...
// Input std::stringstream csv; // Prepare variables FooList v; std::vector<string> tokens(3); std::string line; // Iterate over lines while (std::getline(csv, tmp)) { // Grab comma-delimited tokens tokens.clear(); boost::split(tokens, tmp, boost::is_any_of(",")); // Verify line format if (tokens.siz...
6,629,530
6,629,620
error LNK2028 when calling the WinSnmp function SnmpStartup?
I'm trying to write a simple demo application in C++. I just want to query some of the printers on my network and sort the incoming info into a few database tables but I get this error when compiling my code: Error 1 error LNK2028: unresolved token (0A00001C) "extern "C" unsigned long __stdcall SnmpCleanup(void)" (...
You do not have any definition for SnmpStartup() & SnmpCleanup() so linker complains that it cannot find a reference to it. Probably, you are using a library which defines these functions but are you linking to it? EDIT: You should be linking your program to Wsnmp32.lib or Wsnmp32.dll and it should work fine. Have a l...
6,629,775
6,629,957
How do I invoke my C++ binaries via the CGI interface?
I'd like to convert a PHP solution to a C++ solution. Currently I have my server-side written in PHP - not too much code, under a thousand lines. So I can rewrite it with no problem - I don't need to use hip-hop or similar automations. The question is how do I install/configure the correct software to support C++ code...
Three basic options: do the whole thing in C++, making your program a standalone web server (possibly proxying through apache to provide things like ssl, static media, authentication etc.) run C++ in a cgi-bin, through apache make a PHP wrapper that shells out to the C++ part (this is a nice option if the performance-...
6,629,802
6,629,862
Help with a programming challenge
I am trying to make the programming challanges from the book written by Steven S. Skiena and Miguel A. Revilla. But I am already having problems with the first challenge called "The 3n+1 problem". The challenge can be found here: http://www.programming-challenges.com/english/pdfs/110101.pdf The solution I though of is....
You output an extra space at the end of each line. Try removing this space, as automated judging often fails on such things. Other than that, your algorithm looks correct to me. By the way, there's no reason to put the numbers in vectors - you can just output the results for each line as you calculate them. Edit: It is...
6,630,181
6,630,288
C++ library that imitates matlab's functionality
I'm wondering if there any c/c++ libraries out there that imitate the functuonality that matlab offers (neglecting all the toolboxes of course) and if so, how they compare to matlab in both simplicity and speed?
For standard linear algebra, Armadillo essentially has "ease of use" a la Matlab as a stated goal. Quoting from the main page: Armadillo is an open-source C++ linear algebra library (matrix maths) aiming towards a good balance between speed and ease of use. Integer, floating point and complex numbers are su...
6,630,466
6,630,799
Strange behaviour with operator[]
Having spent the last couple of days experimenting with C++ operator[] methods, I've come across an anomaly that I can't easily explain. The code below implements a simple test string class, which allows the user to access single characters via its subscript "operator" method. As I would like to differentiate between l...
The line s1[0] = s1[1]; causes the compiler to generate an implicit copy assignment operator for CReference if you didn't declare one yourself. This causes an error because your class has a reference member, which can't be copied. If you added an assignment operator that takes a parameter of type const CReference&, it...
6,630,623
6,630,720
Capture All Keyboard Input
First off, I know this could be used for a keylogger. I'm not going for that, I'm looking to make an application that listens for custom key combinations just to automate a few really annoying tasks. Is there some way to capture all input from the keyboard?
You appear to be looking for RegisterHotKey(). I don't think you want to hook all keyboard input. You simply want an app with a hidden window listening for WM_HOTKEY. I don't think you even need to write it yourself. There are a lots of utilities that will do it for you and let you associate system-wide hot keys with ...
6,630,802
6,638,017
Draw border of QGraphicsItem
How to draw border of QGraphicsItem ? Simple painter->drawRect( boundingRect() ) in overloaded paint method is not correct(bottom-right corner is outside the item).
I found out my problem. Thanks for all advises, but now I see, that my problem was elsewhere. I can draw a QRectF(), which fits to boundingRect of my item, but... when I scale my QGraphicsView (no matter if I use fitInView() method, or my own implementation) there are some errors in displaying my border. Rarely one or...
6,631,347
6,631,370
How to indent lines using recursion?
Trying to achieve something like this using recursion: if (m > n) return; Foo 1 // no tabs Foo 2 // \t Foo 3 // \t\t Foo 2 // \t Foo 1 // no tabs I have a function that takes 2 parameters: void indent(int m, int n); (calling number from m to n). So far I figured this much ...
Looks like you are on the right path. You would just want your recursive method to check when m == n, you would only print the line once rather then twice and then unroll.
6,631,357
6,631,425
Calling functions in a DLL loaded by another process
I have a DLL that I inject into another process but I want to be able to call the exports on that DLL from my application. I've read elsewhere that you have to the SendMessage API but I have no idea what to do. Is there any example code on how this is done?
You can't directly call functions in another process, in general. There are, however, some workarounds you can use. First, if you know the address of the export (which isn't the case a lot of the time), and the function you call uses the __stdcall calling convention, takes a pointer-sized integer as an argument, and re...
6,631,426
6,632,073
boost::asio only works when run within Visual Studio
I am using boost::asio::io_service and boost::asio::deadline_timer from a secondary (i.e. non-GUI) worker thread. This works perfectly when the program is run from within Visual Studio (2010). However, when I run the release executable outside of Visual Studio, the async_wait()/run() combination doesn't seem to do an...
(Reposting from comment so the question can be marked as answered) You probably have an uninitialized variable somewhere, i.e. a default-initialized object of scalar or POD type.
6,631,926
6,632,527
Interface bloat needs trimming
Sorry about the bad title, I couldn't think of a more descriptive one. The Shape ADT I have is steadily getting bigger and more bloated, specifically due to this section of the interface: class Shape() { //... virtual bool Intersects(const Point& point) const =0; virtual bool Intersects(const Line& line) ...
The first thing to realize that as structured, this can't help but break encapsulation. Each intersection function must know the internal workings of two different objects. The second thing to realize is that this is an n^2 problem, or more precisely n*(n+1)/2. Each time you add a new shape, you must add an intersectio...
6,631,954
53,901,119
How to Render images in shape/ polygon form?
Hey i'm working with SFML right now, and upon finishing the tutorials i still do not know how to give a shape a texture or image, and not just a solid color/outline. The only thing i know can take an image is a sprite, but thats WAY to simple, as it only allows you to render rectangular images in a rectangluar way! Wh...
SFML has been updated since this question was originally answered and you can now add textures to shapes easily. The shape class has the setTexture() and setTextureRect() methods. setTexture() takes a pointer to an sf::Texture. See the documentation. Sf::Texture texture; if (!texture.loadFromFile("mytexture.png")) { ...
6,632,064
6,632,111
Inserting typedef map into a hash table
In the program below I've a typedef map. What I want to do is to implement a hash table. I'm trying to use unordered_map since I heard that is the efficient as it takes O(1) time. I use my typedef map everywhere in my main program (another program that I'm working on) so I don't want to change that. I want to implement...
The basic element you're missing to make this work is to define a hashing function for your std::set that you're using as the key. The STL already defines equality and lexicographical ordering for a std::set, so you can use it as the key-value in a std::map as-is without any problems. It does not define a hash functi...