question_id
int64
25
74.7M
answer_id
int64
332
74.7M
title
stringlengths
20
150
question
stringlengths
23
4.1k
answer
stringlengths
20
4.1k
4,774,291
4,774,338
Q_OBJECT throwing 'undefined reference to vtable' error
I'm using Qt Creator 2.0.1 with Qt 4.7.0 (32 bit) on Windows 7 Ultimate 32 bit. Consider the following code, which is a minimum to produce the error: class T : public QObject, public QGraphicsItem { Q_OBJECT public: T() {} QRectF boundingRect() const {return QRectF();} void paint(QPainter ...
It is because the unit generated by MOC isn't included in the linking process. Or maybe it isn't generated at all. The first thing I'd do is to put the class declaration in a separate header file, perhaps the build system isn't scanning implementation files. Another possibility is that the class in question once didn't...
4,774,300
4,774,363
Boost: is it any how possible to start a process and run a function in it?
My main point is that let's say we create our main function of our app which lies in one project file. We have some static function in it like one with cout << "Hello!";. We want boost to create a process for us and run that function in it. Is such thing possible using boost and how to do it?
Boost.Process though it has not been accepted into the Boost distribution yet.
4,774,420
4,775,714
Use of rvalue reference members?
I was wondering what use an rvalue reference member has class A { // ... // Is this one useful? Foo &&f; }; Does it have any benefits or drawbacks compared to an lvalue reference member? What is a prime usecase of it?
I've seen one very motivating use case for rvalue reference data members, and it is in the C++0x draft: template<class... Types> tuple<Types&&...> forward_as_tuple(Types&&... t) noexcept; Effects: Constructs a tuple of references to the arguments in t suitable for forwarding as arguments to a function. Because ...
4,774,508
4,774,537
C++ C2582 Compiler won't auto-generate default c'tor or = operator
setting aside the fact that I use getter/setter where the more experienced C++-programmer won't make use of them I have a problem with the following code: #include "Player.h" class Entity { public: Entity::Entity(Player& _owner) : owner(_owner) { } Player &get_owner() { return this->owner; } void...
You cannot "reseat" a reference, not even a class member which is a reference. this->owner = _owner; is not going to change what object the member refers to, it's attempting to modify the object this->owner always has referred to and always will. If you need your class to change what other object(s) it refers to, use ...
4,774,524
4,774,538
The memset() function
I am a beginner to C/C++, and I came across the following segment of code: #define MAX_MSG 1000 char *szBuf = new char[MAX_MSG]; char *szBufRaw = new char[MAX_MSG]; memset(szBuf, ‘\0’, strlen(szBuf)); memset(szBufRaw, ‘\0’, strlen(szBufRaw)); I've read the tutorial about memset here: http://www.java-samples.com/showtu...
strlen(szBuf)(and strlen(szBufRaw)) will return correct result only on valid strings. You should pass MAX_MSG instead.
4,774,877
4,774,913
template function with more than 1 typename
It seems C++ template can automatically deduct the type, when there is only one template parameter. For example, template<typename T> void f(const T &t) { cout << t << endl; } f(1); is fine. However, template<typename T1, typename T2> void f(const T1 &t1, const T2 &t2) { cout << t1 << t2 << endl; } f(1, 2)...
The second function and call is perfectly valid. Your compiler is bugged or flat out old rejecting it.
4,774,899
4,777,293
Rotate camera over centre of a model
i have 2 meshes rendered with DirectX 9 and a camera that is looking at 0,0,0. One mesh is located at 0,0,0 and the other one at 5,0,0. How can i rotate the camera around 0,0,0 to always look the two meshes but from the new position? I would like to press the arrow keys on the keyboard and be able to rotate the camera
Build the camera matrix from a lookat function. There are d3dx functions to build a proper matrix. What you want to do is to setup the camera so that you can let it go in a circle around the objects. Say a circle of radius 10 centered around 2.5,0,0. Iam not sure around what axis you want to rotate but i assume z (and ...
4,774,932
4,775,053
Boost.Process - how to make a process run a function?
So I try to do something with Boost.Process though it has not been accepted into the Boost distribution yet. simpliest programm would look like #include <boost/process.hpp> #include <string> #include <vector> namespace bp = ::boost::process; void Hello() { //... contents does not matter for me now - I just w...
You can't. Another process is another executable. Unless you spawn another instance of the same program, the child process will not even contain the Hello() function. If the child is another instance of your program, you need to define your own way to tell the child to run Hello(). That could be process arguments or so...
4,775,157
4,777,374
Boost::asio udp socket - how should I use the API to allow cancellation of reads?
I am using boost::asio::ip::udp::socket to communicate. I use socket.receive_from(...) to receive messages from clients. This is working fine for now, but I want to be able to shut down my server. Right now I am calling receive_from in a while-loop, which depends on a bool condition which I can set. However, this is pr...
There's no good way to do what you want using the synchronous receive_from method. You should use the asynchronous async_receive_from method if you desire timeouts and cancelability. There's a ticket on the Boost.Asio trac website describing this. I answered a similar question recently that you might find useful as wel...
4,775,187
4,775,245
Visual Studio: how to create a project that would compile 2 exe files?
So I have main.cpp and main2.cpp with int main in each. I want to get 2 exes out of it. Is it possible and what would be instruction to create such project?
Nope, Visual Studio's project model is rigidly built around the assumption that "one project generates one output". If you need two executables, you have to create two projects. You can keep them in the same solution to make things easier for yourself, but they have to be separate projects. Edit Ok, as other answers ha...
4,775,246
4,775,275
Vector error message and how to insert an object into a vector in C++?
I have a Room class and it has this constructor: Room::Room(string a, int b, int c, string d) And in my main function I do: vector<Room> room; sale.push_back("aaa", 1, 2, "ccc"); It gives me this error: error: no matching function for call to ‘std::vector<Room, std::allocator<Room> >::push_back(const char [4])’ note...
Probably something like: std::vector<Room> rooms; room.push_back(Room("aaa", 1, 2, "ccc"));
4,775,411
4,775,423
C++:: Call class method using vector iterator?
I have a class called Room, the Room class has setPrice and display function. I stored room objects in a vector: room.push_back(Room("r001", 1004, 2, "small")); room.push_back(Room("r002", 1005, 2, "small")); room.push_back(Room("r003", 2001, 4, "small")); room.push_back(Room("r004", 2002, 4, "small")); In my main fun...
Dereferencing has higher priority than member access. You could add parens ((*it).display()), but you should just use the shortcut that was introduced long long ago (in C) for this: it->display(). Of course the same rule applies for pointers and everything else that can be dereferenced (other iterators, smart pointers,...
4,775,584
4,775,718
Linker Error in c++, It is just a simple class program, I am beginner at c++
#include<iostream> #include<stdlib.h> #include"header_complex.h" using namespace std; class Complex { private: float real,imag; public: Complex(); //default cnstructor Complex(float, float); //parametrize constructor void set_real(float); void set_imag(float); float get_real(); float get_imag(); void input...
error LNK2019: unresolved external symbol "public: __thiscall Complex::Complex(void)" (??0Complex@@QAE@XZ) referenced in function _main Reading and understanding the error message is a very important skill to learn to get ahead. "Unresolved external" is an error message that the linker produces when it sees ...
4,775,633
4,775,661
Smart Pointers, Forward Declaration, and C4150
So as part of a large hobby learning project I have implemented a mostly complete smart pointer implementation. It does practically every thing I ask of it, except for one minor detail that may prove to be a deal-breaker if I can't solve it. Contrived Example: //Header1.h #include <Header2.h> class A { //Methods an...
So how does boost deal with this issue? Boost deals with this issue by using checked_delete instead of delete inside the smart pointer class template, thus requiring the complete definition of A.
4,775,887
4,782,895
(mac c++ development), for a dynamic library, where does one specify the install_name in a Makefile.am script?
I'm building a project using the gnu autotools on the mac. Everything compiles fine but I'm having issues linking in with dynamic libraries. How do I specify install_name in my Makefile.am scripts. I thought it might be something like the following: lib_LTLIBRARIES = libphysics.la libphysics_la_SOURCES = Physi...
After hacking around, it seems that the correct entry in the Makefile.am file should be: AM_LDFLAGS= @LDFLAGS@\ -Xlinker -rpath -Xlinker "`pwd`/.libs"\ -Xlinker -install_name -Xlinker "`pwd`/.libs/libphsyics.0.dylib" I don't know why this works. The trick was to add pairs of '-Xlinker' fl...
4,776,010
4,776,051
pass by reference and value with pointers
I don't understand why passing a pointer to a function doesn't change the data being passed in. If the function proto looked like this: void func( int *p ); and func allocated memory to p, why can't it be used outside of the function? I thought that pointers were addresses?
Whilst something like this does what you expect: void func(int *p) { *p = 1; } int a = 2; func(&a); // a is now 1 this does not void func(int *p) { p = new int; } int *p = NULL; func(p); // p is still NULL In both cases, the function works with a copy of the original pointer. The difference is that in the ...
4,776,110
4,776,155
Can you use the size of a vector as a length of an array?
I have an std::vector defined as: std::vector<glm::vec3> faces; And I want to use the size of that vector as the length of an array of floats. Right now I'm trying to do it like this: float vertices[faces.size()][3]; But I keep getting errors saying that you must use a constant value. I thought maybe it was because t...
Why do you want to use a C array anyway? A vector would be much more apt here. vector<vector<float> > vertices(faces.size(), vector<float>(3)); And if you already know the size of the inner vector and its size is fixed, it’s a safe bet that a struct would be better suited than a vector here: struct vertex { float ...
4,776,114
4,776,203
What's with these g++ "multiple definition" errors?
I'm in the early stages (read:just started yesterday) of a project, and I'm setting up my initial makefile. It's very simplistic. Here's the full contents of the file: all: main.o resource.o g++ -o output.exe main.o resource.o main.o: main.cpp main.h resource.h g++ -mwindows -o main.o main.cpp resource.o: res...
You're missing the -c argument to g++ when you're compiling a .cpp file to an .o file . As it is now , you're trying to create one executable from another one. g++ -mwindows -o main.o main.cpp should be g++ -mwindows -c -o main.o main.cpp While at it, add warning flags as well, at least -Wall
4,776,164
4,776,224
C++ vector<vector<double> > to double **
I'm trying to pass a variable of type vector<vector<double> > to a function F(double ** mat, int m, int n). The F function comes from another lib so I have no option of changing it. Can someone give me some hints on this? Thanks.
vector<vector<double>> and double** are quite different types. But it is possible to feed this function with the help of another vector that stores some double pointers: #include <vector> void your_function(double** mat, int m, int n) {} int main() { std::vector<std::vector<double>> thing = ...; std::vector<d...
4,776,231
4,779,066
Animating to an array
I have an Arduino, and I am trying to find the most efficient way to animate pixels in an array. The array is represented by 3 arrays of 30 uint8_ts. (30 pixels * R+G+B levels 0-255). What is the best way to move pixels down the array independently? This is a memory limited environment (2 KB RAM), and the array takes u...
How about a function like this? int pixelAt(int index, int min, int max, int a, int b, int b_2) { int pixel = -1; if (min <= index && index <= max) { pixel = a * index + b; if (i % 2) { pixel += b_2; } } return pixel; } Then you would have: for (int i =...
4,776,247
4,776,266
variable initialization within an if statement blocks
Every time I initialize a variable within an if-statement's blocks and its else's blocks, and use it afterward, the compiler spits an error: the variable isn't declared. For example: if (/*Some expression*/) int a=5; else int& a=c; //... a++; // Variable not declared My compiler would say that a is not declared....
Variables in C++ have a specific type; a cannot be an int sometimes, and an int & at other times. So there is no way that your code would ever make sense. And as you've already found, the "scope" of variables is limited to the block they were declared in. Without knowing what you're trying to solve, I can't really be...
4,776,355
4,776,388
Does WPF Work with C++?
My understanding is that Microsoft Visual Studio was rewritten to use WPF. I'm still not clear on why, but acknowledge my knowledge about WPF is very limited. My question is if anyone knows how much support WPF has for C++, and if Visual Studio is still written in C++. Personally, WPF primarily appears to be .NET/VB/C#...
You can use WPF with C++/CLI. It is a .NET API, however, so it requires the .NET Framework. That being said, the designer support is non-existent with C++. This means that, for practical purposes, WPF doesn't really work with C++. Typically, the user interface layer is written in C# (or VB.NET), then calls into C++ c...
4,776,446
4,776,723
Is it waste of time to develop unmanaged C++ library which like .NET framework class library in design and architecture?
There a lot of C++ class libraries either open source or commercial like MFC, ATL, SmartWin++, QT. but none of them has the design and the architecture and the purity of .NET framework class library. What about the idea of implementing C++ library that is like .NET framework class library and provide the developers wit...
Interesting question. But I believe it would be either a waste of time or not optimal to re-create the .NET BCL (base class library) for unmanaged C++. Why is that? The C++ language is quite different from the .NET languages. This means that if you were to re-write the BCL for C++, you would optimally try to make the ...
4,776,466
4,776,487
Confusion over typedef struct in C++
I have a program my professor wrote that simulates the way the memory writes to the L2 cache. It has a couple of places where I'm supposed to fill in the blank. The first thing I'm supposed to do is clear the valid bit of each cache entry. He has given us the following: //number of cache entries (2^11) #define L2_NUM_...
typedef struct is redundant in C++, as are the #define I'm seeing, they could be static const int. In order to clear them all, you would want to do for(int i = 0; i < L2_NUM_CACHE_ENTRIES; i++) l2_cache[i].v_d_tag &= 0x80000000;
4,776,646
4,778,343
Graph theory - switching tree members
I cannot decide, how to define a graph in C++. Right now, i have 2-dimensional array: A - B,D B - A C - D D - A,C But my troubles comes when i want to switch some "members" of the graph (e.g. D and A). I know i need something like this (which i can manually recognize from the graph): A - C,D B - D C - A D - A,B But...
There are two common way to represent a graph in data. The first is a set of pairs where the first and the second are both vertices. If the pair exists, then an edge exists btween the two vertices in the pair: std::set<std::pair<int, int> > setMyGraph; The second uses a data structure known as an adjacency matrix. The...
4,776,726
4,776,746
What are the best ways to wrap C function and function pointer in C++?
I'm working on a project with openGL, and I want to wrap all the C function, function pointers with a higher level of abstraction using C++ STL and boost. I checked boost::function, but it was designed to work with functor instead of function pointers. I wonder if there is a C++ idiom help to wrap C function calls inst...
Boost Function also works with function pointers see http://www.boost.org/doc/libs/1_45_0/doc/html/function/tutorial.html#id1264511
4,776,813
4,776,882
Inconsistencies with double data type in C++
This may be something really simple that I'm just missing, however I am having trouble using the double data type. It states here that a double in C++ is accurate to ~15 digits. Yet in the code: double n = pow(2,1000); cout << fixed << setprecision(0) << n << endl; n stores the exact value of 2^1000, something that is...
You will need eventually to read the basics in What Every Computer Scientist Should Know About Floating-Point Arithmetic. The most common standard for floating-point hardware is generally IEEE 754; the current version is from 2008, but most CPUs do not implement the new decimal arithmetic featured in the 2008 edition....
4,777,025
4,777,061
visibility of friend functions when creating functors
See the code below. The drive() is in the scope, I can drive the porsche. However, unless I uncomment the declaration of drive(), g++ gives a very weird ‘drive’ was not declared in this scope error when trying to create the functor. Why? #include <functional> class car { friend void drive(const car c); }; //void ...
When you declare a friend function with an unqualified id in a class and that function is not a member of another class, it names a function in the nearest enclosing non-class, non-function prototype scope. If that function hasn't previously been declared then the friend declaration doesn't make that function visible i...
4,777,063
4,779,337
chroma key with openframeworks/opengl
I need to implement chroma keying (removal of a solid color background) in an openFrameworks application. I'll be playing many (10 or more) videos simultaneously (in the same frame), and drawing them to the screen along with alternate backgrounds. I can achieve a chroma-key-like effect by iterating through each frame'...
You could use glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_DST_ALPHA) and then when you enable blending, you could use a pixel shader to do what you want if the pixel is of specific color (set alpha to 0).
4,777,069
4,777,082
How to handle STL container with elements of classes containing large arrays of data
I am looking for a way to put large arrays of data (stored inside a class holding basic functionality like checks on the data, size etc) into any STL container, like a vector or a queue (FIFO queue is best since I have a producer and a consumer). The problem is that I have to implement the copy constructor and.. well.....
Boost has a shared_array class that is like shared_ptr but will use delete[], or you can add a custom deleter to shared_ptr that will make it call delete[].
4,777,153
4,777,160
Is it possible to convert all regular programming tasks to compile time using meta-programming?
I read about meta-programming, and found it was really interesting. For example, check to see if the number is prime, calculate fibonacci number...I'm curious about its practical usage, if we can convert all runtime solution to meta-programming, the the application would perform much better. Let's say to find max value...
You can't because metaprogramming only works for inputs that are known at compile time. So you can have a metafunction that calculates a Fibonacci number given a constant known at compile time: int value = Fibonacci<5>::Value; But it won't work for values that are inputted by a user at runtime: int input = GetUserInpu...
4,777,207
4,777,218
Get part of a char array
I feel like this is a really silly question, but I can't seem to find an answer anywhere! Is it possible to get a group of chars from a char array? to throw down some pseudo-code: char arry[20] = "hello world!"; char part[10] = arry[0-4]; printf(part); output: hello So, can I get a segment of chars from an array like...
In short, no. C-style "strings" simply don't work that way. You will either have to use a manual loop, or strncpy(), or do it via C++ std::string functionality. Given that you're in C++, you may as well do everything with C++ strings! Side-note As it happens, for your particular example application, you can achieve ...
4,777,259
4,777,321
CreateProcess, first parameter question
I am trying to create a process called s2.exe. However I'm having trouble figuring out what needs to be passed in as the first argument. I tried putting the name and location of where the process would be located but I get "Error 2 starting CC". What exactly should go in the first parameter? (According to MSDN it is t...
A value of 2 returned from GetLastError() indicates ERROR_FILE_NOT_FOUND. You need to pass in c:/s2.exe, assuming that s2.exe is actually in the c:\ drive. Note that the MSDN documentation for the lpApplicationName parameter in CreateProcess() says: The string can specify the full path and file name of the module to e...
4,777,266
4,777,305
Goto before variable initialization causes compiler error
Consider this code (VS2008): void WordManager::formatWords(std::string const& document) { document_ = document; unsigned int currentLineNo = 1; size_t oldEndOfLine = 0; size_t endOfLine = document_.find('\n'); while(endOfLine != std::string::npos) { std::string line = document_.subst...
You are skipping over the construction of the words array: if(line.size() < 2) goto SkipAndRestart; std::vector<std::string> words = Utility::split(line); // ... SkipAndRestart: You could have used words after the SkipAndRestart: label, which would have been a problem. You don't use it in your case...
4,777,360
4,777,380
How to assign a C struct inline?
typedef struct { int hour; int min; int sec; } counter_t; And in the code, I'd like to initialize instances of this struct without explicitly initializing each member variable. That is, I'd like to do something like: counter_t counter; counter = {10,30,47}; //doesn't work for 10:30:47 rather than counter....
Initialization: counter_t c = {10, 30, 47}; Assignment: c = (counter_t){10, 30, 48}; The latter is called a "compound literal".
4,777,394
4,777,446
Visual-Studio tutorial on how to make all code in one directory and all sln and proj stuff in another?
So what I want is to develop a project easily portable / compilable across diffident platforms. I use only crossplatform libs. But My First priority currently is windows os so I am using Visual Studio for main development. Structure I Want to achieve looks like: !MainFolderForSolution !SolutionBuildDebugFolder ...
You might want to consider using CMake. It supports out of place builds (which supports a directory structure similar to yours), but also would assist in automatically generating and maintaining your other build settings, such as Qt or makefile based builds for cross platform development.
4,777,701
4,777,749
Linker Error - Friends and left-hand-side. (no templates)
This is the line that is throwing the error in the program: (s and u are statistician objects) s = 2*u; error C2678: binary '*' : no operator found which takes a left-hand operand of type 'int' (or there is no acceptable conversion) This is the header file: #ifndef STATISTICIAN #define STATISTICIAN namespace main_sav...
It seems you've rightly recognized that you need to provide another overload with double on the left-hand side. The op* overload with (statistician, double) does not work for (double, statistician). When I uncomment the two operators in the header and the implementation, it gives linker errors. Your project settings...
4,777,854
4,778,090
Help me insert entries into a C++ std map
map<int, BasicBlock*> basicBlocks; // in my header file basicBlocks.insert(std::pair<int, BasicBlock*>(pc, bb)); where pc is an integer and bb is a BasicBlock: (earlier) BasicBlock *bb = new BasicBlock(pc); that is from earlier in the code. I get this error: error C2664: 'std::pair<_Ty1,_Ty2>::pair(const std::pair...
You have the line: basicBlocks.insert(new BasicBlock(pc)); This is trying to insert a BasicBlock* into the map, not a pair. Did you mean: basicBlocks.insert(std::make_pair(pc, new BasicBlock(pc)) );
4,777,881
4,777,897
Maintaining an Ordered collection of objects
I have the following requirements for a collection of objects: Dynamic size (in theory unlimited, but in practice a couple of thousand should be more than enough) Ordered, but allowing reorder and insertion at arbitrary locations. Allows for deletion Indexed Access - Random Access Count The objects I am storing are n...
Original answer: That sounds like std::list (a doubly linked list) from the Standard Library. New answer: After your change to the specs, a std::vector might work as long as there aren't more than a few thousand elements and not a huge number of insertions and deletions in the middle of the vector. The linear complexi...
4,777,909
4,777,940
How does one maintain memory with the putenv system call?
The POSIX system call putenv states that the allocated memory string cannot be freed by the caller after the call to putenv. Therefore, you cannot call putenv with an automatic variable. Example: #include <cstdlib> #include <cstring> #include <unistd.h> int main() { char envVar[] = "MYVAR=Value"; // putenv(env...
Don't use putenv() if you are worried about the memory leaking. That's why POSIX provides setenv() and unsetenv() as well - those take control of the memory and manage it. Quoting the putenv() manual page (URL above): The putenv() function shall use the string argument to set environment variable values. The string a...
4,777,935
4,777,947
How to use NDK? Starting with 'hello world' app
I would like to see a 'Hello world' program written in C/C++ but made to run on Android. I know this is possible by using NDK and JNI calls. But not able to make it work. No guides online are helpful. Need to know to to get started. I am developing on Windows 7 machine and also using Eclipse for ease. Android installat...
There are samples in the android-ndk-r5 folder + there is a nice step-by-step tutorial: https://developer.android.com/ndk/samples/index.html No excuses, dude. You just have to read (take a look at the Exploring the hello-jni Sample section).
4,778,216
4,778,544
Doxygen Out of Line Documenting for C++ Class Operators
If I have a class in a file I can't change, but I need to document in doxygen, what is the best way to do it? I know it would be best to document in the actual .h or .cpp file, but in this specific instance, that is not possible. I have figured out how to document some members, but I cannot document operators in a reli...
If you look at your doxygen output, there should be a warning /path/to/Documentation: warning: no matching class member found for Foo::operator!() Possible candidates: bool Foo::operator!() const in which case, change your documentation to /// @fn Foo::operator!() const /// @brief Some info about the operator /// ...
4,778,365
4,778,447
Is Returning by Reference Useless?
Coming from a C# background, I was more or less puzzled by the seemly weird behavior of returning method handling in C++. My concern now is for a method in C++, returning by reference is not a very useful technique, this is because-- unlike C#--any variable declared inside a method body will go out of scope once the th...
The only time where returning by reference is useful is when you are returning a reference to an existing data member in a class, or you are returning a reference to an element inside a parameter of the method. Loosely speaking, true. The variable might not be "owned" by the class (as in tied to its lifetime): it co...
4,778,552
4,787,077
Is it possible to enable array bounds checking in g++?
Is it possible to have g++ show an error when compiling the following file with some flag? #include <iostream> using namespace std; int main() { int arr[ 2 ]; cout << arr[ 4 ] << endl; return 0; } I saw some things like gcc -Wall -O2 main.c which only works with C, not C++.
You can use a static analyser such as Cppcheck. When run on your above code: $ cppcheck --enable=all test.cpp Checking test.cpp... [test.cpp:6]: (style) Variable 'arr' is not assigned a value [test.cpp:8]: (error) Array 'arr[2]' index 4 out of bounds You can integrate Cppcheck into your build procedure and consider y...
4,778,644
4,778,684
C++ illegal digit, simple issue
I'm running against this error: int temp = 0789; error C2041: illegal digit '8' for base '8' For what I can understand is that the compiler understands any number that begins with 0 like 0123 to be octal. But how can I tell the compiler to just take it with the 0 in front?
http://msdn.microsoft.com/en-us/library/00a1awxf(v=vs.80).aspx Great resource about this. 0xff is hex 0123 is octal 123u is unsigned ..lots more...
4,778,709
4,778,724
Comma operator in a conditional
I have read in a lot of places but I really can't understand the specified behavior in conditionals. I understand that in assignments it evaluates the first operand, discards the result, then evaluates the second operand. But for this code, what it supposed to do? CPartFile* partfile = (CPartFile*)lParam; ASSERT( part...
In this case, it is an unnecessary expression, and can be deleted without changing the meaning of the code.
4,778,750
4,786,599
Irritating Text Wrapping with GDI & Direct3D
If I use Direct3D's DrawText, which behaves like the GDI counterpart, and I enable the DT_WORDBREAK formatting flag, it'll cut the text on apostrophes whenever the situation arises, which leaves many titles and text displays looking like a mess. For instance, it will appear as: The Horseman' s Head When it should s...
You can wrap manually with the help of the GetTextExtentPoint32 function.
4,778,762
4,778,810
C++ String to double atof conversion losing precision?
C++ is not my language so forgive this simple problem. I'm losing precision in an atof conversion from string to double, can anyone help? string lAmount; string lSuspendedInt = "131663.51"; string lAccruedInterest = "0.0"; double dSuspendedInt= atof(lSuspendedInt.c_str()); //PROBLEM HERE? double dAccruedInterest = a...
The problem is your %g format operator, which isn't specified with enough precision. You might want %.2f instead, which prints two digits after the decimal point.
4,778,797
4,789,710
Setting seed boost::random
I would like to reset random sequences by using different seed numbers. When running this test code: boost::mt19937 gener(1); boost::normal_distribution<> normal(0,1); boost::variate_generator<boost::mt19937&,boost::normal_distribution<> > rng(gener, normal); cout << rng() << endl; cout << rng() << endl; cout << rng() ...
Following Jim, Alan and Igor suggestions made some changes to the code: rng.engine().seed() instead of gener.seed(), and called rng.distribution().reset() after the call to rng.engine().seed() and it worked like a charm. Many thanks!
4,778,805
4,778,829
Why hasn't sort_heap put the elements in the order I expected?
Given the following code: // range heap example #include <iostream> #include <algorithm> #include <vector> using namespace std; bool Greater(int a, int b) { if (a > b) { return true; } else { return false; } } int main () { int myints[] = {10,20,30,5,15}; vector<int> v...
sort_heap only sorts the range if it is heap-ordered according to the provided comparator. Since you used Greater as the comparator in all the heap operations, you don't have the elements in heap order according to the default comparator, so sort_heap isn't guaranteed to work correctly. The regular sort algorithm sho...
4,778,823
4,787,083
Why does Windres report a syntax error on my GROUPBOX statement?
I'm experimenting with the Win32 API in C++, specifically with writing resource files. Now, my entire project was working just fine, menus and titles and everything. However, when I add this code for a modal dialog box to the .rc file: IDD_ABOUT DIALOG DISCARDABLE 0, 0, 239, 66 STYLE DS_MODALFRAME | WS_POPUP | WS_CAPT...
If you still have the same syntax error on the same line after switching to a DIALOGEX statement (as @YeenFei pointed out), the only thing I can think of is that IDC_STATIC is not defined. Try changing it to GROUPBOX "About this program...",-1,7,7,225,52 If that fixes the problem, it's because the identifier isn't def...
4,778,978
4,779,510
Which language should I stick with
I've got good experience in Java and web development with some experience in C++ also. Lately, I've been thinking of leaving Java (bored with it) for C++. Then came Python(didn't like Ruby). I find it too good to resist and started using it. But the C++ still stays in my mind. Now I want to "stick" with one language t...
I have mostly experience in a few of domain-specific languages and a few general purpose languages (C, C++, Java, Delphi, etc.), and I have no experience with Python (only a general idea of it). You must not judge languages on a basis of how hard they are. You say you have to consider the fact that you have to spend ti...
4,779,348
4,779,475
Fast Reading and Writing of Data to/from a file
I have an application, which in initialization creates a graph and I perform an all-pair shortest path on that graph and use the results later. As the graph is quite big, this takes pretty much time around 10-12 minutes, and the graph which I create is same everytime, so I can calculate the matrix once, dump it and re...
The number of options available depends on the operating system. In virtual memory systems, there is usually a way to map a portion of memory space to a file and have it automatically transfer pages back and forth as required. In most operating systems with file systems, increasing the file buffer can dramatically imp...
4,779,401
4,779,570
Call template function from within a template class
GCC will not compile following code snippet (which in fact is correct behavior of GCC as it is conform to the standard C++ as I have learned already. VC++ however will compile.) template<class T> void CUDAMemory1D2DTextureAllocator<T>::allocateMemoryOnDevice() { m_pChannelDesc = cudaCreateChannelDesc<T>(); ... ...
You can call it directly like: cudaCreateChannelDesc<T>() if it doesn't belong to any class or namespace. Isn't it working like that?
4,779,606
4,780,300
Window does not get displayed(Maximized) after Minimizing
I have a Windows CE application which logs key strokes of the mobile device. There's a button to initialize the recording functionality, which forces the main window to minimize by calling: ShowWindow (hWnd, SW_MINIMIZE); Before minimizing the window, I register to the trigger button event (via a custom API). While th...
Showwindow could fail by several reasons. You could try: 1) Set foreground SetForegroundWindow For WinCE specifically refer to the following MSDN article. http://msdn.microsoft.com/en-us/library/ms940024.aspx SetForegroundWindow((HWND)(((ULONG) hwnd) | 0x01) ); 2) Bring to front BringWindowToTop http://msdn.microso...
4,779,759
4,781,964
How to determine inter-library dependencies?
My project consists of a couple of static libraries, which are linked together in a final step. Now I have the problem, that the link order of the library is important (otherwise I get an undefined symbol linker error). Sometimes I run into the problem, that I have to re-sort the linked libraries (-lcommon -lsetup -lco...
Another option to link libraries with circular dependencies is to use a special linker option for that. Man ld: -( archives -) --start-group archives --end-group The archives should be a list of archive files. They may be either explicit file names, or -l options. The specified archives are...
4,779,779
4,779,818
Array declaration at the end of a struct?
I just came across some code which declares a struct within a C++ class as follows: struct T { int data; T* next; } array[0]; What does this kind of declaration do? What effect does putting "array[0]" at the end of the struct defintion have?
Ahh, it's almost a "flexible array member". It was formalized in C99, but it's an old C trick that creates a dynamic array. Allocate more memory for the object and you can store more elements in the array. I think the use of a specific 0 there is a compromise, as actual [] flexible arrays were not in C89 or C++. The m...
4,779,857
4,779,961
where is c++filt source code?
Does anyone known the link of c++filt source code. I want call c++filt in my code as a library.
On Linux you can use /usr/include/demangle.h which comes with binutils-dev package. You'll have to link to the libiberty from binutils.
4,779,915
4,814,695
Copy Content of Hosted Silverlight Control
EDIT: Since my original problem was due to my mistake I will rephrase this question. Im hosting a Silverlight in a window inside my C++ application based on the code found here. Now I'd like to copy the content of the control to memory in order to use the content inside my own renderer. The problem I have is that when ...
I will start researching this, I have an idea that OpenCL or perhaps since you are using Silverlight, DirectCompute may be able to set up a context where you can have more flexibility. One way would be to simply do all GPU acceleration in one of those languages. Meanwhile I'll try to find out if you can use one of them...
4,779,994
4,780,597
Why doesn't valgrind detect a memory leak in my "test" program?
The entire test code is contained in main.cpp as follows: #include <iostream> using std::cout; using std::endl; void f(int i) { int* pi = new int; *pi = i; std::cout << "*pi = " << *pi << std::endl; } int main(int argc, char *argv[]) { int i = 0; while (i < 10000) { f(i); ++i; ...
The reason this happened is that the call to: valgrind --leak-check=yes test was actually running valgrind on /usr/bin/test which is a built in program that checks file types and compares values, all I needed was: valgrind --leak-check=yes ./test
4,780,067
4,780,204
Object Slicing in c++
class Base { int iBase; public: virtual void display() { cout<<"I am a Base Class"<<endl; } }; class Derived : public Base { int iDerived; public: Derived() { cout<<"In Derived Def...
C++ has virtual functions, but no virtual data. You could add the following to simulate it: class Base { // What you had before virtual int getAnInt() const = 0; // =0 means that Derived must implement this }; class Derived { // What you had before virtual int getAnInt() const { return iDerived; } }; Object s...
4,780,119
4,780,134
2D Euclidean vector rotations
I have a euclidean vector a sitting at the coordinates (0, 1). I want to rotate a by 90 degrees (clockwise) around the origin: (0, 0). If I have a proper understanding of how this should work, the resultant (x, y) coordinates after the rotation should be (1, 0). If I were to rotate it by 45 degrees (still clockwise) in...
you should remove the vars from the function: x = x * cs - y * sn; // now x is something different than original vector x y = x * sn + y * cs; create new coordinates becomes, to avoid calculation of x before it reaches the second line: px = x * cs - y * sn; py = x * sn + y * cs;
4,780,202
4,814,897
External makefile to call Eclipse CDT's generated makefile - according to Debug\ Release config
I'm using Eclipse CDT on Linux to build a c++ executable and several static libraries which the executable depends on. Everything is good - Eclipse generates the makefiles for both Debug and Release as expected. However, I want to compile this code also on a computer without Eclipse installed, so I thought to write a s...
With this in your makefile you can invoke 'make debug' or 'make release' to build all the projects in the required mode : config: cd Lib1/$(CONFIG) && make all ... cd LibN/$(CONFIG) && make all cd Exec/$(CONFIG) && make all debug: make config CONFIG=Debug release: make config CONFIG=Release .PH...
4,780,241
4,780,308
Print out pointer value
I am doing a threading, but i don't know how to print out the pointer value. UINT __cdecl CThreadDlg::func(LPVOID pParam) { data *ptr = (data*)pParam; AfxMessageBox(L"You have entered a thread function."); ptr->a = "abc12345"; // char * a AfxMessageBox(???); // what should i put here to pri...
Maybe something like this: CString a; a.Format(_T("%p"), ptr->a); AfxMessageBox(a); Edit: to get value 'ptr->a' points to: a.Format(_T("%s), ptr->a);
4,780,252
4,780,294
Reading File tags/properties in c++
I know there are file comparison tools out there to determine whether files were added, deleted, or modified when comparing between two folders. However, I'm wondering how you would approach reading the file properties programmatically to see when the file is created/modified/accessed (like how you can find these infor...
use the file info class of my current library of choice, for example: QFileInfo
4,780,263
4,781,137
Lzz (Lazy C++) - #include file not found
I am trying to use Lzz to generate C++ header files from my *.cpp files. The calling sequence is something like this: ./lzz -hx hpp -c -o out src/*.lzz Unfortunately, it always fails saying it couldn't find any included headers, including parts of the standard library such as iostream, string and vector. I get a bunch ...
Enclose your #includes with #hdr ... #end The delimited lines are copied verbatim to the header file.
4,780,316
4,780,422
Easiest way to build a cross-platform application
I have read a few articles in the cross-platform tag. However, as I'm starting a fresh application (mostly a terminal/console app), I'm wondering about the easiest way to make it cross-platform (i.e. working for Linux, Mac OS X, and Windows). I have thought about the following: adding various macro/tags in my code to ...
Do not go the first way. You'll encounter a lot of problems that are already solved for you by numerous tools. Qt is an excellent choice if you definitely want C++. In fact, it will speed up development even if you aren't familiar with it, as it has excellent documentation and is easy to use. The good part about it is ...
4,780,410
4,780,467
Secure C++ coding practices
I am looking for a comprehensive record of secure coding practices in C++. Since i haven't found such a list existing here already we might as well make this into a community wiki, for further reference. I am looking for solutions to security issues like stack and heap based buffer overflows and underflows, integer ove...
The book Writing Secure Code (only sample pages in this link) is very good at explaining security issues and how to avoid them. The book has been out for a while, but most of the topics covered are still relevant.
4,780,869
4,780,927
Custom Command Line Parameters
I have a problem with command line parameters. I finished the program so I can start it like this from command line: program.exe test.txt copy_test.txt Basically, my program does the following : inputs some text file sorts it and copy to a new text file BUT (always that but?!), I should start the program from comman...
Well, with your new format arguments, you can't just pass them as-is to the stream constructors. You will have to check if they start with a specific string, such as with strncmp and then pass the address of the relevant bit such as argv[1]+8 for the input type. Since you're providing --input= type prefixes, you may al...
4,781,068
4,781,161
TinyXML Debian Installation
Can someone give me some instructions on how to install TinyXML (or TinyXML++) to debian so I can use it from within my C++ app. I've never installed a library before so I have no idea what to do. Thanks
on the command line: sudo apt-get install libtinyxml-dev should be all you need alternatively you could use a gui packet manager (if your distro has one) and search for tinyxml
4,781,134
4,781,156
Using STL map for searching for points lying in a rectangular area?
I have with me a lot of x,y points and each x,y point has some extra data associated with it. This extra data I'll be storing in a struct. My application requires that given any one point, I'll have to find how many other points lie within a rectangular area surrounding this point (this point is at the centre of the re...
This is a typical application for a quadtree. The quadtree facilitates lookup of the m points lying in your rectangle in O(log(n) + m), where n is the total number of points. Edit: Your approach using the map is not nearly as efficient. For randomly distributed points, it would have an O(sqrt(n)) average complexity, ...
4,781,264
4,781,281
Usage of static keyword in C++
I have a class exposing a static function in myclass.hpp class MyClass { public: static std::string dosome(); }; Well, in myclass.cpp what should I write: this: std::string MyClass::dosome() { ... } or this: static std::string MyClass::dosome() { ... } I guess I should not repeat the static keyword... is it...
C++ compiler will not allow this: static std::string MyClass::dosome() { ... } since having static in a function definition means something completely different - static linkage (meaning the function can only be called from the same translation unit). Having static in a member function declaration is enough.
4,781,283
4,781,296
std::remove not working correctly, still has extra elements
std::vector<int> v = {1,2,3,4,5}; auto i = std::remove(v.begin(),v.end(),3); for(auto j = v.begin(); j!= v.end();++j) std::cout << *j; Actual output : 12455 Where does extra 5 come from? Desired output : 1245 How to achieve this?
remove doesnt actually remove the elements Remove removes from the range [first, last) all elements that are equal to value. That is, remove returns an iterator new_last such that the range [first, new_last) contains no elements equal to value. 1 The iterators in the range [new_last, last) are all still dereferenceabl...
4,781,361
4,781,393
Which UML diagram is correct for Chain of responsibility pattern?
I am trying to draw UML diagram for Chain of responsibility pattern. I am referring the sites http://www.vincehuston.org/dp/chain.html and http://www.dofactory.com/Patterns/PatternChain.aspx In Vincehuston diagram, there is a self loop at base class, because Base class needs to have a pointer to next handler object. I...
The only difference I see between the two explanations is where the pointer to the next handler is (base handler class or concrete implementation) which should be represented on the base class as it will be inherited in every instance. So from my point of view vincehuston representation is more accurate. If you look at...
4,781,594
4,786,206
Trying to modify read-only DataSet field
I use C++ Builder 6.0 I use TADODataSet execute following SQL statement: SELECT Id, SUM(Saldo) AS Saldo FROM Table GROUP BY Id I use this DataSet only for reporting. No need update date back to database. When I try to modify field "Saldo" adospCard->Edit(); adospCard->FieldByName("Saldo")->AsFloat=0.0; adospCard->Po...
Add a calculated field to your dataset. Calculate the right value for Saldo in this calculated field (you can use Saldo as source for it if you want to) display this calculated field in your report in stead of the Saldo field. Edit: For examples of how to add calculated fields, see for instance here, here and here. -...
4,782,204
4,782,247
Qt 4.6 + MinGW: suppress warnings for generated code
We are using Axis2 (WSDL2C) to generate *.c/*.h files from WSDLs in order to be able to call webservices with Qt 4.6. But the generated code creates a massive amount of warnings (3 services -> >1k warnings), mostly about uninitialized or unused variables. How can we suppress these warnings properly? I know I can wrap h...
Add this line to your Qt .pro or .pri file: QMAKE_CFLAGS += -Wno-unused It turns off unused warning.
4,782,628
4,782,684
How should I properly initialize a C struct from C++?
I have the following code in a C++ file: #include <sys/socket.h> // ... void someFunc() { struct msghdr msg = {0}; // <<< Uninitialized member here } When I compile with g++ using -Wall -Wextra, I get warnings: error: missing initializer for member 'msghdr::msg_namelen' ...same for several other fields My probl...
Do this: void someFunc() { msghdr msg = {}; // <<< All members zero-initialized } The g++ -Wextra warning level is IMHO not very useful. The code that you have is also formally OK for a "C struct", in standardeese known as POD (plain old data structure). But your code explicitly initializes the first member with ...
4,782,673
4,782,689
What does "const char far* inStrSource" mean?
I'm following article about boot loader, ( http://www.codeproject.com/KB/tips/boot-loader.aspx?msg=3745692#xx3745692xx ) and I found this part: "const char far* inStrSource" Whole thing: typedef unsigned char byte; typedef unsigned short word; typedef unsigned long dword; typedef char bool; byte CSt...
It's a far pointer: a pointer which can be longer (ie: take more bits) than normal pointers. It's used to refer memory cells which couldn't be addressed by normal pointers (ie: if pointers on your systems are made of 8 bits, you can only refer up to 2^8 memory cells; if you need to address more memory you could use a f...
4,782,692
4,782,809
what does `using std::swap` inside the body of a class method implementation mean?
I was trying to learn and adopt the copy-swap idiom following this thorough explanation on this question: the Copy-Swap Idiom. But I found some code I had never seen: using std::swap; // allow ADL in this example class dumb_array { public: // ... void swap(dumb_array& pOther) // nothrow { using std...
This mechanism is normally used in templated code, i.e. template <typename Value> class Foo. Now the question is which swap to use. std::swap<Value> will work, but it might not be ideal. There's a good chance that there's a better overload of swap for type Value, but in which namespace would that be? It's almost certai...
4,782,714
4,782,874
GCC vs MS C++ compiler for maintaining API backwards binary compatibility
I came from the Linux world and know a lot of articles about maintaining backwards binary compatibility (BC) of a dynamic library API written in C++ language. One of them is "Policies/Binary Compatibility Issues With C++" based on the Itanium C++ ABI, which is used by the GCC compiler. But I can't find anything simila...
First of all these policies are general and not refer to gcc only. For example: private/public mark in functions is something specific to MSVC and not gcc. So basically these rules are fully applicable to MSVC and general compiler as well. But... You should remember: GCC/C++ keeps its ABI stable since 3.4 release and ...
4,782,757
4,782,927
Rule-of-Three becomes Rule-of-Five with C++11?
So, after watching this wonderful lecture on rvalue references, I thought that every class would benefit of such a "move constructor", template<class T> MyClass(T&& other) edit and of course a "move assignment operator", template<class T> MyClass& operator=(T&& other) as Philipp points out in his answer, if it has dyna...
I'd say the Rule of Three becomes the Rule of Three, Four and Five: Each class should explicitly define exactly one of the following set of special member functions: None Destructor, copy constructor, copy assignment operator In addition, each class that explicitly defines a destructor may explicitly define a move c...
4,782,793
4,880,264
fcam - n900 - mysterious reboot
I wrote an application to take pictures and well it takes pictures, but it also randomly reboots. How can I determine what caused it? Do I need to observe FCam events or can I just write a simple application that takes pictures? Walter
there are few causes of reboots and hints where to look for, related to camera on N900/Maemo5: (huge) memory leaks mentioned above by Walter may drain your swap and cause reboot there is HW watchdog which fires when some binary app messes heavily with pointers, array boundaries, etc and hangs CPU on itself (then proce...
4,783,132
4,783,234
Pass member function pointers by argument and store them
I'm trying to tackle OOP with a little project of mine. I'm trying to create a simple Menu class (terminal-based) to build, show and execute a menu. And this menu should execute functions from a second class Calendar which is the "main" program. Which interface I try to achieve is: int main() { Menu menu; menu...
Apart the fact that your add function should read: void Menu::add(std::string option, CalendarPtr ptr) // what doesn't work obviously { // adding string to vector options_strings.push_back(option); // Just binding the latest entry of the string to the function-pointer int index = options_strings.size()...
4,783,404
4,784,190
Is main() really start of a C++ program?
The section $3.6.1/1 from the C++ Standard reads, A program shall contain a global function called main, which is the designated start of the program. Now consider this code, int square(int i) { return i*i; } int user_main() { for ( int i = 0 ; i < 10 ; ++i ) std::cout << square(i) << endl; return...
No, C++ does a lot of things to "set the environment" prior to the call of main; however, main is the official start of the "user specified" part of the C++ program. Some of the environment setup is not controllable (like the initial code to set up std::cout; however, some of the environment is controllable like static...
4,783,674
4,783,705
Lookup Table vs if-else
Today I read code using a lookup table instead of if-else for clipping two summed uint8 values. The map is i in i={0...255}, and 255 in i={256...511}. I wondered how big the gain of this might be, and tried to find it out, using gprof, g++ -std=c++0x -pg perfLookup.cpp -O2 -o perfLookup && ./perfLookup && gprof perfLoo...
Well, since src is declared as std::vector<uint8_t>, src[i] is never larger than 255, which is the highest possible value for a 8-bit unsigned integer. Therefore, my guess is that the compiler optimizes the check away. What remains is just the boilerplate loop so the benchmark is meaningless. Provided the check wasn't ...
4,783,781
4,797,405
C++ GDI+ drawing text on a transparent layered window
(unmanaged C++) I already succeeded drawing PNG files to a transparent layered window that I can drag around the desktop, but now my problem is drawing text on a transparent layered window Here's my code and my attempt at drawing text in the middle, it's important to note that i'm using the screenDC instead of using th...
The overall approach looks right, but I think you've got some problems with the DrawString call. Check out the documentation (especially the sample) on MSDN. Gx.DrawString(thetext, 4, NULL, therect, NULL, NULL) The third, fifth, and sixth parameters (font, format, and brush) probably need to be specified. The docum...
4,784,055
4,784,090
Efficient and practical way to generalize struct access?
I have the following: Struct A { char a; char b[10]; int c; float d; } Struct B { float d; char b[10]; char a; int c; bool e; } and I want to make a generic function that accepts struct A or B to access elements like: void SetD(A a, float f) { a.d = f; } There will be many different Struct...
How about: template< typename T > void setD( T &t, float f ) { t.d = f; } Note that the struct keyword is lowercase, and that structs require a semicolor ; after the closing bracket.
4,784,141
4,876,032
SQL request helper for C++
I'm looking for a library that will simplify working with SQL in C++. I'm aware that there are different ORM solutions (like those listed here), and I had a quick look over them, but I'm probably looking for something different (not exactly ORM), so if you could help... I want something that won't encapsulate access to...
Finally I didn't find any library not trying to hide the database access, most of the libraries try to be too much ORM-like. So I just took the DTL bind approach and wrote some text-processing helpers to build SQL requests that I need.
4,784,308
4,784,342
Ensuring template type consistency at compile-time
I have this template class: template <class Tin, class Tout> class Foo { Tin input; Tout output; static inline void __ensure_type_consistency { int16_t* p = (int16_t *)0; // uint16_t* p1 = p; Tin* check_type_in = p; Tout* check_type_out = p; } public: ... } I ...
One simple way: template <class, class> class Foo; template <> class Foo<int16_t, int16_t> { ... }; The other way, if your conditions are actually more complicated, is to use BOOST_STATIC_ASSERT from Boost or static_assert from C++0x. Since you wanted non-Boost options and C++0x may not work, here's something more...
4,784,336
4,784,359
Two decimal places using printf( )
I'm trying to write a number to two decimal places using printf() as follows: #include <cstdio> int main() { printf("When this number: %d is assigned to 2 dp, it will be: 2%f ", 94.9456, 94.9456); return 0; } When I run the program, I get the following output: # ./printf When this number: -1243822529 is assigned t...
What you want is %.2f, not 2%f. Also, you might want to replace your %d with a %f ;) #include <cstdio> int main() { printf("When this number: %f is assigned to 2 dp, it will be: %.2f ", 94.9456, 94.9456); return 0; } This will output: When this number: 94.945600 is assigned to 2 dp, it will be: 94.95 See here for a...
4,784,438
4,784,563
Is there any cross-platform command-line library for C++?
To run a command line using C++, I always use system command. However, I think this way is too error-prone since I only can parse a char* as argument without any other information. So I'm looking for a cross-platform library that works well with command-line? Has anyone known one? Thanks, Chan
Have a look at Boost.Process. It is still work in progress and is not part of the official Boost yet, but looks promising.
4,784,812
4,784,926
What tool/library can help me to generate and test model of neural network that would work with X*Y int arrays as input and N*4 int arrays as output?
I want to make simple neural network that from given gray-scale 2d arrays like [[1 1 1] [0 0 0] [1 1 1]] would give me line coordinates [[1 2] [3 2]] I have a C++ program that has a real algorithm in it to compute lines from gray-scale images and a large set of images. I need some NN tool wit scripting language s...
Here is a quite comprehensive list of nn simulators: Comparison of Neural Network Simulators
4,784,817
4,784,888
What is the preferred way to implement a factory method in C++?
A newbie question: I have a hierarchy of classes with some virtual functions and I am trying to implement a factory method, but I am not sure what is the best way: Return a raw pointer from the factory method and wrap it into a smart pointer in the calling method Return a smart pointer from the factory Return a proper...
Options 3 and 4 are out from the start because they simply don’t work: 3 slices the object, 4 creates memory leaks or invalid references. From the other two methods, I strongly prefer 2: return a smart pointer. In fact, strive to avoid raw pointers completely, if possible. Unfortunately, C++ makes this a lot to write (...
4,784,976
4,785,094
Lax HTML parsing in C++?
I'm looking for a solution for parsing potentially malformed HTML in C++, similar to what Beautiful Soup does in Python. Normally, just using an XML parser would work, but the specific HTML in this case isn't valid XML/XHTML and can't be properly parsed. Do libraries/tools for this exist?
You can use HTMLTidy to transform HTML into valid XML and then use any C++ XML parser availiable
4,784,983
4,785,260
Do I kill a kitten each time I use struct everywhere instead of class?
struct is public by default while class is private by default. Lets take Ogre3D for example; if I change all class occurences with struct, it compiles (I guess), and the engine works just as before. If I'm right, the compiled code is exactly the same as before, because it's only the compiler that does check if a privat...
The difference between struct and class is just the default access level of the bases and attributes, and access levels are only verified at compile time, so you might be tempted to get some library edit the headers and change all class with struct to gain access to the internal details. Don't Compilers are not requir...
4,785,194
4,788,864
how to install or include opengl library GLUT in Turbo C++ folder to run opengl program
My system is running on Windows 7 and my Turbo C++ compiler does not support opengl header files. So the question is what should I do to run the opengl program in Turbo C++ compiler?.
This might help. Good luck!
4,785,207
4,787,346
C++ and inheritance in abstract classes
i have a problem in properly handling method overriding where an abstract class is present inside my classes hierarchy. I'll try to explain: class AbstractClass{ public: virtual void anyMethod() = 0; }; class A : public AbstractClass { void anyMethod() { // A implementation of anyMethod cout <<...
thanks for the answers.. helped me a lot to understand the problem. In effect I posted some wrong code, because i was misunderstanding the real problem. Anyway, i think i partially solved my problem. Here's the code: #include <iostream> `` using namespace std; class Other{ public: void foo(){ cout << "Oth...
4,785,332
4,785,480
Error on adding web reference to WCF service from C++ project
We have WCF service deployed, and attempt to add web reference to it from native C++ project (is written in VS2005) causes an error: Creating web service proxy file for NotificationReceiver1 ... sproxy : error SDL1000 : Unspecified error sproxy : error SDL1002 : failure in generating output file: "NotificationReceiver...
could you try to create it from command line using svcutil like: svcutil.exe /language:cpp /out:NotificationReceiver.h /config:app.config http://localhost:8000/NotificationService
4,785,381
4,785,411
Replacement for MS _vscprintf on MacOS/Linux?
As a learning experience I'm porting some stuff from Windows to MacOS and came across something like this: void SomeClass::someFunction(const char* format, va_list args) { int size = _vscprintf(format, args); // length after formatting std::string s; s.resize(size); vsprintf(&s[0]); ... } Now, as _...
You can use vsnprintf instead; int _vscprintf (const char * format, va_list pargs) { int retval; va_list argcopy; va_copy(argcopy, pargs); retval = vsnprintf(NULL, 0, format, argcopy); va_end(argcopy); return retval; } Thanks to @dbasic for the more complete solution and...
4,785,491
4,785,517
How to use copy_file in boost::filesystem?
I want to copy a file from directory to another, but my program always aborts for some reasons.Has anyone done this this before could tell me what was wrong? And how could I catch exceptions was thrown by copy_file, I checked boost site, but I could not find any relevant information about exception. path user_path( "C:...
You have to provide a path to a file name, not just the directory it resides in.