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,080,267 | 6,080,617 | OpenCV how can i detect webcam and compare the local file to match face | The highlighted code demonstrate openCV framework is loaded in my C code and it render Police watching. Which is just to demonstrate it works very smooth and very clean code to write.
Target:
My webCAM is connected in to the USB port. I would like to capture the live webcam image and match from a local file (/tmp/myfa... | Capturing a video frame is simple just follow this example. The essential part is:
IplImage *img = cvLoadImage( argv[1], CV_LOAD_IMAGE_COLOR );
CvCapture* capture = cvCaptureFromCAM( CV_CAP_ANY );
while ( 1 ) {
IplImage* frame = cvQueryFrame( capture );
//match(img,frame);
}
cvReleaseCapture( &capture );
The s... |
6,080,343 | 16,743,040 | Embeddable document store database | Is there something akin to SQLite but a document-oriented database as opposed to an RDBMS?
Orient seemed to be something similar to what I was looking for, but it is written in Java, and I'm looking for something I can use from C++.
Ideally this would be a serverless system, like SQLite.
| UnQLite
UnQLite is a in-process software library which implements a
self-contained, serverless, zero-configuration, transactional NoSQL
database engine. UnQLite is a document store database similar to
MongoDB, Redis, CouchDB etc. as well a standard Key/Value store
similar to BerkeleyDB, LevelDB, etc.
UnQLite ... |
6,080,542 | 6,081,244 | Calculating critical path of a DAG in C++ | I'm doing the calculation of the critical path for the DAG of the image, according to this algorithm for another post.My teacher requires that aarray be implemented, I simplify the homework statement, a simple graph implemented through arrays.
This es my code in which I have 3 arrays v, u and d, representing the origi... | Your queue contains vertices. Your arrays u, v, d, are indexed by edge numbers.
So you cannot write
first = Q.front();
... u[first] ...
since first is a vertex.
More generally, your code will be a lot easier to read (and the bug will be more obvious) if you use meaningful variable names. first is not very explicit (... |
6,080,643 | 6,080,678 | template for a function | This question was asked to me in an interview:
Lets say you have a function which can take any kind of arguments and any number of arguments.
How would you write a template function for the same?
I do not know the exact answer. could anybody suggest?
| They checked your awareness of the upcoming C++ standard. The new feature is called "Variadic templates" and looks like this:
template<typename... Args> void f( const Args&... args )
{
// do something
}
For a more complicated examples see, e.g. this tutorial.
|
6,080,757 | 6,088,668 | Is OpenGL ES suitable for performing skeletal animations? | I have to start a 3D-Project for mobile platforms. First of all I would like to outline the main aim - skeletal animation. As for the solution I was thinking of OpenGL ES and C++. So the questions are:
Is OpenGL ES robust enough to handle skeletal animation (including those skinning shaders)
Is OpenGL ES supported wid... | Yes, OpenGL ES 2.0 can handle vertex skinning for skeletal animations quite well. OpenGL ES 1.1 used a fixed function pipeline, without shaders, so it's harder in the older API to do this, but 2.0 adds support for shaders. OpenGL ES 2.0 is present on all shipping iOS devices (the iPhone 3G S and newer supports it, in... |
6,080,853 | 6,080,871 | C++: Multiple definition error for global functions in the header file | This function is global and is defined in the header file (temporarily I want to keep it there).
The header file also constitutes a particular class which has inline functions and one of those functions call this global function.
The source file doesn't contain any occurrences of the global function in question.
Any hi... | mark it as inline:
inline void globalfunc() {
}
although doing so means that it will no longer strictly be global - you will get a copy in each translation unit that uses the header, but the linker won't object to this.
|
6,081,161 | 6,081,182 | Is QT the right framework to use for simple 2D game in C++ | I want to create a simple "Mario-like" 2D game. Nothing too fancy, just a some kind of plubmer walking and jumping, some bad guys, user interference, few levels. Is QT the right framework to use? My friend suggested me Irrlicht, but that seems much more for 3D stuff.
Thanks for your ideas!
| I don't think that QT is the right tool for 2D game development in C++, but you can try SDL.
Also, for future game development questions, there's a better StackExchange web site where you can probably get better answers: Game Development.
|
6,081,212 | 6,081,413 | Interesting problem in std::string to str::string.c_str() conversion with file paths | I've ran into an interesting problem. I have the following code:
cout << "\nFILE";
cout << "\tLocation:" << file.location << endl;
cout << "\tLocation (c_str()): " << file.location.c_str() << endl;
where location is set by a function that finds a file location in a file with the format
DRIVE:\dir1\dir2...\filename.ex... | There are so many wrong things in your code... Here is the number 1 problem:
temp2 = char(HexToInt(temp2));
temp2 is empty at this point, so HexToInt returns 0.
Here are more problem:
temp = Location[i+1] + Location[i+2];
this adds two char resulting in an int. It does not concatenate them. Use std::string::substr i... |
6,081,357 | 6,081,492 | Problems with pwrite() to a file in C/C++ | I've a bad problem. I'm trying to write to a file via filedescriptor and memalign. I can write to it but only something like an wrong encoded char is written to a file.
Here's my code:
fdOutputFile = open(outputFile, O_CREAT | O_WRONLY | O_APPEND | O_DIRECT, 0644)
void writeThis(char* text) {
while (*text != '\0')... | Looking at your program, here is what happens:
You fill the memory initially pointed to by buffer0+buffPositionOutput (Which is where, precisely? I don't know based on the code you give.) up to buffer0+outputbuf.st_blksize with data.
You pass the address of the buffer0 pointer to posix_memalign, which ignores its cur... |
6,081,620 | 6,081,630 | What's the real lower limit for (signed) long long? | Checking the limits of the type long long using
std::cout << std::numeric_limits<long long>::min();
I get -9223372036854775808
However when compiling the following code:
int main() {
long long l;
l=-9223372036854775808LL;
}
I get the warnings:
test.cpp:3:7: warning: integer constant is so large that it is unsig... | This 9223372036854775808LL is a positive number. So you need to take
std::cout << std::numeric_limits<long long>::max();
into consideration. Negating it immediately afterwards doesn't make the operand of the - operator itself negative.
|
6,081,697 | 6,081,712 | function with the same name as a macro | #include<stdio.h>
void f(int a)
{
printf("%d", a);
}
#define f(a) {}
int main()
{
/* call f : function */
}
How to call f (the function)? Writing f(3) doesn't work because it is replaced by {}
| Does (f)(3); work?
The C preprocessor doesn't expand the macro f inside ( ).
|
6,081,700 | 6,081,732 | tellg moves after write operation in file | Why does tellg() moves after a write operation, I suppose it should be tellp()?
std::fstream fs("c:\\log.txt", std::ios::in | std::ios::out | std::ios::trunc);
fs << "write";
std::cout << fs.tellg() << std::endl;
fs.close();
Output:
5
| The stream actually maintains only one pointer, so the read and write pointers are effectively the same. if you want to do reads and writes to the same file, you should maintain your own pointer and do a seek before every read/write operation.
|
6,081,773 | 6,082,056 | opencv array more than 255 | I'm dealing with CvMat in opencv of type CV_8U.
I'm basically adding arrays (and resultant addition is expected to be more than 255).
It looks like the CvMat array doesn't store values more than 255 (values more than 10,000-20,000). I don't want an overflow to occur.
Is there any way I can do that using a opencv data... | CV_8U means each variable is between 0 and 255 (8bit unsigned integer).
CV_16U will give you 0 to 65535
Is that all you were looking for?
|
6,081,815 | 6,093,419 | reporting end of seed or leeching to tracker Libtorrent | From what I know, when seeding or leeching torrent, your IP is on tracker and it remains there for some few hours or days How do I manually tell my the tracker using Libtorrent I am no longer going to be connected to the tracker and it should forget my IP as I am neither seeding nore leeching. Any code bits or advices ... | libtorrent automatically does this when stopping a torrent, or stopping the session. If it seems to fail, you might want to increase the tracker timeout when shutting down. This will add to the shutdown delay, but will give some more overloaded trackers some more time. See session_settings::stop_tracker_timeout. By def... |
6,082,034 | 6,082,052 | How to make a menu that doesnt pause my program when used? | This is my code for creating my menu for the program:
WNDCLASS wc;
...
hInstance = GetModuleHandle(NULL);
wc.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC;
wc.lpfnWndProc = (WNDPROC) WndProc;
wc.hInstance = hInstance;
...
if(!RegisterClass(&wc)) ...
Now if i open the menu, my program will pause until i dont use the menu ... | You need to do your rendering in a separate thread - popping up a menu will always halt a single-threaded Windows application.
|
6,082,308 | 6,082,397 | c++ mystic transfer of class array | class Array
{
double *mx; int mn;
public:
Array();
~Array(){delete []mx};
Array& operator-(Array& b); //first right way
Array operator -(Array b); //wrong way, but I don't understand why
};
Array::Array ()
{
mn=10;
mx=new double[mn];
}
//first, works perfectly
Array& Array::operator -(Array& b)
{
i... |
operator- should take a reference, otherwise you're performing needless copies. However, it doesn't need to. It certainly should return a value, because a - semantically gives you a new object. When you write c = a-b, you don't expect a or b to change.
As noted above, you don't need to take a reference into operator-,... |
6,082,318 | 6,082,403 | How to find the multiple definitions of a function | I wrote a findDialog which finds the text searched. When I give make command,it returns
g++ -Wl,-O1 -o findDialog FindDialog.o main.o moc_FindDialog.o -L/usr/lib -lQtGui -lQtCore -lpthread
moc_FindDialog.o: In function `FindDialog::findClicked()':
moc_FindDialog.cpp:(.text+0x20): multiple definition of `FindDialog:... | It usually happens when method definition is included in multiple translation units, also called as object files. Later, when linker is combining those object files, it finds out that there are multiple definitions of the same method, and complains because it doesn't know which one to use. Here is a simple example of h... |
6,082,355 | 6,082,493 | TR1 regex_replace with wstring in VS2010? | #include <iostream>
#include <string>
#include <regex>
#include <ios>
#include <locale>
using namespace std;
int main ()
{
const wstring wstr(L"<(.|\\n)*?>");
static const wregex wr(wstr);
wstring line (L"<tag>Random text<tag>");
wstring line2 (L"");
wcout << regex_replace<wchar_t>(line,wr,line2) << endl;
}
Com... | Partial answer:
You should use regex_repalce this way:
wcout << regex_replace(line,wr,line2) << endl;
i.e., without the wchar_t. The first argument is for the Element Traits class, which you'd only rarely want to modify.
Edit
I've checked your code with VC++ 2010. Changing the line as I specified allowed the code to c... |
6,082,461 | 6,082,528 | C++ convert integer to hex string for Color in Graphicsmagick | How can i convert an integer ranging from 0 to 255 to a string with exactly two chars, containg the hexadecimal representation of the number?
Example
input: 180
output: "B4"
My goal is to set the grayscale color in Graphicsmagick. So, taking the same example i want the following final output:
"#B4B4B4"
so that i can us... | You don't need to. This is an easier way:
ColorRGB(red/255., green/255., blue/255.)
|
6,082,481 | 6,082,621 | boost::asio async_send error | The following code using boost::asio will not compile:
#pragma once
#include <ctime>
#include <iostream>
#include <string>
#include <stdint.h>
#include <boost/bind.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/enable_shared_from_this.hpp>
#include <boost/asio.hpp>
class Connection
: public boost::enable_sha... | Your call to async_send should look like this:
socket_.async_send(boost::asio::buffer(buffer, length), boost::bind(&Connection::handler, this, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred));
|
6,082,862 | 6,083,503 | Problem with seekp(), seekg(), read() and write() on the same file | I'm dealing with a problem with files in C++ I'm not able to work out. I'm managing a file with registers and I'm trying to do "Sorted Insert", in Spanish is "Insercción ordenada" but I don't know the translation to English. What I try to do is opening the file at the end of it and comparing the register with the one I... | This doesn't work
f->seekg(readPosition,ios::beg);
f->seekp(writePosition,ios::beg);
A file only has one position. You have to do your seeks when you need them, when changing from reading to writing or vice versa.
|
6,083,005 | 6,083,258 | Macro with "placeholder" value | I'm working with a library that includes a set of preprocessor libraries. One of them is a FOR_EACH style macro which iterates over a __VA_ARGS__ and calls a user-provided macro for each argument. The user provided macro is called like: SOME_MACRO(current_arg)
However, the problem is that it only works with user-prov... | Yes. You can use following technique.
#define MY_MACRO(FIELD) EXPAND FIELD
#define EXPAND(X, FIELD) X::FIELD()
Usage in the below test code:
struct foo { static int f() { return 0; } };
struct STRUCT { static int f() { return 1; } };
#define MY_MACRO(FIELD) EXPAND FIELD
#define EXPAND(X, FIELD) X::FIELD()
int main (... |
6,083,184 | 6,084,121 | Using-directive class static functions? | I am using an API that has a lot of functions in a class named TCODConsole as static functions. Now I thought that it was in a namespace, so I wrote: using namespace TCODConsole;. Then I found out that TCODConsole ain't a namespace, but a class.
Is there a way to import those functions in a similar way as you would use... | Though I may misunderstand the question,
if shortening the qualification is the objective,
does typedefing like the following meet the purpose?
struct TCODConsole {
static void f();
static void g();
};
int main() {
typedef TCODConsole T;
T::f();
T::g();
}
Alternatively, if the class TCODConsole can be insta... |
6,083,195 | 6,083,409 | CPPCMS build error with libraries | Despite I have open ssl installed, it can't find where the library is. The openssl exists in my Ubuntu as default, it still can't find, so I download a new distribution and reinstall it to /usr/local/ssl . I install by the default cmake command:
cmake ..
As well as explicitly specify the path:
cmake -DCMAKE_INCLUDE_PA... | Great,
I found the answer here: http://cppcms.sourceforge.net/wikipp/en/page/cppcms_1x_build_troubleshooting
sudo apt-get install build-essential libpcre3-dev libicu-dev libgcrypt11-dev zlib1g-dev cmake
|
6,083,286 | 6,083,343 | Having a little issue calculating the bounding sphere radius | I have managed to calculate the bounding sphere radius in two ways, but none is giving me exactly what I want. I don't need a "pixel" perfect bounding sphere but I would like something better than what I currently have.
I'm using Wavefront .obj models and to calculate the bounding sphere radius for those models I extra... | Your second approach should give you the bounding sphere for your bounding box, but as you discovered, it will be larger than necessary for anything other than a box.
A better bounding sphere can be found by translating the model points so they're centered on the origin using the bounding box dimensions you already ha... |
6,083,432 | 6,083,464 | How to sort the letters in a string into alphabetical order in c / c++? | hi all
in this code when i write AaBc it writes ' ABab' .
what should i change in this code ,if i want it writes like ' AaBb '???
#include <stdlib.h>
#include<iostream.h>
#include<string.h>
int main (void)
{
char string[128], temp;
int n, i, j;
printf("\nEnter string: ");
gets(string);
n = strlen(... | The ASCII value of 'A' and 'a' are not the same. 'A' == 65 and 'a' == 97.
So, when you compare, you need to compare using either tolower or toupper to make sure that your value is right. After you make that comparison, you need to then also compare to see if it's upper versus lowercase (to ensure upper, then lower orde... |
6,083,443 | 6,083,457 | Class Operator Overloading | This is a very basic operator overload question.
Say I had a class like this...
class xy
{
public:
double x, y;
XY(double X, double Y) { x = X; y = Y;}
XY operator+(const XY & add) const {
return XY(this->x + add.x, this->y + add.y);
}
XY & operator+=(const XY & add) const {?}
}
}
... | Yep, do the add operation (stick to the += operator), and return a reference to itself. Oh, and this can't be a const method.
XY & operator+=(const XY & add) {
this->x += add.x;
this->y += add.y;
return *this;
}
|
6,083,599 | 6,083,652 | std::foreach with boost::bind | What's wrong with this:
template <typename T>
std::list<T> & operator+=(std::list<T> & first, std::list<T> const& second)
{
std::for_each(second.begin(), second.end(), boost::bind(&std::list<T>::push_back, first, _1));
return first;
}
It compiles fine, but doesn't work.
| You need to use boost::ref to pass an argument/object via reference, otherwise bind creates an internal copy.
std::for_each(
second.begin(), second.end(),
boost::bind(&std::list<T>::push_back, boost::ref(first), _1)
);
|
6,083,758 | 6,089,218 | C++ select stops accepting connections |
I'm trying to make a select-server in order to receive connection from several clients (all clients will connect to the same port).
The server accepts the first 2 clients, but unless one of them disconnects, it will not accept a new one.
I'm starting to listen the the server port like this:
listen(m_socketId, SOMAXCO... | It's not allowed to copy construct fd_set objects:
m_socketReadSet = m_socketMasterSet;
This combined with Nikolai's correct statement that select changes the set passed in probably accounts for your error.
poll (On Windows, WSAPoll) is a much friendlier API.
Windows also provides WSAEventSelect and (Msg)WaitForMulti... |
6,083,764 | 6,084,558 | Can't find standard C++ includes when using C++ class in Cocoa project | I have a Cocoa project (a Mac OS X app), all Objective-C. I pulled in one C++ class (which I know works) from another project, and make an Objective-C wrapper for it. The ObjC wrapper class is using a .mm extension. However, the C++ header file contains #includes to standard C++ header files (<vector>, for example),... | The problem with your CppWrapper class is that it doesn't present a pure Objective-C interface. In your CppWrapper.h file, you're importing the C++ class's header file, which means that any Objective-C class that imports the wrapper class will need to be compiled as Objective-C++, including your TestAppDelegate.
Instea... |
6,083,789 | 6,083,868 | Overriding a non void function in C++, where does supers return value return to? | I'm writing a program with three levels of inheritance. It is required that I overload the operator== in the base class, and then override that function in the derived classes (I am not allowed to change this design).
The function is a bool which does a memberwise comparison of two objects. How do I process supers retu... | If you inherit from a class, then you have to use an explicit qualifier. There's no keyword.
class A {
public:
virtual bool operator==(const A&);
};
class B : public A {
public:
virtual bool operator==(const B& other) {
bool result = A::operator==(other);
//.. do other stuff
}
};
If you don... |
6,083,829 | 6,553,430 | Qt catch pressed key | i think of to write primitive snake. i have window where program paints random lines.
but i can't think up how to catch pressed key to change direction of painted line.
class QUpdatingPathIte : public QGraphicsPathItem
{
void advance(int phase)
{
if (phase == 0)
return;
int x... | QGraphicsView inherits from from QWidget because it inherits from QAbstractScrollArea. You should create a custom subclass of QGraphicsView and just override the function keyPressEvent(). Example:
class SnakeView : public QGraphicsView
{
protected:
keyPressEvent(QKeyEvent *e)
{
// Do something
... |
6,083,987 | 6,084,011 | No instance of constructor? | I'm trying to create my own Vector2D class, similar to that of XNA's, to store coordinates in. Following the example of constructors found here, I created the code below. However, I get an error saying that there is no instance of constructor "Vector2D::Vector2D" that matches the argument list. I don't see how that can... | You are most likely trying to create your Vector2D class like this:
Vector2D vector(1, 2);
You can't do that using pointers to int like you've done in your Vector2D constructor definition because those values are not pointers, they are integer constants. Change to simple int objects like this:
struct Vector2D
{
... |
6,084,012 | 6,106,165 | Fast image manipulation | I have an array 10X10 with values between 1 to 10. Now say I want to give each value a unique color (Say 1 gets blue 2 gets red etc). I'm using qt qimage to represent the image.
Here's what I'm doing
read array from disk. store in a[10][10]
generate a hash table in which each value in the array has a corresponding qRGB... | There is indeed a faster way: Create an array of unsigned chars and modify the pixels values directly. Then create a QImage from this array. Calling setPixel() is very expensive.
unsigned char* buffer_;
buffer_ = new unsigned char[4 * w * h];
//...
for(int i = 0; i < h; i++){
for(int j = 0; j < w; j++){
unsign... |
6,084,027 | 6,084,041 | C++ / C: Trim the first word of each line of a text file | I am looking for a C / C++ or even C# code that will trim the first word of a each line in a text file
e.g. file.txt
test C:\Windows\System32\cacl.exe
download C:\Program Files\MS\
So I will be left with:
C:\Windows\System32\cacl.exe
C:\Program Files\MS\
I have the current code, but it doesnt seem to work:
#include <... | #include <iostream>
using namespace std;
int main()
{
string tmp;
while ( !cin.eof() )
{
cin >> tmp;
getline(cin, tmp);
cout << tmp << endl;
}
}
|
6,084,037 | 6,084,486 | How to serialize a 3D array with boost? | Okay, I recently switched to boost and I partitialy understand serializing simple objects or simple classes (the boost tutorial confuses me), but how can I serialize a 3D array which contains class members?
I have an array (std::vector) called TileList, which contains objects which are of a class Tile and class Tile co... | So I understand you have something like this (that's not really a 3D array, post the exact code you want to serialise if I misread you):
struct Tile {
int id, passability;
};
std::vector<Tile> tileList;
Because std::vector is already serialisable through standard Boost.Serialization facilities, you only need to m... |
6,084,043 | 6,084,062 | Why would I overload operator new or operator delete? |
Possible Duplicate:
Any reason to overload global new and delete?
In c++ you can overload new/ delete operators, are there any benefits in doing so? Since right after calling operator new its result value is sent to the constructor and right before calling operator delete, the destructor is called.
| The point of overloading is to control the memory allocation. In some cases you want to use your own allocators instead of the standard ones (for example, when you want allocations to be from static pools and not directly from the heap).
|
6,084,089 | 6,084,866 | (Re)named std::pair members | Instead of writing town->first I would like to write town->name. Inline named accessors (Renaming first and second of a map iterator and Named std::pair members) are the best solutions I have found so far. My problem with named accessors is the loss of type safety:
pair<int,double> may refer to struct { int index; doub... | I don't see how you can possibly do better than
struct city { string name; int zipcode; };
There's nothing non-essential there. You need the types of the two members, your whole question is predicated around giving names to the two members, and you want it to be a unique type.
You do know about aggregate initializati... |
6,084,137 | 6,084,177 | Why this program doesn't consume memory? | It's bothering me what delete [] actually does, so I just tried some code and I was shocked with the results
Test #1:
int main()
{
int *d;
while(true)
{
d = new int[10];
delete []d;
}
}
The program doesn't consume any memory at all, as expected.
Test #2:
int main()
{
int *d;
wh... |
it's bothering me what delete []
actually does
You're not supposed to worry about what delete[] actually does. It's for all intents and purposes a black box with certain rules on how to use it properly. The only time you need to worry about what it needs to actually do is if you're writing a compiler or a C++ runti... |
6,084,142 | 6,085,951 | is there a way change a member variable in release code on linux while the program is running? | I wrote a program which solves some kind of optimization problem. I have been running it with increasingly lower thresholds and I think I hit some kind of barrier since my program can't get better results. It has been running for about 5 days...
However, I have some code in the program which saves its data if it is bet... | First, you don't need to restart the program in order to debug it.
You should rebuild it using exactly the same sources and flags you used originally and add -g. This will give you an executable that contains debug info, but otherwise is (almost) identical to the original binary. The output from nm a.out and nm a.out.d... |
6,084,222 | 6,084,385 | Can I get a static initialization order fiasco failure when I access static members through a static function? | Is this particular code prone to the static initialization order fiasco? I.e. can I assume that static initialization in compilation unit "B" is already done when I access B's static member function?
// a.h
struct A {
static int foo();
static int var;
}
// a.cpp
#include <a.h>
int A::foo() {
return var;
}
... | Yes you can see the problem when accessing through a static function.
See example below guaranteed to fail.
The way to solve this is not to access "Static storage duration objects" before main has started.
If for some reason you need to access objects from the constructor of a "Static Storage duration object" then thes... |
6,084,226 | 6,084,315 | help with pointers and passing linked list as parameter, undefined reference c++ | I am getting an error message that says undefined reference to
encrypt(int, std::list<int, std::allocator<int> >*)
Here is how I am trying to use it:
decka = new list<int>;
ifstream inF;
inF.open(filename.c_str());
if (inF.fail()){
cerr << "Error opening file" << endl;
exit(1);
}
int deckcount = 2... | void encrypt(int msize, list<int> *L){
Should be:
void DeckOps::encrypt(int msize, list<int> *L){
|
6,084,438 | 6,084,608 | Changing python math module behaviour for non-positive numbers division | Non-positive number division is quite different in c++ and python programming langugages:
//c++:
11 / 3 = 3
11 % 3 = 2
(-11) / 3 = -3
(-11) % 3 = -2
11 / (-3) = -3
11 % (-3) = 2
(-11) / (-3) = 3
(-11) % (-3) = -2
So, as you can see, c++ is minimizing quotient.
However, python behaves like that:
#python
11 / 3 = 3
11 %... | As Thomas K said, use math.fmod for modulo, or if you really want you can define it yourself:
def cmod(x, y):
return abs(x) % abs(y) * (1 if x > 0 else -1)
And this function should emulate C-style division:
def cdiv(x, y):
return abs(x) / abs(y) * cmp(x, 0) * cmp(y, 0)
You said that you must use the / and % ... |
6,084,550 | 9,885,733 | Capture audio of a single application on Windows 7 | Is there a way to capture the audio outputted by only a single application, and not the system as a whole? With WASAPI I can capture the entire system audio, but I wish to only capture the audio from one application (there will be many applications, all playing audio at once.)
| Detours is used for hooking. Using the lib to hook IAudioRenderClient interface, including GetBuffer and ReleaseBuffer, and read data from the buffer.
|
6,084,554 | 6,084,605 | Removing a space from lines in the beginning of a text file | I have a C++ snippet that removes the first word of a line in a text file e.g.
test C:\Windows\System32
download C:\Program Files\test.exe
Although it removes the first word, there is a space left over after trimming it, is there a way to stop remove this space?
#include <iostream>
using namespace std;
int main()
{
... | You just need to trim tmp before streaming it to cout. Use your favourite trim function from a library, or write your own.
You can find some options for trim functions here: What's the best way to trim std::string?
Once you have a trim function, and Evan Teran's versions look rather fine, you then can write:
cin >> ... |
6,084,931 | 6,084,999 | Any idea why i'm getting these two errors in my c++ program? | I'm writing a program that creates a complex number class and I am getting these two errors when i try to test my overloaded operator >>. Here are the errors:
error LNK2028: unresolved token
(0A0002BD) "class
std::basic_istream > & __cdecl
operator>>(class
std::basic_istream > &,class
Complex const &)"
(??... | The compiler, when processing main has found that the best overload for the expression cin >> num; is std::basic_istream<...>& operator>>( std::basic_istream<...>&, const Complex& ), note the const in the second argument.
This probably indicates that you have declared the operator as:
std::istream& operator>>( std::ist... |
6,084,954 | 6,087,297 | What is the closest thing to Apache Hadoop in other languages? | Specifically any Open Source implementations at any degree of usefulness in the following languages:
1) C++
2) Python
3) Ruby
4) C#
| The german wikipedia has some software examples for each language. I'm translating:
Apache Hadoop MapReduce (natively Java, pipes to C++, Python, etc.)
disco Open Source Project (Python and Erlang) by Nokia Research Center
Greenplum MapReduce by Greenplum (not sure, seems to be C++ though, but with a SQL layer like PI... |
6,084,968 | 6,084,976 | How can I launch a function at a specific time in C++? | Is is possible to call a function at a specific time in C++? For example, I would like to launch function doIt() when number_of_elapsed_milliseconds_since_application_start = x.
A cross-platform solution would be ideal.
| In pure C++ probably not, you will need some OS specific code. But you can use a platform-independent OS-wrapper, like Qt (although this could be a bit of an overkill for your quite simple problem).
EDIT: The simplest thing you could do, is actively blocking the program in a loop, that constantly polls the current time... |
6,085,033 | 6,085,078 | Should global functions be used? | Excuse me for the elementary question: In C++, should all functions be inside a class or non-global namespace? In what sort of circumstances should one write a global function?
| Defining a function outside a class might be useful for operator overloading (specifically operator<<) or perhaps a template function that allows many of your classes to be used such as:
template <class T>
void
display (T obj)
{
obj.display ();
}
Of course, that says nothing about being inside or outside a namespace... |
6,085,061 | 6,088,289 | Do work instead of waiting for glMapBuffer | I'm using OpenGL for some GPGPU processing. So I have different threads giving work to a OpenGL processing thread.
After each "work-item" I need to call glReadPixels and glMapBuffer in order to transfer back data to the host from the PBO. The problem with this however is that glMapBuffer blocks the thread and no useful... | Do some additional work in other threads than the one glMapBuffer blocks in? You can have multiple OpenGL contexts, each active in its own thread; if they're configured to share objects they can operate simultanously.
However a DMA actually means work for the GPU, at least the bandwidth to it is fully consumed and so y... |
6,085,084 | 6,085,110 | Key-Value DB (an alternative to Berkeley DB?) | I'm looking for a hashmap on disk (Berkeley DB would fit exactly, but for the licensing problem).
The requirements are:
FOSS w/a commercial-friendly license (can be used in commercial applications without a fee)
a C/C++ interface
Embeddable
decent speed? faster than SQLite would be ideal
cross-platform would also be ... | How about the *dbm libraries?
dbm ndbm gdbm sdbm tdbm and friends
Plenty to choose from.
|
6,085,109 | 6,085,180 | C# Memory optimization for large arrays | Here are two code parts in c++ and c# doing absolutely the same thing:
C++
http://ideone.com/UfL5R
#include <stdio.h>
int main(int argc, char *argv[]) {
char p[1000000];
unsigned int i,j;
unsigned long long s=0;
for(i=2;i<1000000;i++) p[i]=1;
for(i=2;i<500000;) {
for(j=2*i;j<1000000;j+=i) p[j]=0;
for(... | How to GREATLY Increase the Performance of your C# Code
Go "unsafe" (unmanaged) for that... every time you're doing someSortOfArray[i], the .NET framework is doing all kinds of neat-o things (such as out of bounds checking) which take up time.
That's really the whole point of going unmanaged (and then using pointers an... |
6,085,120 | 6,085,426 | SDL - Dynamic Alpha? | I plan on making a game (in SDL) where, if one character moves, the part of the image it was on turns alpha, thus allowing me to place a scrolling image underneath the original scene.
1) Is this possible?
2) If yes to #1, how can I go about implementing this (not to give me code, but to guide me in the right direction... | It sounds like you want to learn about image compositing.
A typical game these days will have a redraw function somewhere to redraw the entire screen. The entire scene is always redrawn each frame.
void redraw()
{
drawBackground();
drawCharacters();
drawHUD();
swapBuffers();
}
This is as simple as it ... |
6,085,155 | 6,085,314 | Performance OVER TIME problem | Hey so i'm making a simple text game using the pdCurses library and a few other minor things kind of like a vertical scroller in which you avoid the randomly generated walls....
Theres two walls on lef and right made out of 'X' characters and blank, black space in which you can move around and avoid the 'X's your chara... | The general issue seems to be that as your data set gets larger things like copying it around (which you seem to do all the time, e.g. in your snippet you are copying strings from one vector to the other) take longer.
Things to consider:
Do you need the data that is coming
off the screen?
Can you use C style array? T... |
6,085,419 | 6,085,508 | What are the most appropriate boost::asio read/write methods to use for a game server? | I am using boost::asio to make a socket network. The library has a number of different methods for sending and receiving data, each of which perform a similar task with a slight difference.
For sending data, boost provides the following functions:
boost::asio::basic_stream_socket::async_send()
boost::asio::basic_strea... | The async_read() and async_write() free functions are composed operations. They are implemented in terms of zero or more calls to the stream's async_read_some() or async_write_some() methods.
The member functions may not transmit or receive all data before the asynchronous operation completes. You should use the free f... |
6,085,494 | 6,085,549 | Loading DLC files in Python or C++ or Java | Is there any Libraries that allow for loading of DLC files in Python Java or C++?
FYI link
| jDownloader is written in java and handles DLC files. Its open source.
http://jdownloader.org/knowledge/wiki/development/get-started
svn://svn.jdownloader.org/jdownloader/trunk
|
6,085,531 | 6,085,570 | C++ SegFault when dereferencing a pointer for cout | I'm new to C++ and just trying to get a hang of it. It generally seems not too bad, but I stumbled upon this weird/pathological segfaulting behavior:
int main () {
int* b;
*b = 27;
int c = *b;
cout << "c points to " << c << endl; //OK ... | int* b points to an unknown memory address because it wasn't initialized. If you initialized it to whatever null pointer value exists for your compiler (0 until C++11, nullptr in C++11 and newer), you'd most certainly get a segfault earlier. The problem lies in the fact that you allocated space for the pointer but no... |
6,085,611 | 6,085,817 | nesting structures, interfaces, and classes within an interface | I'm actually translating some C++ code (which I know very little about, and have never really used) to C#. Normally in C# I wouldn't find myself doing something like this, as it does seem a little odd, but with the way the code in C++ is setup, I find it hard not to do it this way. Admittedly, I'm not very experienced ... | You appear to be trying to port this SourceForge project from C++ to C#:
Ragnarok Online Sprite Viewer
That viewer is not only written in C++ but is also based on the Qt Toolkit.
I know your question is about this translating this particular header file from C++ to C# and what is the best approach, but my opinion is ... |
6,085,801 | 6,085,820 | linker error while mixing object files compiled from C and C++ | I have trouble mixing the C and C++ code , I separately compile the C and C++ code using gcc and g++. The C code calls C++ functions. I compile them separately which go through well. I link both the objects to produce a ".so" file. when i load this module from lua , module loading fails saying some undefined symbol. I ... | I think you need to link with the C++ library. c++filt can help you decode the mangled symbol name:
main% c++filt _ZNSsaSEPKc
std::basic_string<char, std::char_traits<char>, std::allocator<char> >::operator=(char const*)
|
6,085,827 | 6,085,832 | Access violation writing location 0xcccccccc | For the past 2 days I've been stuck on a violation which I can't seem to get to go away.
I've used break points and located where the error is, but I'm just hoping one of you will know what the issue is without me having to copy+paste all my code -.-
I'm getting
First-chance exception at 0x1027cb1a (msvcr100d.dll) in... | Either an uninitialized pointer, or a pointer stored in memory that's been freed. I think cccccccc is the first and cdcdcdcd is the second, but it varies with compiler/library implementation.
For your particular code, probably myMap hasn't been allocated yet, then myMap[0][0] would result in an access attempt to 0xccc... |
6,086,072 | 6,086,089 | Why was std::swap moved to <utility>? | Why has std::swap been moved to the <utility> header for C++11?
N3290 C.2.7 says:
17.6.3.2
Effect on original feature: Function swap moved to a different header
Rationale: Remove dependency on <algorithm>for swap.
Effect on original feature: Valid C++ 2003 code that has been compiled expecting swap to be in <algorit... | The committee wanted to allow you to use swap() without introducing a compile-time dependency on the large and more complex <algorithm> header file. Because swap() is so widely used, it makes sense to let you pull in its definition with as little additional baggage as possible; this will generally lead to faster compil... |
6,086,207 | 6,086,244 | Why is the Win32 mutex so time-consuming | I have been reading the book of Windows via C/C++. In chapter 8, page 215, the author compared the performance of various synchronization mechanisms. And I found the poor performance of mutex. When 4 threads run simultaneously, it spent more than twenty three seconds for the mutex synchronization.
Why is the Win32 mute... | A mutex in Win32 is a kernel object, meaning that every use of it (Wait, Release) requires a system call that switches into kernel mode and back to user mode. Plus if your thread actually has to wait for the mutex, it loses its quantum while another thread that can run gets scheduled on the CPU. On WinXP and earlier (a... |
6,086,247 | 6,086,807 | Parsing HTML with C++ (using Qt preferably) | I'm trying to parse some HTML with C++ to extract all urls from the HTML (the urls can be inside the href and src attributes).
I tried to use Webkit to do the heavy work for me but for some reason when I load a frame with HTML the generated document is all wrong (if I make Webkit get the page from the web the generated... | You can always use XPath expressions to make your parsing life easier, take a look at this for instance.
or you can do something like this
QWebView* view = new QWebView(parent);
view.load(QUrl("http://www.your_site.com"));
QWebElementCollection elements = view.page().mainFrame().findAllElements("a");
|
6,086,383 | 6,086,426 | VS 2008 C++ error C2059 and C2238 | I'm trying to port a program/game that was developed in linux/g++ so that it runs on windows 7 VS 2008 C++. The program uses libraries such as OpenGL, SDL, and Boost.
I've solved a lot of errors but I'm kind of stuck on this one.
I get error code C2059 and C2238. The actual error messages are:
------ Build started: Pro... | Chances are you're including a windows header before that one, and near and far are defined somehwere in there. Those are (legacy) things from the 16bit era.
See this related question Is there a clean way to prevent windows.h from creating a near & far macro? for workarounds.
|
6,086,547 | 6,086,581 | Simple user defined vector template example | Consider the following code:
template<typename T>
class vecTor
{
int size;
T *v;
public:
vecTor(int s=0): size(s),
v(new T[size]) // conv. ctor [1]
{
for(int i=0; i<size; i++)
v[i]=0;
}
vecTor(T *x,int s) // [2] this conv. ctor produces seg. fault if called
{
size=s;
for(int i=... | You aren't initializing T*
vecTor(T *x,int s) : size(s), v(new T[size])
{
for(int i=0; i<size; i++)
v[i] = x[i];
}
|
6,086,557 | 6,099,009 | How to display video in/with Adobe Alchemy? | I want to display a video from a not supported USB camera in Air (or Flash).
There is a SDK (of the camera) to display the video stream.
My question:
How should the C/C++ routine build to compile it with Adobe Alchemy?
I want only to display the video stream in Adobe Air (or Flash).
No audio or something special is nee... | If you cannot already use the camera from Flash, Alchemy is not going to help you.
Alchemy can only do things that ActionScript can do-- it does not help you "get around" the Flash sandbox. The reason people use Alchemy is so that they can compile large legacy codebases and/or open-source libraries.
|
6,086,643 | 6,087,403 | Why does postfix operator++ have higher precedence than prefix operator++? | Defined this way, we can do neither ++x++ nor ++x--. But on the other hand, both (++x)++ and (++x)-- are useful expressions: (++x)++ increments x by two and returns the value "in the middle", while (++x)-- is essentially equivalent to x+1 but completely avoids having to call operator+, which can be quite useful sometim... | C++ standard just kept the C rules and obviously those weren't fixed considering operator overloading and idioms yet be invented in a yet to be invented language.
Looking at what is available in D.M. Ritchie Home Page, on see that this precedence is already present in B (Unary operators are bound right to left. Thus -!... |
6,086,912 | 6,088,010 | Double-Checked Lock Singleton in C++11 | Is the following singleton implementation data-race free?
static std::atomic<Tp *> m_instance;
...
static Tp &
instance()
{
if (!m_instance.load(std::memory_order_relaxed))
{
std::lock_guard<std::mutex> lock(m_mutex);
if (!m_instance.load(std::memory_order_acquire))
{
Tp * i... | That implementation is not race-free. The atomic store of the singleton, while it uses release semantics, will only synchronize with the matching acquire operation—that is, the load operation that is already guarded by the mutex.
It's possible that the outer relaxed load would read a non-null pointer before the locking... |
6,087,056 | 6,087,124 | What is the right way of implementing C++ setters in char array wrapper class? | I'm working on the class that simply contains a character array and it's size (length in bytes). At the moment, I want to overload '+' operand for this class (to implement concatenation). Constructors work fine. Objects are created and I can see their fields and values in the debugger. I'm stuck at the point where '+' ... | in BufferArray::operator+, tempCharArray is a temporary buffer that will be destroyed when the function completes. There a basically two ways to handle this:
1/ allocate the temporary buffer with new[] in operator+, that way you'll make sure the buffer survives the call to operator+ but you'll either have a memory leak... |
6,087,108 | 6,087,867 | How to fire off QML-animation from C++ | I connected C++ and QML via a mediator-class and have everything working in both directions but this one puzzles me.
This is how I connect the mediator-class:
// Initialize Mediator between QML and C++
QmlCppMediator m_qmlCppMediator;
QDeclarativeContext *context = viewer.rootContext();
context->setContextProperty("cpp... | Ok I can answer this myself already.
I went for an approach described here http://qt-project.org/doc/qt-4.8/qdeclarativeanimation.html
I bind the “state” of the object which I try to animate to a Q_PROPERTY in the C++ interface.
The different states are linked to transitions (in QML) which do the animate the object.
|
6,087,117 | 6,087,162 | Class in C++ which implements streams | I want to write a class Map with two functions: save and load.
I'd like to use streams so I could write in my program:
map << "map name" and it'd load a map to memory and map >> "map name" and it'd save my map.
Unfortunately in google I can only find how to override the operators '>>' '<<',but using cout or cin at t... | overload the << and >> operators and declare them as friend to your class, and then use them. Here is a sample code.
#include <iostream>
#include <string>
using namespace std;
class Map
{
friend Map& operator << (Map &map, string str);
friend Map& operator >> (Map &map, string str);
};
Map& operator << (Map &map... |
6,087,159 | 6,087,433 | Is it possible to generate a C++ class from a xsd using Qt (without the XSD tool)? | I get several Datasets listed in a single xml File. I have to extract each dataset and do some operations depending on their values (not changing the content of the xml file).
So I have to parse that file.
With the .Net Framework I would simply use the XSD tool to generate a matching class avoiding to write a parser my... | Nice question! You should not worry if Qt has such a feature. You can use CodeSynthesisXSD which is open source. The you can combine the generated classes to your Qt project.
|
6,087,160 | 6,087,165 | restrict qualifier and pointer arithmetic | Does incrementing or decrementing a restrict qualified pointer preserve no aliasing assumption?
// a and b point to disjoint arrays
void foo(size_t n, double * __restrict a, double * __restrict b) {
size_t i;
double x, y, z;
double * c = b; // copy
for(i=0; i<n; ++i) {
x = *(a++); // not ali... | Yes. The restrict qualifier is part of the type of the pointer, and this type isn't changed when you increment, decrement, or assign it.
|
6,087,228 | 6,087,797 | Configure OpenCV 2.2 with Borland on C::B | Hii all,,
I have some project that requires me to do Image processing, I used to work with MATLAB but it is just too slooowww, Searching for an alternative lands me up to OpenCV. I am used to C::B with Borland Compiler 5.5, and to my luck, borland is not supported by default, I have googled it but ain't no luck.
Please... | The best way is to use a compiler wrapper to convert from g++ compiler options to Borland C. Then use the configure script to discover the settings that are needed for your compilation environment.
You can take the compiler wrapper for msvc and modify it for Borland. It can be found here.
Next you should install Cygwin... |
6,087,239 | 6,087,280 | boost::thread program crashes on throwing std::exception | I am puzzled as to why this program crashes. This is the entire program
#include<fstream>
#include<string>
#include<iostream>
#include <exception>
#include <boost/thread/thread.hpp>
void func( const std::string& filename )
{
std::ofstream outFile( filename.c_str(), std::ios::binary);
if( !outF... | The basic problem is that in the current standard there is no support for moving exceptions from one thread to another. When the exception is left uncaught in the newly created thread, it reaches the top of the stack and finalizes the program as if an exception had been left uncaught in main. Consider that the try in m... |
6,087,274 | 6,087,300 | Segmentation fault after mmap() | I wanna share a pointer of map during 2 processes. So I tried mmap. I tested mmap in a single process. Here is my code:
#include <vector>
#include <iostream>
#include <sys/mman.h>
#include <unistd.h>
#include <cstdlib>
#include <stdio.h>
#include <map>
using namespace std;
int main(int argc, char *argv[])
{
... | You are allocating new memory with mmap (why? seems like a bad idea...) but you are not initializing your map. Use "placement new" to initialize it.
void *p = mmap(....);
if (p == MAP_FAILED)
abort();
map<string,string> *b = new(p) map<string,string>();
b->insert(...);
But I suspect something is terribly wrong, a... |
6,087,293 | 6,087,348 | Help me understand this URL decoder: | After playing around with URL decoding myself, I managed to come up with some ideas that worked - but they weren't very efficient. Since URL decoding is a place where severe bottlenecking could occur in my program I decided to go out on the internet and find a more efficient solution. I ran across this codeguru article... | The array is a lookup table, for each ascii character used as an index it will provide either -1 if the character is not an hexadecimal character (in [0..9], [A..F] or [a..f]) or the conversion to integer of that hex character.
In the main loop, whenever a % is found the array is first used to determine whether the fol... |
6,087,296 | 6,087,863 | Looking for example using FTGL and Qt (OpenGL) | i need to do simple application that render 3d fonts to image.
the recommended lib is FTGL , how can i combine it with 3dQt?
| OpenGL doesn't care whether you are using Qt, glut, SDL or anything else. Therefore, find an OpenGL example for Qt, then find an example using FTGL library, and combine the two by starting from the Qt OpenGL example, and add the code to initialize FTGL library and try to render some text.
PS Unfortunately, I do not hav... |
6,087,388 | 6,087,543 | C++ equivalent of Python difference_update? | s1 and s2 are sets (Python set or C++ std::set)
To add the elements of s2 to s1 (set union), you can do
Python: s1.update(s2)
C++: s1.insert(s2.begin(), s2.end());
To remove the elements of s2 from s1 (set difference), you can do
Python: s1.difference_update(s2)
What is the C++ equivalent of this? The code
s1.erase(... | Using std::set_difference is the idiomatic way to do this in C++. You have stumbled across one of the primary differences (pun intended) between C++/STL and many other languages. STL does not bundle operations directly with the data structures. This is why std::set does not implement a difference routine.
Basically,... |
6,087,581 | 6,087,676 | Can the 'auto' keyword be used as a storage class specifier in C++11? | Can the auto keyword be used as a storage class specifier in C++11?
Is the following code legal in C++11?
int main() {
auto int x;
}
| No the code is ill-formed in C++11. auto in C++11 would be used to deduce the type of a variable from its initializer and it can't be used as a storage class specifier.
Correct Usage
int main()
{
auto x = 12; // x is an int
auto y = 12.3; // y is a double
}
|
6,087,729 | 6,087,785 | const in C vs const in C++ | The given code compiles in C but fails in C++.
int main()
{
const int x; /* uninitialized const compiles in C but fails in C++*/
}
What is the rationale and the reason behind the change from C to C++?
| See the spec, in the compatibility appendix C.1.6:
7.1.6 [see also 3.5]
Change: const objects must be initialized in C++ but can be left uninitialized in C
Rationale: A const object cannot be assigned to so it must be initialized to hold a useful value.
Effect on original feature: Deletion of semantically well-defined... |
6,087,846 | 6,088,014 | cannot convert from 'const boost::asio::const_buffers_1' to 'boost::asio::mutable_buffer' | bool Connection::Receive(){
boost::shared_ptr<std::string> buffer(new std::string());
socket_.async_receive(boost::asio::buffer(*buffer), boost::bind(&Connection::handler, this,
boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred));
//std::cout<<buffer<<std::endl;
... | The async_receive function need to change the content of the buffer, but you can't change a constant buffer.
Use a mutable_buffer instead of a constant buffer. You can find some informations here
You need to pass a pointer and the size to the mutable buffer:
std::vector<char> content_buffer(max_buffer_size);
... boost... |
6,087,887 | 6,087,923 | Bring window to front -> raise(),show(),activateWindow() don’t work | In my Qt-application I open a URL in the default-browser.
Afterwards I want to bring the main-window of my application to the front again.
I tried all approaches I could find but none worked. All it does is blink in the taskbar (of Window 7)
Here’s an example:
this->viewer->show();
this->viewer->raise();
this->viewer->... | This problem is specific to Windows.
If the active window belongs to some process, then Windows does not allow other processes to change the active Window.
(Do not try the following:
https://wiki.qt.io/Qt_project_org_faq#QWidget_::activateWindow.28.29_-_behavior_under_windows)
|
6,088,158 | 6,088,177 | Include in header files | class A{
private:
std::string id;
public:
void f();
};
gives compile time error. However, if I include <string> at top, it compiles correctly. I don't want to use include statements in headers,though. How can i do it?
| You must include <string> in this case to be able to use std::string.
The only moment when you can avoid #including a header is when you're only using references or pointers of the object in your header. In this case you can use forward declaration. But since std::string is a typedef, you can't forward declare it, you ... |
6,088,266 | 6,977,694 | OpenCL doesn't find ATI card | I have a notebook with ATI Mobility Radeon HD 5650, and want to use the card for computing =) After installing AMD APP SDK v.2 (installation was OK) I tried to run code samples, provided with AMD. But there is a problem: when I run a sample, it doesn't find my ATI card - in the list of available OpenCL devices there is... | I have the same problem in my Acer 3820TG. However, the OpenCL programming is needed the driver version over 8.753.1. It seems that Acer doesn't support in currently.
One way to overcome this problem is to force install the newer mobility drivers from AMD.
You can follow the the steps from:
http://www.sevenforums.com/d... |
6,088,602 | 6,088,630 | object of abstract class type "Connection" is not allowed | class Connection
{
public:
typedef boost::shared_ptr<Connection> pointer;
static pointer create(boost::asio::io_service& io_service){return pointer(new Connection(io_service));}
explicit Connection(boost::asio::io_service& io_service);
virtual ~Connection();
boost::asio::ip::tcp::socket& socket();
-->>>vi... | You have not provided a definition for OnReceived, it is therefore a pure virtual (abstract) method and the class an abstract class. You cannot instantiate an object of an abstract class. To use the method OnReceived you have to, well, provide an implementation for it (what does it do at the moment? nothing). Abstract ... |
6,088,793 | 6,088,841 | std::vector out of range | Currently I am trying to render a .obj model that I loaded into vectors. I am trying to pull the Vector3D object out of the array but it gives me an out of range error. It only goes to five before the array crashes, when the array has 12 objects for example. Here is the code for the rendering.
glBegin(GL_TRIANGLE_STRIP... | Did you remember that vertex indices in .OBJ files start at 1 rather than 0? So you have to decrement the vertex indices by 1 after reading them from an "f" tag.
And also as a little comment, I would strongly suggest using [] instead of .at, although in this example it was a good idea, so you got the exception. But in ... |
6,089,214 | 6,089,416 | How do I marshal wchar_t* from C++ to C# as an out parameter or return value? | I have tried to do this in many ways, but none is working. Does anyone have a correct example for this? I just want to move the wchar_t* value from a function to the C# level.
| This isn't as difficult as you think it is... What is wchar_t*? What value does that type typically represent? A string. It's the equivalent to the LPWSTR type defined in windows.h.
So, you marshal it as a string type. However, since it's an out parameter (or a return value), you'll need to use the StringBuilder class ... |
6,089,231 | 6,089,413 | Getting std :: ifstream to handle LF, CR, and CRLF? | Specifically I'm interested in istream& getline ( istream& is, string& str );. Is there an option to the ifstream constructor to tell it to convert all newline encodings to '\n' under the hood? I want to be able to call getline and have it gracefully handle all line endings.
Update: To clarify, I want to be able to wri... | As Neil pointed out, "the C++ runtime should deal correctly with whatever the line ending convention is for your particular platform."
However, people do move text files between different platforms, so that is not good enough. Here is a function that handles all three line endings ("\r", "\n" and "\r\n"):
std::istream&... |
6,089,425 | 6,089,587 | Do compilers automatically use move semantics when a movable object is used for the last time? | I've been studying rvalue references lately and came to a conclusion that it's quite advantageous to use pass-by-value everywhere where complete copy of an object will be made (for complete justification see e.g. How to reduce redundant code when adding rvalue reference operator overloads? and Want speed? Pass by value... |
Is this optimization allowed by the C++0x Standard?
No.
Do the compilers employ it? Even in
complex cases, i.e. the function
consists from more than one line?
No.
How reliable is this optimization,
i.e. can I expect the compiler to
utilize it as much as I expect the
compiler to apply Return Value
Optim... |
6,089,452 | 6,089,466 | Is there a use for function declarations inside functions? | We can declare functions inside functions (I wanted a local variable, but it parses as a function declaration):
struct bvalue;
struct bdict {
bdict(bvalue);
}
struct bvalue {
explict operator bdict() const;
}
struct metainfo {
metainfo(bdict);
}
void foo(bvalue v) {
metainfo mi(bdict(v)); // parses as f... | This is really a C question, because this behaviour was inherited directly from C (although it gets much more press in C++ because of the most vexing parse).
I suspect the answer (in the context of C, at least) is that this allows you to scope the existence of your function declarations to precisely where they're neede... |
6,089,482 | 6,089,507 | How expensive is fmod in terms of processor time? | In my game, I need to ensure that angles do not exceed 2 pi. so I use fmod(angle,TWO_PI);
Is this noticeably expensive to do about 100 times per second?
| 100 times per second? That's almost zero, you shouldn't trouble yourself.
Even if fmod takes 100 clock cycles - that's 10,000 cycles/Sec. For 1 1GHz CPU - that's 0.001% CPU.
BTW: why do you want to do fmod of TWO_PI? If you're going to take sin() or cos() - you can skip it.
|
6,089,498 | 6,090,008 | Type erasure for methods with differing in return types | I was wondering if some form of type erasure exists for dealing with methods that have the same name and arguments but return different values like in my example below (begin and end). I'm not planning on actually using this anywhere I'm just interested in knowing if it's possible, and, if so, how it would be done.
... | Type erasure can and has been implemented in C++ in different contexts. The most common approach, which is used in boost::any, std::function< signature >, std::thread and others is based on a non-polymorphic class that is the type erased object, which contains a pointer to an interface type. Internally, during construc... |
6,089,551 | 6,089,814 | glortho zox plane projection | I need to make an opengl projection on a plane paralel with XOZ plane (perpendicular on OY).
Can you explain me what parameters I should use with glOrtho to make this projection.
Thanks,
| The wording of your question is not entirely clear to me, but if you want to display things in a "2D" fashion, this is how to do it:
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0, window_x_size, window_y_size, 0, 0, 1);
|
6,089,642 | 6,089,757 | qpainter painting alternatives (performance sucks on Mac) | I have a class which displays waveform data of audiofiles in a QWidget (see screenshot of the widget below, back then i still used a gradient, which caused poor performance).
The audio data is painted in the paintEvent directly on the widget using multiple calls to QPainter::drawLine (the minimum amount of calls to QW... | The current version (4.7.x) of Qt uses Core Graphics backend for painting. It can be slow at times as you found out. On Windows, it uses a software renderer which has really good performances.
My suggestion is to not paint on the passed painter directly in your paint event. Instead, create a QImage the same size as you... |
6,089,806 | 6,093,526 | Keeping the downloaded torrent in memory rather than file libtorrent | Working with Rasterbar libtorrent I dont want the downloaded data to sit on my hard drive rather a pipe or variable or something Soft so I can redirect it to somewhere else, Mysql, or even trash if it is not what I want, is there anyway of doing this in preferably python binding if not in C++ using Libtorrent?
EDIT:-->... | You can do this by implementing your own storage class to use with libtorrent. Unfortunately this is not possible to do in python, but you can do it in c++. The documentation for it is a bit scarce and can be found here.
Here's a simple example of how to do this by storing all the data in RAM:
struct temp_storage : sto... |
6,089,866 | 6,098,185 | How to test for equality of audio sessions | I am trying to use the Windows Audio Session API to locate the default audio session within the enumeration of current audio sessions. Currently I have a reference to the IAudioSessionControl of the default session of the audio render endpoint in the eConsole role as well as an IAudioSessionEnumerator object that enum... | Look at the IAudioSessionControl2::GetSessionIdentifier API, that's what the audio subsystem uses to persist session volumes. If you want to distinguish sessions at runtime (two instances of the same app running at the same time), check the GetSessionInstanceIdentifier API.
|
6,089,891 | 6,089,968 | Invalid argument errno on connect() | I'm writing a program that basically perform server-client relationship.
When i run my client (with the relevant params, when the server is already running), i get the following errno message:
Invalid argument
Here's a part of the relevant code:
if(argc != NUM_OF_ARGS)
{
fprintf(stderr,"usage: Client <CLIENT NAME... | connect expects as third parameter the size of the struct that the second argument points to. See man 2 connect for details.
|
6,090,096 | 6,090,208 | _wsopen_s with _O_U8TEXT flag, returns 0 to buffer, inbetween chars, and 4 inbetween russian chars. VS2010 | If I input a UTF-8 encoded file like,
example.html
<html>
<head>
<meta http-equiv=Content-Type content="text/html;charset=utf-8">
<title>Текст на русском</title>
Where "Текст на русском" - Is text in russian
#include <string>
#include <ios>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <io.... | It looks like _O_U8TEXT causes _read to convert from UTF-8 to UTF-16. You should probably be reading using high-level Unicode functions like getwc when opening a stream in a unicode mode. You could use _wfopen_s with L"rt, ccs=UTF-8", or if you need the sharing support you could use your existing _wsopen_s call followe... |
6,090,306 | 6,090,529 | Unexpected compilation problem with g++ -std=c++0x | I have some compilation problems pushing back elements of type T to a vector when compiling with g++ -std=c++0x.
This is a minimal example:
#include <vector>
using namespace std;
class A {
public:
A() { }
A& operator=(A &orig) {
return *this;
}
};
int main(int argc, char **argv) {
A a;
v... | The Assignable requirement imposted by the language standard on the standard container elements requires the t = u expression to be valid even if u is a const object. The requirement was defined that way since C++98 (see 23.1/4)
You violated that requirement, since your assignment operator does not accept const objects... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.