question_id
int64
25
74.7M
answer_id
int64
332
74.7M
title
stringlengths
20
150
question
stringlengths
23
4.1k
answer
stringlengths
20
4.1k
5,914,334
5,914,341
Debugging C++ in Linux
After using Visual Studio for a week, I find CodeBlocks and other IDEs in Linux far inferior. I don't know if I am missing something, but I would love to have an IDE like VS in Linux. I have tried gdb, but I find it difficult to use. For instance, is there anything in Linux that can inspect values of a linked list like...
Yes, the Data Display Debugger, or DDD, displays data structures graphically while debugging. Having said that, if you are writing your own linked list class in C++, you are not really taking full advantage of the language. Why not use the already fully-debugged std::list?
5,914,393
5,915,229
Intersection of a function and a line
I am trying to find a way to find the first point of intersection between a function and a line. I don't know if it is even possible though. The idea is, that I have a line segment, and then I have a box that is rotating while it moves through 2space. I have made these two functions that represent the position of one o...
1) Represent the line with the equation A*x+B*y=C, such that if it passes through (x1,y1) and (x2,y2) then the equation is x*(y2-y1)+y*(x1-x2)=x1*y2-x2*y1. 2) The signed distance of any point (xp,yp) to the line is : d = (A*xp+B*yp-C)/sqrt(A*A+B*B) or d=( yp*(x2-x1)-xp*(y2-y1)+x1*y2-x2*y1 )/sqrt((x2-x1)^2+(y2-y1)^2)...
5,914,399
5,914,468
How to convert local object coordinates to world coordinates?
I need a simple way to convert my objects coordinate into world coordinates, so that a can locate them in that coordinate system and do collision detection?
First, some background. In 3D graphics, you need to worry about several vector spaces: Model space - these are usually the coordinates you specify to OpenGL World space - coordinates are specified with respect to some central point in the world. View space - coordinates are specified with respect to the camera Project...
5,914,422
5,914,697
Proper way to initialize C++ structs
Our code involves a POD (Plain Old Datastructure) struct (it is a basic c++ struct that has other structs and POD variables in it that needs to get initialized in the beginning.) Based one what I've read, it seems that: myStruct = (MyStruct*)calloc(1, sizeof(MyStruct)); should initialize all the values to zero, as do...
In C++ classes/structs are identical (in terms of initialization). A non POD struct may as well have a constructor so it can initialize members. If your struct is a POD then you can use an initializer. struct C { int x; int y; }; C c = {0}; // Zero initialize POD Alternatively you can use the default constr...
5,914,443
5,914,871
QWebPage, getting the mime type
I am wondering how I can get the mime-type of the current page using a QWebPage. Also, if possible, I would like to be able to do this using the HEAD request so I know not to download the whole page if it's not the correct mime-type. Any ideas?
It is possible. You will want to use QNetworkAccessManager, QNetworkRequest, and QNetworkReply classes. Here's an (untested) example, but should get you started with retrieving the mime-type of a page using a HEAD request: class TestClass: public QObject { Q_OBJECT public: TestClass(); void run(); public s...
5,914,484
5,914,539
Detecting floating point software emulation
I'm working on an application where runtime speed is more important than precision. The number crunching involves floating point arithmetic and I'm concerned about double and/or long double being handled in software instead of natively on the processor (this is always true on a 32-bit arch right?). I would like to cond...
The Floating-point unit (FPU) on modern x86 is natively double (in fact, it's even bigger than double), not float (the "32" in 32-bit describes the integer register widths, not the floating-point width). This is not true, however, if your code is taking advantage of vectorized SSE instructions, which do either 4 singl...
5,914,499
5,914,594
Proper place in nests to put cout
EDIT: Changed to a boolean flag, but still prints more than it should: string line; // a string to hold the current line while(getline(myFile,line)) { bool old_count = false; // to help determine whether the line has been output yet for (unsigned int i = 0; i < line.length(); i++) { string test = line.substr( i, ...
Try changing the int flag for a bool flag, like the following: while(getline(myFile,line)) { bool old_count = false; // to help determine whether the line has been output yet bool second_flag = false; for (unsigned int i = 0; i < line.length(); i++) { string test = line.substr( i, targ_length ); if ( strcmp(w...
5,914,992
5,915,176
C++ Initializing a Global Array
Hey everyone. I am an experienced java programmer and am just learning C++. Now I have a bit of a beginner's problem. I have an array variable x of type int. The user will input the size of x in method B. I want to use x in method A. void method A() { using int x [] blah blah blah } void method B() { int n; cin >>n; ...
If you actually want an array and not a vector, and you want that array dynamically sized at runtime, you would need to create it on the heap (storing it in a pointer), and free it when you're done. Coming from Java you need to understand that there's no garbage collection in C++ - anything you new (create on the heap...
5,915,125
5,915,267
fftshift/ifftshift C/C++ source code
Does anyone know if there is any free and open source library that has implemented these two functions the way they are defined in matlab? Thanks
Or you can do it yourself by typing type fftshift and recoding that in C++. It's not that complicated of Matlab code. Edit: I've noticed that this answer has been down-voted a few times recently and commented on in a negative way. I recall a time when type fftshift was more revealing than the current implementation, b...
5,915,215
5,924,781
wxDialog works fine but a wxFileDialog call results in program not terminating
Similar problem to last time. I run the code, exit it. The GUI disappears and it appears to have been fully exited but I check my process list and the code is there still holding memory. I've narrowed it down to a call to wxFileDialog. I don't understand what I'm doing wrong because I'm calling much in a similar way as...
Problem is a conflict with OpenCV (specifically HighGUI). To avoid this problem and the OLE error problem, override the WxWidgets initialize base class virtual as follows: bool MywxApp::Initialize( int& argc, wxChar **argv ) { ::CoUninitialize(); return wxApp::Initialize( argc, argv ); }
5,915,463
5,915,517
linking problem on linux (can't find the name of the appropriate library)
I trying to use a library (http://code.google.com/p/qxmpp/) but I can't find the name of the library to link it to. I want to understand how can you find out the name of the library to use in the linking parameters.
Looks like that is a source archive only -- no binaries included. Have you built the library from it? Where did the build process put it? /usr/lib or /usr/local/lib would be usual suspects, but read the build and install documentation in the package.
5,915,753
5,920,190
Generate a plane with triangle strips
What would be the best algorithm to generate a list of vertices to draw a plane using triangle strips? I'm looking for a function which receives the plane's width and height and returns a float array containing correctly indexed vertices. width represents the number of vertices per row. height represents the number of ...
Thanks you all. I've coded this. Is it correct? Or is the generated strip somehow wrong? int width; int height; float* vertices = 0; int* indices = 0; int getVerticesCount( int width, int height ) { return width * height * 3; } int getIndicesCount( int width, int height ) { return (width*height) + (width-1)*(...
5,915,805
5,915,936
Accessing a C++ .lib library from c#
I have a c++ library file (.lib). How can I access the functions within it from C#? I have read that I could wrap the library file in a c++ dll and expose the functions that way. Is that the only way? I am not the owner of the code, so my options are limited.
Wrap the C++ lib with a C++/CLI assembly. C++/CLI allows you to mix managed and unmanaged code, serving as a bridge between C# and native C++. It's actually very straightforward and relatively easy to do, although it can get tedious if you have a lot of classes/functions to wrap. Here is one example.
5,916,040
5,916,068
C++ macros to ensure used memory is freed?
So I am a bit of a n00b and was reading about new, delete, and pointers, and I am certain that I will forget too many deletes over the course of my life. So I was wondering if a macro like the following would be more trouble than it's worth. #define withObject(ptr, value, BODY) \ { ...
No, do not do this. It won't prevent either memory leaks or stray pointers. Instead, read up on smart pointers. The current standard provides one in the shape of auto_ptr, but many more (and better ones) are available, depending on your C++ platform. Also, I suspect you may be over-using new and delete - they should be...
5,916,062
5,916,278
Qt Creator Code File Refactoring
I was wondering if anyone know of a quick and easy way to refactor the code files in my QT Project using QTCreator? Specifically I am trying to organize my source files and Its a bit of a pain to have to go back into the project file and change the filepath for each file. Not to mention moving a dialog class is even wo...
The only file renaming/moving support that is "integrated" (i.e. it updates your project file automatically) is using the active project pane with your file list, rightclick and select "rename", using "../../some/new/dir/name.cpp" to move your files. It will of course not update any #include statements, but will save y...
5,916,239
5,916,268
std::advance behavior when advancing beyond end of container
What is the behavior of std::advance when you have say: std::vector<int> foo(10,10); auto i = foo.begin(); std::advance(i, 20); What is the value of i? Is it foo.end()?
You are passing the foo size by advancing to 20th position. Definitely it is not end of the vector. It should invoke undefined behavior on dereferencing, AFAIK. Edit 1: #include <algorithm> #include <vector> #include <iostream> int main() { std::vector<int> foo(10,10) ; std::vector<int>::iterator iter = foo...
5,916,364
5,919,461
Communicate between c# interface application and injected to another process dll
My application inject dll(written using c++) to another process and send some information to the interface form. Interface was made using MFC. Injected code communicates with interface via sending messages WM_COPYDATA like this: ::SendMessage(hWnd, WM_COPYDATA, 0, (LPARAM) &cd); and interface form has method for rec...
WPF handles messages and handles a bit different than you are used to. Read this article to understand what is possible and what is not. An important part of this article: All WPF elements on the screen are ultimately backed by a HWND. When you create a WPF Window, WPF creates a top-level HWND, and uses an HwndSource ...
5,916,560
5,916,621
Finding the text "space" value in pixels
With dealing with fonts, is there a way to figure out what the space between two characters should be if it was "1 2"? If it is known in C++ or C#, I don't mind. If it is in C++, I will marshal it over, it if is in C#, I will save it to a file and load it in C++. I tried taking a look at the TextMetric structure but it...
If you want metrics of how text will be rendered you need to provide the text. You would need to provide the ascii space character. Modern systems using Kerning to adjust spacing and make text look more attractive.
5,916,619
5,917,511
Boost binary static_visitor and apply_visitor
I have the following code: typedef boost::variant<LandSearchParameter, WaterSearchParameter> SearchParameter; enum Visibility{ CLEAR, CLOUDY, FOG, SMOKE }; class DetectionGenerator : public boost::static_visitor<double>{ public: DetectionGenerator(const EnvironmentalFactors& factors); double...
@Boaz Yaniv's answer is 100% correct. The boost::apply_visitor<> docs state directly: Overloads accepting two operands invoke the binary function call operator of the given visitor on the content of the given variant operands. Yaniv's suggested approach for remedying that – taking a Visibility object in the visitor's...
5,916,681
5,916,692
Adding method to library
I've been recently writing simple game in C++ with SFML. Here's my question: In SFML library there is a template class Vector2<T> (specifically I'd be using Vector2f). Unfortunately, it doesn't have any method to rotate itself, so I came with the idea to write one. But as I wrote: template<typename T> void Vector2<T>::...
What you're thinking of is called "monkey patching" or categories and is not available in C++. You can derive from that class to add that functionality or create a friend function to implement what you're trying to do. (Functions defined as friend inside a class definition have access to an object's internal state)
5,916,808
5,916,919
diagonally reflect a matrix
I'm not sure if this question has been either asked or quite possibly already answered. If I start with an original 3x3 matrix: 1 2 3 4 5 6 7 8 9 , how would I produce the following 3x3 matrix: 9 6 3 8 5 2 7 4 1 ??
Since you're trying to reflect about the secondary diagonal (that's NOT transposition), here's the code, a slightly modified copy of Peter's: for (int i = 0; i < n; i++) { for (int j = 0; j < i; j++) { int temp = a[i][j]; a[i][j] = a[n - 1 - j][n - 1 - i]; a[n - 1 - j][n - 1 - i] = temp;...
5,916,852
5,916,950
C++, template specialization problem
I am having problems with template class specialization, see the code bellow, please. template <typename T> class Point { private T x, y; typedef T Type; public: Point ( const T & x_, const T & y_) : x ( x_ ), y ( y_ ) {} }; template <typename Item> struct TItems { typ...
You can, yes, but your syntax isn't quite right. As it stands, the compiler doesn't know what T is, so you have to tell it that it is a template parameter: template<typename T> class Container<Point<T> > { };
5,916,894
5,916,974
Threads Waiting for Event Do Not Always Catch Event Signal
I have an application wherein multiple threads wait on the same event object to signal. The problem I am seeing appears to be a type of race condition in that sometimes some threads' wait states (WaitForMultipleObjects) return as a result of the event signal and other threads' wait states apparently don't see the even...
Use conditional variable as in PulseEvent description. The only problem is that native conditional variable on windows was implemented starting from Vista so older system like XP doesn't have it. But you can emulate conditional variable using some other synchronization objects (http://www1.cse.wustl.edu/~schmidt/win32-...
5,917,182
5,924,406
Get size of excel cell in pixels
I am trying to programatically (C++ but VBA explanations are OK) get the size of an excel cell in pixels. The excel application gui shows the size of the cell as: Width: 8.28 (160 pixels) Height: 24.6 (41 pixels), Font is Arial 20 pt. Using an excel range I can get the: ColumnWidth: 8.3, RowHeight: 24.6 Range Width: 96...
The conversion from points to pixels depends on your DPI setting. There are 72 points to an inch, so if you have 96 points that's 4/3 of an inch. If your DPI (in Display Properties) is 120 then that works out to 160 pixels. In other words, pixels = points * DPI / 72. However, this doesn't take zoom into account. Active...
5,917,425
7,235,460
Porting code from c++ to c# - Encrypting with RSA PKCS#1 private key
I'm trying to port this piece of code from c++ to c#: ... strPrivateKey = "someBase64EncodedPrivateKey"; long sizeKey = DecodeBase64(strPrivateKey, pKey); const unsigned char* _pKey = pKey; d2i_RSAPrivateKey(&pRSA, &_pKey, sizeKey); ... RSA_private_encrypt(sizeOfMessage, pMessage, pSignature, pRSA, RSA_PKCS1_PADDING);...
Fixed it by adding: At the begin of the private key: "-----BEGIN RSA PRIVATE KEY-----\r\n" After each line of my private key : "\r\n" At the end of my private key: "-----END RSA PRIVATE KEY-----" And finally, I used OpenSsl.NET as library. This post originally solved my problem: Decrypting RSA using OpenSSL.NET with ...
5,917,510
5,917,725
Interview question interface implementation
Could your please help me with following interview question. Given function ‪Sleep(int seconds) implement following interface so timers could be used: function ‪void CreateTimer(void (*func)(), int seconds) that her purpose is to create timer function ‫‪void StartTimers() that her purpose to start all the timers Ever...
EDIT 1: Use the questions API. EDIT 2: Oops, didn't call q.pop(); This sounds like a job for std::priority_queue, ordered by deadline. //pseudo-code class Job; std::priority_queue<Job, std::vector<Job>, CompareLessByDeadline> q; CreateTimer(func, deadline) { q.push(Job(func, deadline)); } StartTimers() { now = 0;...
5,917,588
5,917,726
VS2003 can't find .h file even after addition to "additional incl. dirs"
I have file which needs to include blah.h in another project. I've tried adding the directory that holds the blah.h file to Project -> Project Properties -> Additional include directories but I keep getting a "C1083: Cannot open include file: blah.h: No such file or directory". I've tried absolute and relative paths...
Get the build (or at least this part of the build) working using: #include "c:/path/to/blah.h" If/when VS stops complaining about not being able to find blah.h, cut-n-paste the path used in the #include into the "Additional include directories". Remember that the "Additional include directories" field should have the...
5,917,678
5,917,690
Why isn't the const qualifier working on pointer members on const objects?
I know this has been asked a lot, but the only answers I could find was when the const-ness was actually casted away using (int*) or similar. Why isn't the const qualifier working on pointer type member variables on const objects when no cast is involved? #include <iostream> class bar { public: void doit() {...
When a foo instance is const, its data members are const too, but this applies differently for pointers than you might at first think: struct A { int *p; }; A const obj; The type of obj.p is int * const, not int const *; that is, a constant pointer to int, not a pointer to constant int. For another way to look at i...
5,917,950
5,918,444
Weird memory corruption
This error only is occuring when I build with the WinDDK nmake compiler in 'free' (release), which performs optimizations. I can't reproduce this in the 'checked' build or compiling with VS. Here is pseudo-code of what is happening in my code: main() { //variable init and other code fprintf(log, "pre nullValue: ...
Not a completely slamdunk. But it is very likely that the stack is getting imbalanced. In the debugger (yes, you can debug the release build), check the value of the ESP register before and after the call. It should be the same. It won't be if the calling convention for the function is wrong. Like __stdcall vs __c...
5,917,956
5,918,008
Why is indentation in empty lines bad?
Every FOSS project I know has rules against trailing whitespace in code. But I think it's very natural to continue the current indentation on the next line: int main() { ....int a = 42; .... ....return a; } But git for instance throws warnings anyway. So my question is: Why are those tabs inside the current indentatio...
It is probably because merging patches with useless whitespace is harder than it should be. diff(1) and patch(1) treat spaces and tabs as important content. (Ask any Makefile or .py source file -- they are important!) And if your "blank line" has four spaces on it, and my "blank line" has eight spaces on it, any attemp...
5,917,969
5,918,076
Doubly-Circular Linked list. New node not inserting. C++
So this new node is supposed to be inserted after the last node. I can't figure out why that is not happening. Note: The list has multiple elements before this function is called (approx 5) so as of now it only has to work for that case. The last node should point to the top node and the top->prev pointer should point ...
This code has a few issues. First, if you're going to do "insertAfterLast" frequently, you should use "top->prev" to get a pointer to the last element in constant time; otherwise building a list will require quadratic (O(n^2)) time. Second, in any real project implementing a circular linked list from scratch is almost ...
5,917,996
6,590,951
Dynamically combine Boost.Spirit.Qi rules at runtime (arbitrary number of alternatives)
I was wondering whether there is a way in Boost.Spirit.Qi to dynamically combine an arbitrary number of rules at runtime. The inner workings of Boost.Spirit are still a bit of a mystery to me, but since rules are implemented as objects it seems feasible. My motivation is to make certain parts of my grammar easily exten...
Yes I'm not sure to really understand how it work internally but you do not copy all the rules in your for loop (only the left one) so this seems to work: std::vector<qi::rule<iterator_t, void(int&)>> rules; rules.push_back(qi::char_('a')[qi::_r1 = px::val(0)]); rules.push_back(qi::char_('b')[qi::_r1 = px::val(1)]); r...
5,918,005
6,131,727
QT Style Comments (Intellisense?)
I noticed in 2.1 of QTCreator, that they now have a sort of intellisense similar to that of Visual Studio. I know intellisense is Microsoft's name for this concept of the helpful tooltip that pops up giving you a description of the method, parameters etc so i don't know what this is actually called. Does anyone know ho...
I've been wanting to do this as well. I found this thread over on qtCentre.org where someone has integrated their own docs into the QT Creator Tooltips. I haven't tested it myself, but it sounds reasonable: http://www.qtcentre.org/archive/index.php/t-40324.html?s=98d48c38547da14b0725e5106d83c315 To use your own docum...
5,918,024
5,918,050
IntelliSense: no operator >> matches these operands
I am trying to figure out why I keep getting the compiler error IntelliSense: no operator ">>" matches these operands with the code below. Would appreciate any help given. Thanks #include "stdafx.h" #include <string> #include <iostream> using namespace std; int main(void) { int n;//number of resources we wil...
Hint: cout <<"What is number of resources to be shared?"<< cin >> n; Is the same as: cout <<"What is number of resources to be shared?"<< cin >> n; Perhaps << should be followed by something like std::endl;, just or changed to a ;.
5,918,043
5,920,107
Phonon problem in Windows 7 with code compiled in XP
I have some code compiled using Visual Studio 2010 (C++), with Qt for the GUI and Phonon to show some videos. I compile and run the code in a Windows XP machine and everything works fine. The videos and controls are shown correctly, and the same in other Windows XP machines. But at the moment that I try to use a Windo...
When deploying your application to a different computer, make sure you don't forget to copy the Phonon backend. Not just the DLL contained in it (the ds backend for me), but also the directory itself. That is -Application Directory ¦-myexe.exe ¦-phonon_backend ¦-phonon_ds94.dll Furthermore the Phonon backend on ...
5,918,121
5,918,156
What's the equivalent of cout for output to strings?
I should know this already but... printf is to sprintf as cout is to ____? Please give an example.
It sounds like you are looking for std::ostringstream. Of course C++ streams don't use format-specifiers like C's printf()-type functions; they use manipulators. Example, as requested: #include <sstream> #include <iomanip> #include <cassert> std::string stringify(double x, size_t precision) { std::ostringstream o;...
5,918,312
5,918,369
What rules to follow for a function to use NRV optimization
What rules or tips should I follow to enable a function to use NRV (named return value) optimization in a function? I assimilated these tips from different places, but don't know if it my understanding is correct: the object to be returned should not have any name inside the function (then why is it called NAMED retur...
If you mean NRVO (Named Return Value Optimization) as opposed to RVO (Return Value Optimization), then the object has to be named inside the function. Otherwise it would only be eligible to RVO, not NRVO. So there's a pretty good reason for calling it Named Return Value Optimization. Check out the following examples: R...
5,918,451
5,918,484
Why getline skips first line?
In the following code, getline() skips reading the first line. I noted that when commenting the "cin >> T" line, it works normally. But I can't figure out the reason. I want to read an integer before reading lines! How to fix that? #include <iostream> using namespace std; int main () { int T, i = 1; string lin...
cin >> T; This consumes the integer you provide on stdin. The first time you call: getline(cin, line) ...you consume the newline after your integer. You can get cin to ignore the newline by adding the following line after cin >> T;: std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); (You'll need #in...
5,918,512
5,918,530
Writing a tokenizer, where to begin?
I'm trying to write a tokenizer for CSS in C++, but I have no idea how to write a tokenizer. I know that it should be greedy, reading as much input as possible, for each token, and in theory I know how I could put that in code. I have looked at Boost.Tokenizer, and it seems nice, but it doesn't help me whatsoever. It s...
Writing a "correct" lexer and/or parser is more difficult than you might think. And it can get ugly when you start dealing with weird corner cases. My best suggestion is to invest some time in learning a proper lexer/parser system. CSS should be a fairly easy language to implement, and then you will have acquired an am...
5,918,607
5,918,618
C++ class use of undefined type
I have a class that I made that I am using in thread above the class. Even though I did a prototype of the class at the top it still throws off those errors error C2027: use of undefined type 'foo' class foo; DWORD WINAPI demo(LPVOID param) { foo a; } class foo { public: int x; };
Even though I did a prototype of the class With a forward declaration of the class you can create pointers and references to the class. This is because pointers/references are represented the same across all classes/structs/etc. They're all just addresses of memory. So, for example, you could create a second class ...
5,918,631
5,918,666
C++ OpenGL Game Timer
I am attempting to make a simple game using C++ and OpenGL and I haven't been able to find any good tutorials on creating a simple tick or a timer system for a game i also would like to use an little external librarys as possible. Any help is appreciated. I am using Win32 and C::B IDE...MingW complier.
Check this pages: http://wiki.allegro.cc/index.php?title=Timers#How_to_use_them.3F http://www.koonsolo.com/news/dewitters-gameloop/ Maybe you can get more answers on Gamedev Stackexchange.
5,918,909
5,918,993
C++ memory errors at program exit
I am writing a client-side app that communicates to a server app through sockets. I'm currently experiencing weird behavior where the application finishes running properly, but then I get many lines like the following thrown on the screen afterwards. *** glibc detected *** ./sll_client: free(): invalid next size (fast)...
The invalid writes of size 4 are almost certainly what's causing your problem. You're stomping on memory you don't own, most likely just before or just after a region of memory that's been dynamically allocated. The invalid reads of size 4 are problematic too, but aren't causing the output you're getting. Fix them anyw...
5,918,930
5,918,994
C++ OpenGL gluLookAt help
I have been attempting to use gluLookAt but i have come across some issues...my first is what is the default position of the camera, whenever i try to use it, my whole scene seems to rotate sideways and up.... my second question is....from what i have read it is gluLookAt(Posx,Posy,PosZ,yaw,pitch,roll,then three up vec...
You seem to have gotten some bad information about the arguments to gluLookAt(). From the OpenGL 2.1 online documentation, the arguments should be as follows: eyeX, eyeY, eyeZ: World coordinates of camera location centerX, centerY, centerZ: World coordinates of camera aimpoint (what it's looking at). This point...
5,919,300
5,919,310
Why does this program swap the values?
I have the following code: #include "stdafx.h" #include <iostream> using namespace std; #include <conio.h> #include <cstring> #include <iomanip> void swap(long a, long b) { long temp; temp=a; a=b; b=temp; } int _tmain(int argc, _TCHAR* argv[]) { int x = 5, y = 3; cout << x ; cout << y << e...
Your swap function isn't being called at all. One of the Standard Library includes that you have included is pulling in <utility>, which declares a function template named swap in the std namespace. Since you are using namespace std;, that swap function is being brought into the global namespace and it is called inste...
5,919,699
5,919,804
Proper Usage of SetThreadAffinityMask
There are 12 cores, and 12 threads running..I want to bind 1 thread to each core. this is what I call at the beginning of each thread. int core=12; SetThreadAffinityMask(GetCurrentThread(),(1<<core)-1); This is what I have...I don't know if this would be the proper way to call it. I'm not sure if i'm understanding ho...
The second parameter to SetThreadAffinityMask() is a bit vector. Each bit corresponds to a logical processor: a CPU core or a hyper-thread. If a bit in the second parameter is set to 1, the thread is allowed to run on the corresponding core. For core equal to 12, your mask (1<<core)-1 contains 0..11 bits set, so every ...
5,919,855
5,919,869
C++ references Vs C# references
What are the similarties/differences between a C++ reference and a C# reference ? Edit: I'm talking about Object references,as I'm a newbie I was unaware that such a simple line would cause ambiguity,as I have read. Whenever the term "reference" is used,its in context to Object reference,otherwise its explicitly qu...
C# references are closer to C++ pointers than to C++ references. C# references can be null and have assignment semantics similar to pointers. The difference is that they are black boxes(you can't convert them to integral types) and you can't do arithmetic on them. They also can only point to reference types. C++ refere...
5,919,878
5,919,909
Setting a char array with c_str()?
char el[3] = myvector[1].c_str(); myvector[i] is a string with three letters in. Why does this error?
It returns type char* which is a pointer to a string. You can't assign this directly to an array like that, as that array already has memory assigned to it. Try: const char* el = myvector[1].c_str(); But very careful if the string itself is destroyed or changed as the pointer will no longer be valid.
5,919,928
5,919,952
Qt Need to bring Qt application to foreground called from win32 application
I have a simple win32 application that uses the createProcess method to call Qt application. The problem is that I like to bring the Qt application to the foreground. Who is responsible for this? The parent win32 app or the Qt application?
The application that currently has the foreground focus is the only one that is allowed to change the foreground focus. You need to use the SetForegroundWindow function to exercise this right. The "Remarks" section in the documentation contains an applicable list of restrictions: The system restricts which processes c...
5,919,996
5,920,028
How to detect reliably Mac OS X, iOS, Linux, Windows in C preprocessor?
If there's some cross-platform C/C++ code that should be compiled on Mac OS X, iOS, Linux, Windows, how can I detect them reliably during preprocessor process?
There are predefined macros that are used by most compilers, you can find the list here. GCC compiler predefined macros can be found here. Here is an example for gcc: #if defined(WIN32) || defined(_WIN32) || defined(__WIN32__) || defined(__NT__) //define something for Windows (32-bit and 64-bit, this part is common)...
5,920,335
5,925,739
Get website thumbnail snapshot with C++
Is there any way to capture an image of a web page using a C++ CGI? I've been searching high and low, and while I've found a number of implementations in everything from Perl to C#, haven't been able to find any implementations in C++. The idea is for a user visiting a site to be able to specify a URL. The script wou...
You need to render the webpage in order to create a snapshot. To render the page in C++ you need to include a browser engine. You can do this easily using Qt (a toolkit for c++). This is taken from the documentation of Qt and is all you need to show a webpage. QWebView *view = new QWebView(ui->centralWidget); view->loa...
5,920,456
5,920,529
Pushing vector member into vector during expand: vector.push_back(vector[0])
I'm doing custom vector class in C++. I have a question about such code: vector<T> vec; vec.push_back(one); vec.push_back(two); vec.push_back(vec[0]); Definition of push_back is as follows: void push_back(const T & v) to avoid unnecessary copying. It's implementation looks like if (size == cap...
In some STL implementations I've seen (like the current VS2010 for instance) they first check whether a pointer to the new data item to be added is within the current extent of the vector buffer. If so, the index position (not pointer!) to the location of the data within the vector is found. This will not change even ...
5,920,499
5,931,171
How to use FMOD with C++?
I'm trying to create a simple mp3 player using FMOD: #include "inc/fmod.h" int main() { FSOUND_Init(44100, 32, 0); return 0; } Trying to compile the program I get the following error: holle@x300:justmp3$ pwd /media/daten/Entwicklung/C/justmp3 holle@x300:justmp3$ LD_LIBRARY_PATH=$(pwd)/lib holle@x300:justmp3$...
FSOUND_Init is an FMOD 3 API function, you are using FMOD Ex so that function doesn't exist. To initialize FMOD Ex you should include "fmod.hpp" and use the functions: System_Create to create the FMOD system object, then System::init to initialize, followed by System::createStream to load your MP3, then System::playSou...
5,920,585
5,920,683
Compiler Error for unknown reasons (C++)
I get a compiler error (C2061) in MSVS C++ 2010 IDE, when I try to compile. I simply got no clue as to why it occurs, as I can see no apparant error. #pragma once #ifndef _CCOMPONENT_H #define _CCOMPONENT_H #include "CGame.h" class CComponent { public: CComponent(CGame &game); ~CComponent(); protected: v...
Your headers try to #include each other - you can't do that. Remove the #include of the game header from the component header and use a forward declaration of CGame instead. CComponent(class CGame &game); On a design point, problems like this usually mean you have got something wrong. I think it unlikely that compone...
5,920,754
5,927,393
Is it possible to get the original value of a number, after several multiplications **with overflow**?
Summary: Is there a way to do that? Here's what I mean: suppose I have an unsigned int number. Then I multiply it several times(and there's overflow, which is expected). Then is it possible to "revert" the original value back? In details: It's all about Rabin-Karp rolling hash. What I need to do is: I have the hash of...
Extended Euclidean algorithm is a good solution for this, but it's too complicated and hard to implement. There's a better one. And there's another way to do this (thanks to e friend of mine (: ) There's a nice article in wikipedia - modular multiplicative inverse using Euler's theorem in the case, when m and a are co...
5,920,839
5,920,857
Vector subscript out of range
I'm getting the vector subscript out of range error. I've had it before, but it prints 'before' but it doesn't print 'after' so I'm confused at to why one of these lines would be causing it. cout << "before" << endl; vector<vector<char>> animals; vector<vector<char>> food; vector<char> other; int lastline = 0; for(int ...
If c is the count of elements in any vector, then the mistake is simply that in a vector with N items the item indexes are 0...[N-1] and not 1...N. Therefore, make this correction: for(int i=0; i < (c); i++) { By the way, in C-like languages the archetype of a for loop that iterates N times is, not coincidentally: for...
5,920,853
5,920,883
How to open a folder in %appdata% with C++?
As you all know, the appdata folder is this C:\Users\*Username*\AppData\Roaming on windows 7 Since my application will be deployed on all kinds of Windows OSes i need to be able to get the folder 100% percent of the time. The question is how do you do it in C++? Since i don't know the the exact Windows OS it could be...
For maximum compatibility with all versions of Windows, you can use the SHGetFolderPath function. It requires that you specify the CSIDL value for the folder whose path you want to retrieve. For the application data folder, that would be CSIDL_APPDATA. On Windows Vista and later, you should use the SHGetKnownFolderPat...
5,921,186
5,921,221
How to convert win32 CHAR(char) type to std string?
Im using the win32 function ReadFile: CHAR lpBuffer[256]; DWORD nBytesRead; DWORD nCharsWritten; ReadFile(hPipeRead,lpBuffer,sizeof(lpBuffer), &nBytesRead,NULL) || !nBytesRead) now im catcing the response from stdout in to lpBuffer with this i like to convert it to std string , t...
You need to specify the size of the string: std::string szReturnlpBuffer(lpBuffer, nBytesRead); because otherwise it reads till it finds a null character, which causes undefined behavior when it gets outside lpBuffer's memory.
5,921,260
5,921,472
Filling std::map with std::transform (error: cannot deduce argument)
I'm trying to fill std::map with std::transform. Next code compiles without error: std::set<std::wstring> in; // "in" is filled with data std::map<std::wstring, unsigned> out; std::transform(in.begin(), in.end() , boost::counting_iterator<unsigned>(0) , std::inserter(out, out.end()) , [] (std::wstring _str, unsi...
This is a bug in the Visual C++ library implementation. The following program demonstrates the issue: #include <utility> int main() { &std::make_pair<int, int>; }; This program yields the error: error C2568: 'identifier' : unable to resolve function overload In the C++ language specification, make_pair is not a...
5,921,289
5,921,319
Events in QGraphicsView
I'm having trouble getting events in QGraphicsView working. I've subclassed QGraphicsView and tried to overload the mousePressEvent and wheelEvent. But neither mousePressEvent nor wheelEvent get called. Here's my code (Edited a few things now): Declaration: #include <QGraphicsView> #include <QGraphicsScene> class rasIm...
You're not getting the events because they're being handled by the scene object you're creating, not your class. Remove the QGraphicsScene *scene; from your rasImg and try something like this for the constructor: rasImg::rasImg(QString file) : QGraphicsScene(QRect(0, 0, MaxRow, MaxCol)) { addText("HELLO"); setBackg...
5,921,418
5,921,795
Error on char array declaration in GCC 3.3.4
int main () { char b[100]; for (int i = 1; i <= 10; i++ ) scanf ("%c%*c", b[i]); } but am getting the error 'Format arguemnt is not a pointer' How can i declare an array to get all values form the user? EDIT : #include <cstdio> #include <stdlib.h> using namespace std; int p[100], b, bc; char bb[100]; ...
#include <cstdio> Apparently, you're coding in C++ #include <stdlib.h> Oh! Wait. It is C after all. @coderex: make up your mind what language you're using using namespace std; Oh! It is C++. My answer does not consider the C++ specifics which I don't know. int p[100], b, bc; char bb[100]; If you can avoid using glo...
5,921,460
5,921,798
How to setup GTK+ to develop with Code::Blocks on Ubuntu Linux
I am trying to develop a GTK+ application on Ubuntu 11.4, using Code::Blocks. www.gtk.org has instructions on building GTK+ from source, that looked complicated. But the Ubuntu package manager listed libgtk3-dev as a package that I installed. Code::Blocks I installed using the Ubuntu Software Center. Using the Code::Bl...
Assuming that you have located and installed the correct package. As of 2011, the current package was libgtk-3-dev then the pkg-config tool can be used to extract the linker and compiler flags - and with proper escaping in the Code:Blocks settings can inject the correct settings automatically. Open Code::Blocks Setting...
5,921,609
5,921,826
What is predicate in C++?
Can you give some example or a link to a topic.
A predicate is a C++ function returning a boolean or an object having a bool operator() member. A unary predicate takes one argument, a binary takes two, and so on. Examples of questions predicates can answer for a particular algorithm are: Is this element what we are looking for? Is the first of two arguments ordered...
5,921,670
5,928,102
How to Google Mock a method called from a struct
Let's have this example: Class A{ public: int Get(); } In another file: A a; struct B{ int res = a.Get(); } I would need to Google Mock Get method, however, I will also need to call the real one. I have tried with #ifdef, and it seems to work. Then I decided to mock it in the #ifdef se...
Header file: class A{ public: int Get(); }; A a; Source file: int A::Get(){ .... } struct B{ return res = a.Get(); };
5,921,674
5,921,864
win32 CreateThread ,how to call the lpStartAddress parameter as c++ class function?
i was reading the thread that talking about my problem here: how to use CreateThread for functions which are class members after using the code from microsoft site here : How to spawn console processes with redirected standard handles i implemented this solution but there some problems like : i need to use the lpvThrea...
Ok. I think I know where you are heading now. How about something like this. Create the pipe in the class constructor and then use the hInputWrite handle in your class thread function (called from the static thread function. class MyClass { HANDLE hInputWrite; HANDLE hInputRead; SECURITY_ATTRIBUTES sa; ...
5,921,765
5,927,159
Use gsl on Mac 10.6.3
I recently have a project using GSL. After I installed the GSL package on Mac 10.6.3. I cannot compile my code. The gsl lib is located at /usr/local/lib, and the head file located at /usr/local/. When I compile my code I get the the following error. If I do not specify "-m32" in the makefile, it still gives the same e...
I'm not sure, but I think you'll need to link with GSL's BLAS library as well. Your x86_64 undefined reference seems to imply as much (blas.o is the hint I'm going on). Just add -lgslcblas to your LIBS variable.
5,921,851
5,921,985
C++ memcpy() tricky use, behavior understanding needed
Decompilation so as to fix an old program can be painful. As I'm a C# developer, there's something strange I don't understand. I would need a C++ tricks expert to help me understand the behaviour of "memcpy()". Here's what I play with: unsigned char sdata[] = { 0x54, ... many values (=4100)...
I do not undestand how does behave this with higher number of bytes than arrays destination length Is that about data types ? First, memcpy operates on bytes, not array elements. So if you want to copy an array int[10], for example, you tell memcpy to copy 40 bytes (10*sizeof(int)). So the argument passed to memcpy...
5,921,920
5,922,051
Difference between initialization of static variables in C and C++
I was going through the code at http://geeksforgeeks.org/?p=10302 #include<stdio.h> int initializer(void) { return 50; } int main() { static int i = initializer(); printf(" value of i = %d", i); getchar(); return 0; } This code will not compile in C because static variables need to be initialised...
It compiles in C++ because C++ needs to support dynamic initialization anyway, or you couldn't have local static or non-local objects with non-trivial constructors. So since C++ has this complexity anyway, supporting that initialization like you show isn't complicated to add anymore. In C that would be a big matter b...
5,922,119
5,922,217
Java and C++ pass by value and pass by reference
It is said that in Java method arguments are passed by value which is true for primitives and for objects, object's reference is passed by value. To illustrate consider the code: class Test { private static void dateReplace (Date arg) { arg = new Date (arg.getYear(), arg.getMonth(), arg.getDate() +1); ...
C++ does not have the same semantics as Java for values and references. At first, every type has the potential to be either passed by copy or by reference or by address (you can however prevent types to be passed by copy by hiding the copy constructor). The passing type the most closely related to Java's "by reference"...
5,922,248
5,922,320
c++ hooking to a different application, how to find thread id from process id?
I would like to add a hook to an application. I am using SetWindowsHookEx and I can create a system wide hook, but I want to create a hook for a particular application. I need to have thread id of the target application to hook it. I know title of the window, I know exe name and from these I can get window handle and p...
GetWindowThreadProcessId() returns the thread ID. You are erroneously assigning the thread ID to the process ID variable. Instead write: HWND windowHandle = FindWindow(NULL, _T("SomeOtherApp")); DWORD threadId = GetWindowThreadProcessId(windowHandle, NULL); HHOOK hook = ::SetWindowsHookEx(WH_CBT, HookCBTProc, hInst, th...
5,922,282
5,922,424
Easy c++ question regarding valarray
Most posts probably ask question as to why something is not working; mine is to ask why something IS working... I thought that the only way to dynamically allocate memory was with the use of new or malloc in cpp, but this is apparently wrong. The following code both compiles and works, but cannot figure out why! int x;...
The dynamic memory allocation is hidden inside of the constructor of the valarray class and still uses new or malloc in the end. Instead of valarray you could also use a vector. Both classes can be resized at runtime. That the complexity is hidden behind the interface of the classes is an advantage. You don't ever have...
5,922,295
5,922,415
How can I derive from a template twice, and have the subclasses interact?
Here's my problem: I wrote two base classes: Wire and CircuitComponent. The two were almost similar enough to derive from a common superclass, but not. Wire can only join with CircuitComponent, and CircuitComponent can only join with wire. The implementations were identical aside from type though, so naturally I though...
The minimally-invasive way to make your code compile is indeed to use a typedef, and either tag classes, or simply Enumerations: enum MeshType { MeshTypeWire, MeshTypeCircuitComponent }; template <MeshType thisType> class TwoTypeMesh { // calculate 'otherType' from 'thisType' (prevents usage mistakes): static ...
5,922,409
5,922,520
C++: When is it appropriate to define functions outside of a class
Possible Duplicate: When should functions be member functions? Are there situations when it is better to define functions outside of classes or should you use static functions inside a class?
There are some cases that have to be non-member functions: operator overloads can't be static member functions (they can be non-static member functions), and in particular most binary operator overloads work better as non-member functions because you get implicit conversion on the LHS and RHS for free operator overloa...
5,922,435
5,922,466
Correct use of const c++
I have this sample code ( below ), example1() method works with no problem, example2() is similar but I must force const_char to make it compile, although I consider as example1() method is not needed, example2() would be not needed either. My question is, how can I modify add() method to make both compile or how must...
You should do something like : Buffer<MyClass const*> because &item on a const MyClass is a Myclass const* not a MyClass*
5,922,455
5,922,512
Does a public static const variable break the encapsulation ideology?
I always seem to struggle with the decision of whether a value in a class which should be static and const should be public or private with a static public method for access. class DeepThought { public: static const int TheAnswer = 42; }; versus: class DeepThought { public: static int GetTheAnswer() { return T...
In a purely theoretical sense, the second option is the more correct. In the practical sense, I agree with you - wrapping the constant value with a getter function is useless and will be removed by the compiler anyway. In my experience, sometimes the simpler approach is better, even if it violates OOP somewhat. And a f...
5,922,695
5,922,843
Using boost::lambda to copy a container
I'm here learning how to use boost::lambda. One question I have is about member function calling. It's just a test, and I'd like to do this with boost::lambda, as there are, obviously, half a million ways to copy the elements from one container to another container. I have a list<int> which has 3 elements: std::list<in...
Did you try something like this? for_each(a.begin(), a.end(), bind(&std::vector<int>::push_back, &b, _1));
5,922,797
5,922,813
Allocating elements in C++ vector after declaration
Please refer to the code and comments below: vector<int> v1(10); cin>>v1[0]; // allowed cin>>v1[1]; // allowed // now I want v1 to hold 20 elements so the following is possible: cin>>v1[15]>>v[19]; // how to resize the v1 so index 10 to 19 is available.
You simply need to resize the vector before adding the new values: v1.resize(20);
5,922,847
5,922,897
make one arrays content into another 2d arrays rows & colums
I have this function that reads a textfile and sends the strings to an array and then from that function I send that array and number of elements to my constructor. Now my constructor creates a dynamic 2d-array(I hope). I would like my 2d-arrays rows and columns to be assigned values from the array received. heres my c...
In order to make a dynamic 2darray you must try s.th. like this: type** arr2d; arr2d = new type*[rows]; for(int i=0; i<rows; ++i) arr2d[i] = new type[cols];
5,922,881
5,922,896
Problem with MSVC includes
I'm working on making a library. Eventually I will use CMake but right now I'm just using MSVC. First my directory structure (as an example) will be as follows: LibRoot blah.h SubRoot bloop.h The way I used to include blah in bloop was by doing: #include "../blah.h" I looked at many other libraries and they ...
You need to add whatever directory LibRoot is in to the Additional Include Directories of the project's properties (on the C/C++ - General page).
5,922,907
5,922,927
using _wtol to convert with decimals
The function _wtol converts from a wide character string to a long. The problem is that it doesn't convert with decimals. I don't know enough c++ to come up with a workaround, so can someone suggest a workaround or an alternate conversion function that does convert with the decimal? Thx void button_click(void) { Edit_...
_wtof(), et al. See here.
5,922,992
5,923,021
Is there a way of disabling the old c style casts in c++
Possible Duplicate: How to find (and replace) all old C-style data type casts in my C++ source code? I'm currently refactoring some old code and the project I am working on has a policy of only using the new c++ style casts. I'm trying to make sure that I don't miss any but currently the approach I'm taking is quite...
If you use GCC, add -Wold-style-cast to the command line. That gives warnings, not errors, but you can always add -Werror, which turns warnings (all warnings) into errors. As for other compilers, it seems no other compiler has such a warning option. But that doesn't really matter: GCC is Free Software, and available on...
5,923,043
5,923,059
Forward declarations: templates and inheritance
When writing a framework I got following problem: I have class A and class B wchich is derived from class A. class A has a function wchich returns B*. Of course, it's not difficult: #include <iostream> using namespace std; class B; // forward declaration class A { public: B* ReturnSomeData(); }; class B...
Your forward declaration is incorrect. It needs to be: template <class Number> class B; ^ no argument list
5,923,297
5,924,005
Exceptions in bad stream
If a user was to enter a letter instead of an integer, the loop goes wild. I know how to get rid of that error cin.clear() and cin.ignore() But I haven't been able to understand why it happens. A character is represented by an integer from 0 to 255. And each number is 32 bit enough for the integer variable to handle.....
Why do they work like this: Well the stream operators >> and << are designed to read text (or human readable streams (or files)). Thus when used you are expecting a certain type of input that has a particular form: int a; stream >> a; // I expect the stream to contain an integer in human readable form. MyClass x; str...
5,923,310
5,928,112
Visual Studio 2010, Intellisense and PCH: what are the alternatives to ugly stdafx.h?
I recently switched to Visual Studio 2010 and for Intellisense not to take half a minute to show up when using boost libraries, Microsoft's suggestion seems to use precompiled headers. Except that I never used them before (except when forced to by Ugly ATL Wizards (TM)), so I searched around to figure out how they work...
Your problem basically seems to be that Intellisense is slow for Boost in VS2010? I don't have a direct solution for this problem, but could Visual Assist X be an option for you? I have used it in various versions of Visual Studio now and with great pleasure. Not a direct solution, but it might work for you.
5,923,389
5,923,534
Encryption algorithm
Do you know a good encryption algorithm that isn't too difficult to implement in c++ (but neither too easy)?
Look at this wonderful comics on AES. It explains the cryptographic background of the algorithm and you can practice by writing a high-performance implementation of one in different languages.
5,923,538
5,924,066
Getting Started with UnitTest++
This is the current code I have from their fundamental example: http://unittest-cpp.sourceforge.net/UnitTest++.html #include <unittest++/UnitTest++.h> TEST(FailSpectacularly) { CHECK(false); } int main() { return UnitTest::RunAllTests(); } The include exists but I'm receiving errors: undefined reference to U...
Found the answer here: http://comments.gmane.org/gmane.comp.lang.c%2B%2B.unittest%2B%2B.devel/13 Set the library path -L/usr/include and the library -lunittest++
5,923,612
5,923,729
Return Function Pointer to Self?
The following code does not compile..but is there some way to get a function pointer to return another function pointer that is equivalent to itself? typedef FunctionPtr (*FunctionPtr)(int, int); FunctionPtr Second(int, int); FunctionPtr First(int, int) { // do something return Second; } FunctionPtr Second(i...
This was the closest I got to in about 15 minutes...: #include <stdio.h> struct container { typedef container (*Ptr)(int, int); const Ptr _ptr; explicit container(Ptr ptr) : _ptr(ptr) { } operator Ptr() const { return _ptr; } }; struct container narcissus(int a, int b) { printf("Narcissus: %i %i.\n"...
5,923,702
5,923,830
Casting an object to a reference?
I've been reading some OSS code lately and stumbled upon this peculiar piece: class Foo { ..... }; void bar() { Foo x; Foo *y=new Foo(); x=(const Foo &) *y; } For the life of me I can't find documentation about the behavior of casting an object to a const reference.
x=(const Foo &) *y; is assignment. The only reason I see to explicitly cast to const reference is to have Foo::operator=(const Foo &) called for assignment if Foo::operator=(Foo &) also exists.
5,923,934
5,923,984
Primitive to user defined assignment on construction
Sorry for the blurry title, I seem to be missing something. I was hesitant to post this, because it seems so basic, but I can't get it to work. My IDE tells me the following is incorrect. I have a class called IRatio which I want to be interchangeable with long double. class IRatio { protected: long double ...
Your code should work as is. That said, IRatio doesn't manage any resources on its own, so you don't need the copy constructor and assignment operator. This should do: struct IRatio { IRatio() : d(0L) { } IRatio(long double d) : d(d) { } operator long double() const { return d; } private: long double d;...
5,923,973
5,924,010
Accessing class of class
Class A{ public: MyVec<A> test; //problem error: ‘MyVec’ does not name a type }; Class B{ public: template<typename Obj> Class MyVec{ //some methods... }; private: MyVec<A> test1; //ok }; Compiler complains about the line where test is defined.
You didn't define or even declare MyVec before the definition of A. This makes it impossible for the type to be used in A. This is because of the order of declarations.
5,923,990
5,924,196
Ideal bitmap size for optimal GPU performance?
I know that when dealing with the graphics card, one needs to provide bitmaps with a power of 2. 1,2,4,8,16,32... I am planning on making a tile based project, only I needed to know if there were any limitations in providing a gigantic bitmap to the graphics card. What are the pros/cons of using small/large bitmaps? Is...
In general, when dealing with modern GPUs, larger datasize is better. You don't say what API you're using (OpenGL, CUDA, etc.), but you can think of it like this: chunk_time = overhead_time + (num_of_elements/num_of_chunks) * per_element_time total_time = chunk_time * num_of_chunks You'll get the overhead for both me...
5,924,079
5,924,158
C++ lambda expression does not compile
I am trying to cin a loop index's value in the loop itself using lambda expression: #include<iostream> using namespace std; int main(){ for(int a, ([](int & b){cin>>b;})(a); a < 2; ++a); return 0; } These are the errors when i compile using g++ 4.5 on ubuntu: forLoopAndCinTest.c++: In function ‘int main()’: forLo...
That's not how the for look works. You are trying to call a lambda where the compiler expects you to declare an int: for( int a, int2, ...; a < 2; ++a ); Now, If i use a normal function instead of the lambda, program compiles fine Yes, but it's probably not doing what you think it does. void f(int& b) { cin >>...
5,924,248
5,924,278
Why is it allowed to cast a pointer to a reference?
Originally being the topic of this question, it emerged that the OP just overlooked the dereference. Meanwhile, this answer got me and some others thinking - why is it allowed to cast a pointer to a reference with a C-style cast or reinterpret_cast? int main() { char c = 'A'; char* pc = &c; char& c1 = (c...
Well, that's the purpose of reinterpret_cast! As the name suggests, the purpose of that cast is to reinterpret a memory region as a value of another type. For this reason, using reinterpret_cast you can always cast an lvalue of one type to a reference of another type. This is described in 5.2.10/10 of the language spe...
5,924,261
5,924,279
c++ reading from cin
If I have: double x; cin >> x; then I proceed to enter a character or a string, what would happen? And what would the statement cin >> x return?
The istream::operator>> always returns an istream object, no matter what. The value of x however would be undefined, and the istream would be "errored" and wouldn't work again till you cleared the error state. This is just from memory and I really haven't thought about this before, so if someone sees that this is wrong...
5,924,297
5,924,319
No matching function for call to
I got this method where I'm getting lines of userdata from a file, then splitting the lines into parts and then putting those parts into different strings. Then at last, I'm creating a new user object and adding the user object into another vector called users. void userdata::importData(string fname) { g_string g; ...
std::vector::at() takes a size_type argument, which is unsigned. Perhaps this works: string usernr = parts.at(0u); string name = parts.at(1u); string gender = parts.at(2u); string age = parts.at(3u); string profession = parts.at(4u); string email = parts.at(5u);
5,924,375
5,924,397
Creating Boiler Plate Code using Macros
I have a bunch of classes such as the following, class SomeClass : public Function{ public: ref call(ref args){ // do & return stuff } int getType(){return TYPE;} ref toString(){ return "SomeClass";} }; I got like 50 of these and the only thing that is different is the body of the call function. I...
Sure. Expanding the body of the call member function is a bit easier if you have a compiler that supports variadic macros. While I've used Boost.Preprocessor's stringize macro, it is trivial to write your own. #define DEFINE_CLASS(name, parenthesized_call_body) \ class name : public Function { ...
5,924,492
5,924,535
Converting projectPoints from C to C++
I'm trying to convert simple code for cvProjectPoints2 to C++, so I'm using cv::ProjectPoints. I'm using the cv namespace to avoid prefixing everything with cv:: Mat_<double>* object_points = new Mat_<double>(10, 3, CV_64FC1); Mat_<double>* rotation_vector = new Mat_<double>(3,3, CV_64FC1); Mat_<double>*...
The documentation I've found gives the following declarations for projectPoints: void projectPoints(const Mat& objectPoints, const Mat& rvec, const Mat& tvec, const Mat& cameraMatrix, const Mat& distCoeffs, vector<Point2f>& imagePoints); void projectPoints(const Mat& objectPoints, const Mat& rvec, const Mat& tvec, cons...
5,924,599
5,924,687
Sockets in Linux - how do I know the client has finished?
I am currently trying to implement my own webserver in C++ - not for productive use, but for learning. I basically open a socket, listen, wait for a connection and open a new socket from which I read the data sent by the client. So far so good. But how do I know the client has finished sending data and not simply tempo...
The protocol (HTTP) tells you when the client has stopped sending data. You can't get the info from the socket as the client will leave it open waiting for a response. As you say, you must guard against errant clients not sending proper requests. Typically in the case of an incomplete request a timeout is applied to ...
5,924,611
5,924,659
What is the best way (performance-wise) to test whether a value falls within a threshold?
That is, what is the fastest way to do the test if( a >= ( b - c > 0 ? b - c : 0 ) && a <= ( b + c < 255 ? b + c : 255 ) ) ... if a, b, and c are all unsigned char aka BYTE. I am trying to optimize an image scanning process to find a sub-image, and a comparison such as this is done about 3 million times per s...
Well, first of all let's see what you are trying to check without all kinds of over/underflow checks: a >= b - c a <= b + c subtract b from both: a - b >= -c a - b <= c Now that is equal to abs(a - b) <= c And in code: (a>b ? a-b : b-a) <= c Now, this code is a tad faster and doesn't contain (or need) complicated un...
5,924,630
5,924,699
Local-variable declaration inside a "virtual" loop optimization
This time, I couldn't find what I'm looking for (dunno if I'm not searching for the right stuff...) but, here it is: In c++, imagine you have a function Bar() that is called once every cycle... like this: class Foo { public: void Bar() { double my_array[3]; // fills the array based on some calculations ...
Use a profiler As it stands, the function is declared inline in a class. This code will trivially optimize, and the compiler will probably get the allocations out of the loop anyway (depending on how much cruft you have left out of the picture, really). Also, the overloaded array operators likely get vectorized in gcc ...
5,924,670
5,924,691
Arithmetic operator return type
int main(int argc, char **argv) { unsigned char a = 10, b = 100; std::cout<<sizeof(a-b)<<endl; return 1; } Output: 4 What is the return data type?
Arithmetic is always performed at least with int precision in C++. a and b are both promoted to int and the result of the subtraction is of type int. There are a set of rules used to determine the type used for an arithmetic operation; MSDN has a handy table listing the rules.