question_id
int64
25
74.7M
answer_id
int64
332
74.7M
title
stringlengths
20
150
question
stringlengths
23
4.1k
answer
stringlengths
20
4.1k
7,855,713
7,855,796
Image smoothing using opencv data structures
I would like to implement Gaussian blur on the AVI Files i read, i know about the in-built functions of opencv however i would need help from SO users to assist me so that i can get started by implementing it myself. I know how to access the Image Pixels of an IplImage * , CvARR * , etc.... However i am just not sure h...
6 month back I was also new to the opencv. The way I learn it is: http://opencv.itseez.com/doc/tutorials/tutorials.html http://www.packtpub.com/opencv-2-computer-vision-application-programming-cookbook/book
7,855,908
7,855,929
C++: initializing template constructor/routine declared in header file?
I have a template defined in my header file as follows: template<typename T> class BoundedBuffer { unsigned int size; T entries[]; public: BoundedBuffer( const unsigned int size = 10 ); void insert( T elem ); T remove(); }; However, when I try to initialize the constructor: BoundedBuffer<T>::Bou...
The right syntax is: template <typename T> BoundedBuffer<T>::BoundedBuffer(const unsigned int size) : size(size) { // create array of entries entries = new T[size]; // initialize all entries to null for(int i = 0; i < size; i++) entries[i] = null; } Note that optional parameters should not be ...
7,855,941
7,860,169
Necessity of writing print functions for containers?
I use about 6 different C++ containers. I started writing print functions to output the container contents. Is this necessary? I would think this is part of the C++ library? void print_list(const list<int>& list_int) { for (list<int>::const_iterator it = list_int.begin(); it != list_int.end(); it++) cout <...
The code you give in your question has a hint as to why it is not part of the standard library. Your code uses square brackets and a comma with no spaces to show the pairs in the map. Other people may want it formatted differently so the options the standards committee had were: Provide a lot of formatting options. ...
7,856,047
7,856,079
Can copy() cannot be use for initializing a container?
Can copy() be used for initializing a container? The following code has a runtime error: "list iterator not dereferencable". What would be the reason for this? Thanks string a[] = {"00", "11", "22"}; list<string> list_1(a, a+3), list_2; copy(list_1.begin(), list_1.end(), list_2.begin()); // error:
list_2 has no space where to copy the source range. You have to either reserve enough space, or use an inserter iterator. Alternatively, you could just use the list constructor: std::list< std::string > list_2( list_1.begin(), list_1.end() ); or further on the assign member function: list_2.assign( list_1.begin(), lis...
7,856,248
7,856,293
C/C++ Forward declaration vs. Include
What is happening when you include some file and what is happening when you forward declare some function/class? If two files include the same file will the first one success to read all the function the second will fail but still be able to use the functions?? What happens when I forward declare some function? Is this...
What is happening when you include some file and what is happening when you forward declare some function/class? When you include a file, its contents get "copy and pasted" into the inclusion source by the preprocessor. When you forward declare a function/class you are declaring an incomplete type, letting the rest o...
7,856,267
7,856,351
How to compile opencv with visual studio without CMake
I want to compile opencv with visual studio, so the code of opencv will be on my computer like all other local code. i.e. i want to be able to change it and debug it. I can't find anywhere a simple directory file with all the opencv files. It is segmented into include files, modules and similar. All explanations in t...
cmake is an platform independent makefile. You can generate from cmake also visual studio projects, which can than imported into visual studio. But you need to install cmake on your computer. To make a visual studio project call cmake like this: cmake -G "Visual Studio 9 2008" Cmake Wiki
7,856,309
7,856,532
VisualC 2010, project references, and include paths
I am trying to use the VC2010 project references, which are the replacement for the old Project Dependencies dialog. What I am missing, however, is a way to let the referring project inherit the referred one's include and library paths. Right now, I have to manually copy any extra paths I set in the referred project. A...
You can use property sheets to abstract away the common compiler and linker settings. Both of your projects then would import the same property sheet. See http://msdn.microsoft.com/en-us/library/ee662426.aspx
7,856,364
7,856,411
C++ passing pointer to vector element instead of array pointer
I think the following code snippet is perfectly legal (it builds anyway on MS Visual Studio 2008, C++). I use it to link to a 3rd party library. But I think because I am passing a pointer to a vector element instead of a regular pointer that the 3rd party library function expects, I get a run-time error Invalid parame...
std::vector<T> expands if you are adding elements using std::vector<T>::push_back(T &), std::vector<T>::insert(iterator, T &) (thanks K-ballo) or explicitly calling std::vector<T>::resize(size_t). Otherwise, it doesn't expand. std::vector<int> vec_ints; vec_ints.reserve(27); std::vector<double> vec_doub; vec_doub.reser...
7,856,453
7,856,473
Accessing map value by index
If I have a structure like std::map<string, int> myMap; myMap["banana"] = 1; myMap["apple"] = 1; myMap["orange"] = 1; How can I access myMap[0]? I know that the map sorts internally and I'm fine with this, I want to get a value in the map by index. I've tried myMap[0] but I get the error: Error 1 error C2679: bina...
Your map is not supposed to be accessed that way, it's indexed by keys not by positions. A map iterator is bidirectional, just like a list, so the function you are using is no more inefficient than accessing a list by position. If you want random access by position then use a vector or a deque. Your function could be w...
7,856,514
7,856,534
How to sort a vector <char*>?
#include <algorithm> bool comparisonFunc(char* c1, char* c2) { return strcmp(c1, c2) ? 0 : 1; } vector<char*> myVec; vector<char*>::iterator itr; sort(myVec.begin(), myVec.end(), comparisonFunc) Is that correct or is there a better way to do it?
std::sortexpects a "less than" predicate. You should implement your comparisonFunc() like this: bool comparisonFunc(const char *c1, const char *c2) { return strcmp(c1, c2) < 0; } (Note the consts; they are important.) Your current implementation couldn't possibly work because you just return if the values are equa...
7,856,665
8,478,845
How to compile multiple files in ROOT
I wrote a C++ program (with a main.cpp, and various header and implementation files) that compiles fine under g++. Now I am trying to compile it in Cern's ROOT library, but I do not know how to, since the only way I know how to compile files in ROOT is by using .L main.cpp. How can I include multiple files in ROOT?
The most reliable way to use ROOT (at least historically and currently) is to ignore the interpreter other than for the simplest explorations and explicitly compile your C++ programs against the ROOT libraries. For example, use g++ MySource.cc `root-config --libs --cflags` -o foo to compile an executable "foo" from a ...
7,856,669
7,856,677
Overloading global function getline in a c++ class
I'm working on a school project to implement a c++ class for polynomials. Something my class is supposed to do is read polynomials from standard in, or from a file. I thought about overloading >> until I read the following on my favorite c++ reference site: Notice that the istream extraction operations use whitespaces...
You should still overload operator >>. Within your operator implementation, you can extract as many 'words' as you need (I'm assuming one per coefficient or so). Don't try to overload getline, thats about getting a line not a Polynomial.
7,857,230
7,857,267
C++ Pointers in Typedefs
I'm relatively new to C++, I start by reading C++ Primer 4th edition. It has a section explains about Pointers and Typedefs, start with bellowing code. typedef string *pstring; const pstring cstr; I know that after I define typedef string *pstring; I can use *pstring to declare string variable in my code. *pstring val...
They are not identical. pstring v1; // declares a pointer to string string v2; // declares an object of type string string* v3; // this is the same type as v1
7,857,462
7,864,631
Dealing with fragmentation in a memory pool?
Suppose I have a memory pool object with a constructor that takes a pointer to a large chunk of memory ptr and size N. If I do many random allocations and deallocations of various sizes I can get the memory in such a state that I cannot allocate an M byte object contiguously in memory even though there may be a lot fr...
I wanted to add my 2 cents only because no one else pointed out that from your description it sounds like you are implementing a standard heap allocator (i.e what all of us already use every time when we call malloc() or operator new). A heap is exactly such an object, that goes to virtual memory manager and asks for l...
7,857,518
7,857,845
(C++) Passing a pointer into a template
I have two pointers. p1. p2. p1 and p2 both point to different classes. The classes have some similar method names, and I'd like to call a template function twice to avoid repeated code. Here is my function: template <class T> void Function(vector<T> & list, T* item, const string & itemName) see that middle paramater...
You should be able to call your code like this: template <class T> void Function(std::vector<T> & list, T* item, const std::string & itemName) { list.push_back(T()); if (item != NULL) item->x = 4; } struct A { int x; }; struct B { double x; }; A a; B b; std::vector<A> d; std::vector<B> i; Functio...
7,857,724
11,011,405
OpenSceneGraph Texture2D image "dirty" vs "setImage" performance
I have a 2D texture placed over rectangular area - it's a dynamic texture image (640x480). tex = new osg::Texture2D; tex->setDataVariance( osg::Object::DYNAMIC ); tex->setResizeNonPowerOfTwoHint( false ); tex->setFilter( osg::Texture2D::MIN_FILTER, osg::Texture2D::NEAREST ); tex->setFilter( osg::Texture2D::MAG_FILTER, ...
I'm assuming you are using not the latest (3.0.1) version of OSG, since it lacks the "dirty" method for Image class. In previous versions (2.x): inline void Image::dirty() { ++_modifiedCount; if (_bufferObject.valid()) _bufferObject->dirty(); } dirty() in turns resets all compiled lists for _bufferObje...
7,857,768
7,857,783
Destructor invocation in C++
I have studied that Destructor is invoked whenever the object goes out of scope or when the memory allocated to it is de-allocated using the delete operator. #include <iostream> using namespace std; class point { private: int x_coord; int y_coord; public: point() { x_coord = 0...
There is mistake in the code. You can not delete p1 (p4 points to p1) as it was not created with new. Thus, the program is invoking undefined behavior. What happens in this particular case is that p1's destructor gets invoked twice: first with delete, second time when p1 goes out of scope. It could be anything else as...
7,857,861
7,877,731
How to inline in C++ self modifying assembly code?
How would I inline this in C++ function. 0041F84E . 7B 02 JPO SHORT Unmodifi.0041F852 0041F850 B8 DB B8 0041F851 00 DB 00 0041F852 . 8B46 38 MOV EAX,DWORD PTR DS:[ESI+38] 0041F855 . 8B56 24 MOV EDX,DWORD PTR DS:[ESI+24] 0041F858 . 8B4E 10 MOV ECX,DWO...
This is an answer-length comment to reply to SSpoke's request for an example. A long time ago, when emulating Turing machines was a cool thing to do, I wrote a Turing machine emulator program to search for busy beavers on a DEC Vax minicomputer. When the program decided which Turing machine to try next, it compiled the...
7,857,985
7,858,222
Why is this constructor with variadic template arguments not a match?
I have a processing pipeline implemented, but I would like to improve it like this : #include <iostream> // buffers struct src{}; struct b1{}; struct snk{}; // filters struct f1 { f1( const src &, b1 & ) { std::cout << "f1( src, b1 )" << std::endl; } }; struct f2 { f2( const b1 &, snk & ) { std::cout << "f2(...
template< typename... Buffs, typename Bin, typename Bout > pipeline( Buffs &... buffs, Bin & bin, Bout & bout ) : pipeline< T... >( buffs..., bin ), filter( bin, bout ) { } Since the function parameter pack (Buffs) is not in the last position, it cannot be deduced. From 14.8.2.1 Deducing template arguments fro...
7,857,989
7,857,996
static member variable when declared private
When a static member variable is declared private in a class, how can it be defined? Suppose i have the following class declaration class static_demo { private: static int a; public: static int b; void set(int x, int y) { a = x; b = y; } void show() ...
When a static member variable is declared private in a class, how can it be defined? In the very same way as you define a public static variable in your source(cpp) file. int static_demo::a = 1; Access specifiers will not give you error while defining the member. Access specifiers control the access of the me...
7,858,059
7,858,154
what does skip procedure do?
i am trying to determine what does this code? #include <cstdlib> #include <iostream> #include<string.h> using namespace std; char *skip(char *p,int n) { for (;n>0;p++) if (*p==0) n--; return p; } int main(int argc, char *argv[]) { char *p="dedamiwa"; int n=4; cout<<skip(p,n)<<end...
It skips n characters of the char array. It interpret the first parameter as a pointer to an array of character containing at least n null characters, and return a pointer after the n-th such null-character. Per se, there is no undefined behavior if you pass correct input to it. Since you pass a simple null term...
7,858,088
7,862,835
print rtp header information using libpcap in cpp
I am parsing the pcap file using libpcap. I want to print rtp&rtcp payload type(96 for H264/0 for PCMU) (and timestamp also) so that I can distinguish whether it is audio/video. I can able to print those rtp/rtcp packet sequence numbers correctly but not palyload type. typedef struct { unsigned int version:2; /*...
The ntohs() function converts the unsigned short integer from network byte order to host byte order. Note that it's byte order, so, for one-byte payload you don't need this conversion. For timestamp you should use ntohl() instead, since you are working with 32-bit value. Update I think this will be more natural than us...
7,858,145
7,858,241
undefined reference (templates)
I have a namespace that gets built out of a .cpp and .h lots of classes use this namespace and call the template functions from within it How do I fix all the undefined references during the linking process? Where would I put all the definitions of the template functions? could someone show me an example of a namespac...
Most likely you're incorrectly placing template definitions in the .cpp file. For more information about that, see the FAQ item "Why can't I separate the definition of my templates class from its declaration and put it inside a .cpp file?". The immediately following FAQ items may also be of help to you, but it's not en...
7,858,228
7,858,248
C++: would universal use of shared_ptr<> be equivalent to a gc?
This is just an academic question (I would never do this in real code): If I were to use shared_ptr<> universally in my code, would the behavior be equivalent to a gc-collected language like Java? If not, how would the behavior be different from a gc-embedded language? Which C++ construct would yield equivalent behavi...
No, there'd be a couple of important differences: You would get a memory leak any time you have a cyclic reference. A garbage collector can handle cycles, ref-counting can't. You would avoid any stalls or pauses because no garbage collection ever occurs. On the other hand, you'd likely spend more total CPU time cleani...
7,858,271
7,858,293
pimpl for a templated class
I want to use the pimpl idiom to avoid having users of my library need our external dependencies (like boost, etc) however when my class is templated that seems to be impossible because the methods must be in the header. Is there something I can do instead?
If the class is templated, your users essentially need to compile it (and this is literally true in the most widely-used C++ implementations) and so they need your external dependencies. The simplest solution is to put the bulk of your class's implementation in a non-template base class (or encapsulated member object o...
7,858,319
7,858,361
c++ reading undefined number of lines with eof()
I'm dealing with a problem using eof(). using string name; int number, n=0; while(!in.eof()) { in >> name >> number; //part of code that puts into object array n++; } sounds normal to me as it whenever there are no more text in the file. But what I get is n being 4200317. When I view the array entries, I s...
The correct way: string name; int number; int n = 0; while(in >> name >> number) { // The loop will only be entered if the name and number are correctly // read from the input stream. If either fail then the state of the // stream is set to bad and then the while loop will not be entered. //...
7,858,466
7,859,971
Unable to pass reference from one class to another
I'm writing a C++ program intended to manage the resources and duties in a flat. This program is intended to run in Linux Shell. I created a class call HomePage for users to login. I've also got another class called SelectionPage. Which are the Menus after the user got past the login. In my main functions, i wish to pa...
Look at your error messages carefully. C_HomePage.cpp:290:41: error: no ‘std::vector<std::basic_string<char> > HomePage::getDutiesList()’ member function declared in class ‘HomePage’ C_HomePage.cpp:294:44: error: no ‘std::vector<std::basic_string<char> > HomePage::getResourcesList()’ member function declared in class ‘...
7,858,519
7,858,527
Initializing and Destructing a 2D Vector in C++
Please I have two questions in respect to vectors in C++: How to fix the problem in the following code: In my header file I have: vector< vector< char > > vec; In my (.cpp) file in the definition of the constructor I have: vec(20, vector<char>(25, " ")); The error I'm receiving is the following: error: invalid conv...
You probably wanted single quotes ' ': vec(20, vector(25, ' ')); Otherwise, you're be passing a string " " which is causing that error. As for your second question. You don't need to destroy it. It will automatically free itself when it falls out of scope. EDIT: You also need to do it together: vector< vector< char > ...
7,858,598
7,858,622
Why does the compiler tell me vector<string> is not declared?
I have some code here which reads from a file, and stores them in a vector. I wish to pass this vector to another class. However, when i try to do that, it gives me a strange error, which i do not fully understand. It seems to be saying that the vector is not declared. Here is the first few lines of a very long error: ...
You're missing parentheses in the declarations of getDutiesList and getResourcesList: vector<string> getDutiesList(); vector<string> getResourcesList(); EDIT: You're also missing the parentheses in your .cpp file: vector<string> HomePage::getResourcesList(){ return resourcesList; }
7,858,652
7,858,676
see if there is a key in a map c++
in my function, i have this parameter: map<string,int> *&itemList I want to first check if a key exists. If this key exists obtain the value. I thought this: map<string,int>::const_iterator it = itemList->find(buf.c_str()); if(it!=itemList->end()) //how can I get the value corresponding to the key? is the correct...
Yes, this is correct way to do this. The value associated with the key is stored in second member of std::map iterator. map<string,int>::const_iterator it = itemList->find(buf.c_str()); if(it!=itemList->end()) { return it->second; // do something with value corresponding to the key }
7,858,709
7,858,949
PHP string to "unsigned long" (from C++)
I have this code in C++, which returns outputs the following number int main(int argn, char** argv) { cout << (*((unsigned long*)"P3TF")) << endl; cin.get(); return 0; } How can I achieve the above in PHP (i.e. the string "P3TF" in unsigned long int). I tried using the pack method: <?php $lol = pack('N', ...
If it's literally "P3TF" in the real code, why not convert it once, and define a constant in the PHP code? Failing that, you need unpack, not pack. e.g. running <?php $in = 'P3TF'; $arr = unpack('N', $in); printf("%08x\n", $arr[1]); ?> Gives 50335446, which is the ASCII codes for 'P' '3' 'T' 'F' in hex (concatenated)
7,858,775
7,858,800
How come the compiler asks for initializer before class constructor?
I am creating a class called SelectionPage. Which essentially is a set of menues. However, when i compile the code, the compiler gives me the following error: g++ C_Main.cpp C_HomePage.cpp C_SelectionPage.cpp C_MemberManagement.cpp -o Project C_SelectionPage.cpp:9:104: error: expected initializer before ‘SelectionPage’...
If you have this line really in your code, you probably copied the constructor twice: SelectionPage::SelectionPage(int newPoints, string newManager, string newLoginName, string MemberFile )SelectionPage( int newPoints, string newManager, string newLoginName, string MemberFile){ Should be this: SelectionPage::Selection...
7,858,817
36,656,413
"unpacking" a tuple to call a matching function pointer
I'm trying to store in a std::tuple a varying number of values, which will later be used as arguments for a call to a function pointer which matches the stored types. I've created a simplified example showing the problem I'm struggling to solve: #include <iostream> #include <tuple> void f(int a, double b, void* c) { ...
The C++17 solution is simply to use std::apply: auto f = [](int a, double b, std::string c) { std::cout<<a<<" "<<b<<" "<<c<< std::endl; }; auto params = std::make_tuple(1,2.0,"Hello"); std::apply(f, params); Just felt that should be stated once in an answer in this thread (after it already appeared in one of the comme...
7,858,820
7,858,851
Promote or not promote - that is the questiion
This code compiles fine with Visual C++ 11 Developer Preview but won't compile with gcc 4.6.1. How to make it "compilable" for the latter? #ifndef PROMOTE_H_INCLUDED #define PROMOTE_H_INCLUDED #include <boost\mpl\vector.hpp> #include <boost\mpl\find.hpp> #include <boost\mpl\next.hpp> #include <boost\mpl\deref.hpp> ...
Change your include directives: #include <boost/mpl/vector.hpp> This will work both on Windows and Unix-type systems. No other syntax problems detected (but since this is just a template, I have no idea if there are problems when you actually use it). Edit: with what you add in the main, it compiles with GCC 4.6.1. Do...
7,858,866
7,860,307
why not run task after pop and return true?
i run the following example from book c++ concurrency in action, and pass function a, b and c with its submit, it print pop and sure return true, but why not print "start task" it seems not run the task() #include <thread> #include <atomic> #include <vector> #include <queue> class join_threads { std::vector<std::...
After fixing all compilation errors, this compiles with GCC 4.6.1 on linux and runs, producing the following output: begin push 0push 1push 2push 3push 4push 5submit start submit finish poptask start a task end poptask start b task end poptask start c task end after which point it remains in endless loop because done ...
7,858,988
7,859,104
How do I translate the following threading model from C++ to go?
In my C++ project, I have a large, GB binary file on disk that I read into memory for read-only calculations. My current C++ implementation involves reading the entire chunk into memory once and then spawning threads to read from the chunk in order to do various calculations (mutex-free and runs quickly). Technically,...
I'm sure this answer will cop a lot of heat but here goes: You won't get reduced running time by switching to Go, especially if your code is already mutex free. Go doesn't guarantee efficient balancing of goroutines, and will not currently make best use of the available cores. The generated code is slower than C++. Go'...
7,859,354
7,860,353
installTranslator method of QApplication don't change language
I redefined QApplication class and add switchLanguage slot and i want to switch language when i press but1. main_ru.qm and main_de.qm is normal, 100% working. But language don't change when i press button // main.cpp #include <QtGui> #include "qmyapp.h" int main( int argc, char** argv ) { QMyApp app( argc, argv )...
You need to call translate again after installing new translations. So after you call switchLangauge() you need to call QObject::tr() once again in whatever context it was used before.
7,859,442
7,861,033
Grab Video Stream from FireWire
I'm trying to stream a video from a camera ( Sony HVR-Z1E ) over FireWire to my Computer. The incoming pictures/stream shall be processed further by some functions which expect the CVMat format ( from openCV ). Well my problem is now that I have no idea how to grab the stream. Okay openCV 2.1 offers me some methods ( c...
See my related answer here. OpenCV cannot capture video from Firewire cameras natively. You will either need to use the CMU1394 driver, or the Sony driver (if an SDK is available for it) to capture video from that camera, and then pass it to OpenCV.
7,859,568
7,859,740
Embed assembler to manipulate 64-bit registers in portable C++
I have a simple (but performance critical) algorithm in C (embedded in C++) to manipulate a data buffer... the algorithm 'naturally' uses 64-bit big-endian register values - and I'd like to optimise this using assembler to gain direct access to the carry flag and BSWAP and, hence, avoid having to manipulate the 64-bit ...
Just to give you a taste of the obstacles that lie in your path, here is a simple inline assembler function, in two dialects. First, the Borland C++ Builder version (I think this compiles under MSVC++ too): int BNASM_AddScalar (DWORD* result, DWORD x) { int carry = 0 ; __asm { mov ebx,result xor ...
7,859,615
7,859,635
Copy constructor not invoked (again)
I don't like questions with debug sessions and memory pointers pasted, but I am forced to ask one like that. This is a question about invoking copy constructors. I know there are already answers about that, but I didn't find anything that would solve my problem I have a Matrix class: class Matrix { ... Matrix...
No, in your case the assignment operator will be called. Just define Matrix& operator=(const Matrix& other); ... Matrix& Matrix::operator=(const Matrix& other) // overloaded assignment { if (this != &other) // self-assignment is usually a problem, avoid it { ... // Stage 1: Do all dangerous st...
7,859,638
8,442,082
Stumped with Unicode, Boost, C++, codecvts
In C++, I want to use Unicode to do things. So after falling down the rabbit hole of Unicode, I've managed to end up in a train wreck of confusion, headaches and locales. But in Boost I've had the unfortunate problem of trying to use Unicode file paths and trying to use the Boost program options library with Unicode in...
Okay, after a long few months I've figured it out, and I'd like to help people in the future. First of all, the codecvt thing was the wrong way of doing it. Boost.Locale provides a simple way of converting between character sets in its boost::locale::conv namespace. Here's one example (there's others not based on local...
7,859,669
7,859,877
C++ Bitmap Bit per pixel
I'm trying to understand building a bmp based on raw data in c++ and I have a few questions. My bmp can be black and white so I figured that the in the bit per pixel field I should go with 1. However in a lot of guides I see the padding field adds the number of bits to keep 32 bit alignment, meaning my bmp will be the ...
Monochrome bitmaps are aligned too, but they will not take as much space as 24/32-bpp ones. A row of 5-pixel wide 24-bit bitmap will take 16 bytes: 5*3=15 for pixels, and 1 byte of padding. A row of 5-pixel wide 32-bit bitmap will take 20 bytes: 5*4=20 for pixels, no need for padding. A row of 5-pixel wide monochrome...
7,859,900
7,859,911
C++ class member allocation
Assume I have this: class foo{ Member member; foo(); ~foo(); }; How I should allocate the member? EDIT: How should I tell him which constructor to use?(sorry for being unclear) Now I already know about the member = Member(...); syntax Will this cause memory leak? { Memory *temp = new Member(); memb...
C++ is not Java. This member is already allocated. It is part of the memory of the instance it is in. It will get constructed (initialized) by the constructor of the containing instance. The key word new has nothing to do with a member that is not a pointer.
7,860,024
7,860,174
What does the gcc -R parameter do?
I am trying to run an autotools configure script for the bson-cpp project, and it fails because it cannot determine what flags it needs to compile with boost_filesystem. A quick look at confg.log shows: g++ -o conftest -g -O2 -pthread -L/usr/local/lib -R/usr/local/lib -L/usr/local/libexec conftest.o -lboost_filesyst...
-R does not seem to be an option for g++ or gcc anywhere. -R may be a linker option on some platforms that is equivalent of -rpath to gnu ld, ... This seems to be a known bug in boost builds ... have a look at Use -Wl to pass arguments to the linker. It actually has the patch available there I am re-posting it for con...
7,860,034
7,860,077
How can I change the position of the mouse cursor in OpenGL/SFML?
I'm writing a simple FPS game and I'm going to have the mouse control the camera. I'm using SFML library for C++. How can i set mouse position to the center of the window. Can you help me to find multiplatform version of the setCursorPos (Windows only) // Sorry for my bad english
You can use: sf::Window::SetCursorPosition for SFML 1.6 sf::Mouse::SetPosition for SFML 2.0
7,860,152
7,860,182
Cannot cycle through all pixels of rectangular image matrix
I am attempting to increase brightness of the loaded image img, however to cycle through the pixels i am using a smaller matrix [which i will use to apply Gaussian blur later]. Here is my function: void Dobright(cv::Mat &in,IplImage * img) { uchar* temp_ptr ; for( int row = 0; row < in.rows; row++) { ...
from the looks of it you have width and height mixed up, try using: CvPoint pt = {col,row}; also with your current algorithm you will run into problems when your pixels original values are > 155, (156 + 100 = 1) because of rounding. Try using tmp_ptr[0] = (tmp_ptr > 155) ? 255 : tmp_ptr[0] + 100;
7,860,227
7,861,827
Local static initialization without holding a lock avoids a possible deadlock in C++11?
In paper http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2660.htm an algorithm is presented that does not need to hold a lock during the initialization of a local static variable but still causes concurrent flow of control through the variable definition to wait until initialization finished. The paper says t...
If you're going to hold a lock during a local static initialization there are two possible designs: Allocate a mutex per static. Allocate just one mutex for all statics. I'm not 100% positive, but I believe the quote to which you refer implicitly assumes design 2. And indeed the algorithm introduced in the paper use...
7,860,386
7,860,545
C++ partial template specialization of stream operator
I have a Matrix class with a friend function to use with operator<<. This all works fine but I now want to partially specialize that friend function to work differently if the Matrix class has Matrix as its template parameter (i.e. when the instance of the class has been declared like Matrix< Matrix< char > >). In the ...
There's no such thing as a partial specialization of a function template. You need overloading, not specialization. This should compile, link, and run cleanly (it does for me): #include <iostream> template <typename T> class Matrix { public: template <typename U> friend std::ostream& operator<<(std::ost...
7,860,432
7,860,454
Can't understand compiler's behaviour (creating object)
I wrote the following code: #include <iostream> class A { public: A(){ std::cout << "created" << std::endl; } A(A& other) { std::cout << "copied" << std::endl; } A& get(){ std::cout <<"got" << std::endl; return *this; } ~A(){ std::cout << "destroyed" << std::endl; } }; Now, lines A a = A().get(); and...
A a = A(); This line tries to call the copy-constructor passing a temporary object, and the copy-constructor takes argument by non-const reference. But a temporary object cannot be bound to a non-const reference. That is why you get the compilation error. However, a temporary object can be bound to const reference. S...
7,860,439
7,860,452
Invalid types 'double [100][double]' for array subscript
#define MAX 100 double velocity[MAX]; for (itr = 0; itr < velocity[0]; itr = itr + 1) { velocity[itr] = velocity[0] - (1*itr); distance[itr] = rk4_solve(itr, velocity); cout << setw(5) << itr << setw(9) << velocity[itr] << setprecision(4) << setw(10) << distance[itr] << endl; } I am tr...
itr must be an int (or other integer type) Be aware that you are comparing itr with velocity[0] in the for cycle (itr < velocity[0];). You probably meant itr < MAX, and I hope somewhere you defined the variable itr
7,860,501
7,860,526
C++ constructor calling order
When I initialize an object of my class, both the default and copy constructor are called. class A { public: A (string s) { str = string (s); cout << "default" << endl; } A (int n) { cout << "A (int n)" << endl; } A (string s, int n) { cout << "A (string s, int n)" << endl; } A (int n2, string s2) { cout <<...
A a_1 = A ("con 1"); Constructs a temporary object by calling the constructor which takes a string as an argument,since the passed type is const char * the compiler has to perform an implicit conversion first to string() and then uses this temporary object to copy construct a new a_1 object. Since there is an additio...
7,860,569
7,860,710
How can I get and use the header file <graphics.h> in my C++ program?
I have been searching to get the source code of the header file <graphics.h> and its associated library in order to integrate it with my C++ program. At the same time, I am interested in those cross-platform libraries that works on more than one compiler. Just to be more explicit, I am talking about those libraries tha...
<graphics.h> is very old library. It's better to use something that is new Here are some 2D libraries (platform independent) for C/C++ SDL GTK+ Qt Also there is a free very powerful 3D open source graphics library for C++ OGRE
7,860,575
7,861,318
Optimized float Blur variations
I am looking for optimized functions in c++ for calculating areal averages of floats. the function is passed a source float array, a destination float array (same size as source array), array width and height, "blurring" area width and height. The function should "wrap-around" edges for the blurring/averages calculatio...
What you are trying to implement are various sorts of digital filters for image processing. This is equivalent to convolving two signals where the 2nd one would be the filter's impulse response. So far, you regognized that a "rectangular average" is separable. By separable I mean, you can split the filter into two part...
7,860,599
7,860,620
Why does assertion fail here
Why does the assertion fail here when i create a CvMat *? It does not happen with an image i load in cv::Mat using a pointer. struct RGB { unsigned char b, g, r; }; cv::Point p; RGB *data; CvMat* mat = cvCreateMat(300,300,CV_32FC1); for( row = 0; row < mat->rows; ++row) { for ( col ...
Because sizeof(RGB) != sizeof(float), which is what you filled the matrix with here: CvMat* mat = cvCreateMat(300,300,CV_32FC1); CV_32FC1 means 1 component, 32-bit floating point. You probably want CV_8UC3. See here or another OpenCV reference.
7,860,657
7,860,702
Undefined reference to Eclipse C++
I've tried more and more time, but I got the same error. When I use an external lib, for example I'm try to work on openssl and crypto++, I receive the error: "undefined reference to (function)". I dunno why Eclipse do that neverthless the #include are all correct. I've tried even to add the path from Properties-C/C++ ...
You must specify the name of the shared libraries which must be linked to the executable. Assuming you are using the GNU toolchain, you can do it by following these steps: Right-click on the project, then select Properties Go under C/C++ Build -> Settings Select GCC C Linker -> Libraries In Libraries (-l), add the nam...
7,860,674
9,147,252
Library for skeleton joint extraction with Kinect
I've done a few things with the Microsoft Research Kinect SDK. Getting the skeleton is super-easy and I'd like to do something similar in the context of a commercial project. What is the best C++ library that is available today (even if that's not free / open source)?
Microsoft has published a commercial version of Kinect SDK here.
7,860,874
7,861,270
Execute a pure binary file on Android
Is there a way to run a binary executable file (compile with NDK), on Android? /* #includes #defines ... */ int main(){ // Do something when this is executed return 0; } I want it to run independant from the VM. As in not inside an activity, just a binary that runs directly on the proc
adb push exename /data/bin/exename #next line might be needed if you are developing on Windows adb shell chmod 777 /data/bin/exename adb shell /data/bin/exename But your device has to be rooted. (It also works on emulator.)
7,860,910
7,860,932
return 5th element from last in linked list?
Above question was asked to me in my interview. Though I am still waiting for the result, I am wondering if my approach is correct or if there is any better solution? struct Node { int data; Node * next; }; Node *function( struct Node *head) { if ( ! head) { std::cout...
For the single-linked list your solution should be optimal. For the double-linked list, you could go from the back.
7,860,953
7,861,129
Accessing all pixels in cv::Mat
Is this the correct way of accessing all pixels in cv::Mat: for( row = 0; row < mat.rows; ++row) { for ( col = 0; col < mat.cols; ++col) { } } Or is there a formula method similar to this formula for an IplImage *: temp_ptr = &((uchar*)(img->imageData + (img->widthStep*...
In the best case, where all the pixels are stored contiguously you should be able to do: uchar* pixel = mat.data; for(int i = 0; i < mat.rows * mat.cols; ++i) { // access pixel[0],pixel[1],pixel[2] here pixel += 3; // move to next pixel } To be a bit more generic, but still fast, have a look at the sample cod...
7,861,014
7,861,064
Return constant and non constant by value
There is such code: const int fun(){ return 2; } // can be assigned to int and const int int fun2(){ return 2; } // can be assigned to int and const int Is there any difference in using these functions? They both return by value so it is always copied at the end of function call.
Is there any difference in using these functions? No. There is, however, a difference in their type, and if the functions returned a class type, there would be difference regarding invoking methods on the return value.
7,861,115
7,861,210
How to add a calculator to start menu search?
I want to make a calculator and add it to the Windows 7 start menu that can calculate functions in the search text box. For example, I write "2*2=" in the search text box and it shows me "2*2=4". I don't know how I can do this :( Does Microsoft have any API for this?
No. The Start menu search box is not extensible in that manner. You can add a search provider but it does not execute until the user hits Enter.
7,861,188
7,861,219
Changing return value of fundamental type and class type
There is such code: #include <iostream> #include <string> int returnnumber() { return 2; } std::string returntext() { return "siema"; } int main() { std::cout << (returntext() += "cze") << std::endl; // siemacze //std::cout << (returnnumber() += 2) << std::endl; error: lvalue required as left operand of assi...
because std::string is a class type with a defined += operator as a member function. and the standard allows you to call member functions on rvalues. a silly consequence of that is that struct S { int x; }; S foo() { return S(); } int main() { foo() = S(); // OK, uses member assignment operator. foo().x = 6...
7,861,211
7,862,610
Fast Fourier Transformation in WinForms
I write an application on VS-2008 (WinForms, C++) Need a Fast Fourier transformation Library. Can anybody advise a good one?
I strongly recommend FFTW over anything else. It is fast, reliable, widely used, portable. Yes, you will have to call from managed code into unmanaged code.
7,861,506
7,861,557
Recursive call in lambda (C++11)
Possible Duplicate: Recursive lambda functions in c++0x Why can't I call a lambda recursively if I write it as: auto a = [&] { static int i = 0; i++; std::cout << i << std::endl; if (i<10) a(); //recursive call }; It gives compilation error (ideone): prog.cpp:8:18: error: '((const main()::<lambda()...
The reason is that there is no special case for lambda-expression initializers of auto variables. Such special cases would be prone to errors and misuses. You need to define the rules when you propose that something like a() should work. How is the operator() looked up? What is the precise state of a's type? Will the ...
7,861,533
7,861,568
Performance difference at stack (re)creating?
is there a Performance difference between this: int test; void Update() { test +=2; } and this: void Update() { int test; test +=2; } -- int main() { while(true) Update(); } I ask because the second Code is better to read (you don't need to declare it at Class headers), so i would use it if ...
It is highly unlikely that there is a performance difference between the two snippets only profiling your code can tell reliably but there is a important functional difference tha you should consider here. If your test variable is needed only inside the function update() then you must declare it inside the function. Th...
7,861,733
7,862,019
export overloaded operator of a class
I've created (in Qt and Mingwin the specified case), a class that has the following structure: #ifndef POINT2D_H #define POINT2D_H #include "Calculus_global.h" #include <QtCore> namespace Calculus { /** Class for definition of a point in 2D space */ class CALCULUSSHARED_EXPORT CartesianPoint2D { public: //! Con...
You have to use CALCULUSSHARED_EXPORT in your free functions (the operators in this case) too. This (I think) is true only to Windows.
7,861,748
7,861,986
How can my library let users choose their smart pointer implementation flexibly?
I'm creating a c++ library that makes heavy use of smart pointers, both in public interface and internally. Currently it is "header-only", but as it evolves it is becoming clear that this may not be appropriate. I don't want to dictate a choice of smart pointer implementation to library users. I also have gotten pret...
Not an answer I would take a different approach to the selection of the shared pointer, mainly because I dislike macros. #if MYLIB_STD_SMART_PTR #include <memory> namespace mylib { using std::shared_ptr; using std::weak_ptr; using std::static_pointer_cast; } #elif MYLIB_STD_TR1_SMART_PTR #include <tr1/memory>...
7,861,750
7,861,859
How do I mock non overridden, virtual/non virtual methods of a base class while unit testing?
How do I mock non-overridden non virtual/virtual methods in a base class and test just the derived class's methods? The case here is: I have a base class X which has methods that connect to an external server and do a couple of other things. I have a class Y derived from X. I have implemented two methods in Y. I want t...
One option is to create a Mock_base class and the class Derived inheriting from it in the test directory. Now mock out any implementations in the actual Base that you are not interested in with functions that do nothing. Example the Mock_base::Connect() may return SUCCESS return code. This way you can unit test the De...
7,862,075
7,868,836
Could iostream inserters and extractors be class members instead of global overloads?
Having to declare "global friend operator overloading" to do serialization always struck me as kludgey. It didn't seem foundational to have to declare serialization operators outside of your class. So I was looking for a solid answer for why. (Note: If anyone has better Google-Fu to find a good answer already written...
You get more flexibility by separating the definition of << and >> from the object you're displaying. First of all, you might want to custom-display a non-class type, like an enum, or a pointer. Suppose you have a class Foo and you want to custom-print a pointer to Foo. You can't do it by adding a member function to F...
7,862,092
7,862,123
int or char enum to int , not ASCII
I'm doing a poker game and have hit a wall. Any help would be great. I have 12 card values. The values are chars either 2-9 or TJQKA (enumed below). I need to pass them to an int array such that their value is what gets passed (whether int value or enum value) instead of their ASCII. for the example below, I want: val...
You'll need a conversion function: int to_card(const char v) { switch(v) { case '2': return 2; case '3': return 3: // etc... case 'T': return 10; case 'J': return 11; // etc... } Then in your loop: val[i] = to_card(value[i]);
7,862,163
7,862,178
Finding the middle of an array without knowing the length
Find the middle of the string or array with an unknown length. You may not traverse the list to find the length. You may not use anything to help you find the length - as it is "unknown." (ie. no sizeof (C) or count(C#) etc...) I had this question as an interview question. I'm just wondering what the answer is. I...
Have two counters, c1 and c2. Begin traversing the list, incrementing c1 every time and c2 every other time. By the time c1 gets to the end, c2 will be in the middle. You haven't "traversed the list to find the length" and then divided it by two, you've just gone through once. The only other way I can think of would ...
7,862,323
8,098,381
How to have multiple attempt to enter password, with terminal in RAW mode?
I am creating a login menu in C++ i wish to give the user 3 attempts at entering the password before the program terminates. My code runs fine if the user gets the password right the first time. It would then go into the home menu ect. However, if the user gets the password wrong. The terminal would run up to: Login: F...
I don't know what your specific problem is. However, you can apply standard debugging techniques to find out which part is causing the problem. First, you're doing weird things with terminals (cfmakeraw, tcsetattr, etc). It sounds like that might be related to the problem. So, remove the code that hides the user input ...
7,862,351
7,862,419
deque::insert() at index?
How do I insert() a bunch of items to the middle of a deque in linear time? (The items I am inserting are not accessible through an STL-style iterator.)
There is a deque::insert(iterator pos, const T&x) function taking the position pos as deque::iterator and a single element. Using this method you could insert all elements one by one. pos can easily be obtained (if you have an index before which you want to insert the element) by deque.begin()+index. The insert method...
7,862,572
7,865,415
Manipulating while filtering
I asked a question but did not get any proper answers: A beginner's attempt on image filtering I am stuck with this. What are we supposed to manipulate in Gaussian Blur? I have an IplImage *img which I want to blur, but I am Completely Clueless about which part of the structure I need to modify to pull off the algorith...
The cvSmooth function is used for Gaussian (and other types of) blurring. You can read all about it (and all the other functions in the library) in the OpenCV API. If you insist on doing smoothing yourself (in the case you really want to know about filtering, or you just like to re-invent the wheel), then you need a b...
7,862,582
7,862,848
Press anykey to continue in Linux C++
I am not sure if being in linux makes any different, but i have found online that this: cout << "Press Enter to Continue..."; cin.ignore(numeric_limits<streamsize>::max(),'\n'); Should be sufficient, with #include<limits> in the header of course. However, it does not seem to work in my program. It compiles, it...
In *nix, terminals usually wait for a whole line of input before sending anything to the program. Which is why the example code you posted said "Press Enter to Continue...";, and then discarded everything until the next newline. To avoid that, you should put your terminal in non-canonical mode, which can be done using ...
7,862,583
7,939,279
Affine transform with interpolation
I would like to do an affine transformation on a very low resolution bitmap and I would like to do it while preserving the maximum amount of information. My input data is a 1 bit 64-by-64 pixel image of hand written character and my output would be greyscale and higher resolution. Upon analysing the image I construct a...
OK, here is the solution I ended up with. I transformed all my array[][] into a BufferedImage object static BufferedImage BImageFrom2DArray(float data[][]) { int width = data.length; int height = data[0].length; BufferedImage myimage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); for ...
7,862,671
7,909,659
Decrypting DES with OpenSSL
I'm trying to decrypt a DES-encrypted file from an external source with a known key and IV using OpenSSL (other libraries aren't really an option, as the application links against it already and I don't want to introduce new dependencies). It's a Qt application, so the data's coming in and out as QByteArrays. Here's th...
The issue was just a missing call to DES_set_odd_parity(&key);, which appears to be necessary for correct decoding with this implementation. Working code is as follows: QByteArray AmzHandler::decrypt(QByteArray encrypted) { DES_cblock key = {0x29, 0xab, 0x9d, 0x18, 0xb2, 0x44, 0x9e, 0x31}; DES_cblock iv = {0x5e...
7,862,791
7,863,636
Boost linking on Linux with GCC
I'm trying to compile a C++ program under Ubuntu 11.10 using boost 1.42 installed from the repository (I also tried building boost myself, but the result is the same as with the repo-boost). The source files compile but the linker gives errors... I tried for hours but couldn't find a solution to this, maybe someone can...
Those error messages are impressive: ../../DIAG_DECODER//libDecoder_Element.a(BaseElements_Group.o): In function `bool boost::regex_match<__gnu_cxx::__normal_iterator<char const*, std::basic_string<char, std::char_traits<char>, std::allocator<char> > >, std::allocator<boost::sub_match<__gnu_cxx::__normal_iterator<char ...
7,862,801
7,863,216
Data written to disk callback
How can I get callbacks once data has been successfully written to disk in Linux? I would like to have my programs db file mapped into memory for read/write operations and receive callbacks once a write has successfully hit disk. Kind of like what the old VMSs used to do..
You need to call fdatasync (or fsync if you really need the metadata to be synchronised as well) and wait for it to return. You could do this from another thread, but if one thread writes to the file while another thread is doing a fdatasync(), it's not going to be clear which of the writes are guaranteed to be persist...
7,862,859
7,862,947
Any way to identify a stream?
Is there any way in C++ to identify a file stream? It doesn't really matter what it is, as long as two streams created from the same file have the same "id"; anything that would allow me to say that two streams created from the same file are equivalent (not equal).
As far as I can tell, there's no built-in way to compare two file streams. You would either have to compare the two pointers, which would require you to keep track of streams which are the same (which might not be possible in your case, judging from the format of the question), or read the data in both file streams and...
7,862,961
7,862,975
How can I get the number of keys in an .ini file using C/C++
Is there any way to get the number of keys from an .ini file? ie. [mysection] server=192.168.1.100 port=1606 blah1=9090 temp1=abcd etc I want to get number of key (from the above example it should return 4) Please, any help will be great.
Kernel32.dll exports GetPrivateProfileSection() which returns a null-separated list of name/value pairs. You can count the pairs.
7,863,145
7,863,177
How to test if a file exists before creating it
I would like to see if a file exists. If it does not exists, then I would like to create it. I am using Linux by the way.
You can't do that reliably. Between when you check to see if the file exists and when you create it, another process may create it. You should just go ahead and create the file. Depending on the larger thing you're trying to do, you might want one of these options for what to do if the file already exists: modify th...
7,863,167
7,864,008
Boost thread_group blocks when calling add_thread from thread, why?
I've written a multithreaded program similar to the following structure (I've omitted the mutex and extraneous code), and it blocks on the call to boost::thread_group.add_thread() when called from a thread. Is there any way around this, so the call doesn't block? boost::thread_group group; void threaded_function2() { ...
Correct me if I'm wrong, but what might be happening here is that the join_all call ran before the thread getting added, making the thread_group object block until the other threads are released. One solution is to make a mutex on the main function to wait for the threaded_function completes to call the join_all method...
7,863,202
7,876,338
Segfault in Ruby Extension Code
I'm writing a small Ruby extension in C/C++ that makes boost::dynamic_bitfield available in Ruby. My code does perfectly compile, but when loading the extension and trying to instantiate the class I am getting a segfault. I haven't been able to properly utilize gdb to find the error or where it is happening. I think I...
The solution was to add: new(bf) BitField(); to BitFieldNew(size); to initialize the struct and boost::dynamic_bitset.
7,863,245
7,863,298
Printing a base 4294967296 integer in base 10
I have in C++ a vector of 32 bits integers (variable size, continous memory; like a C-array), representing a number in base 4294967296. I would like to print it in base 10. These numbers can be extremely big and take over a few megabytes of memory. What would be the best way to do this in terms of performance? Can I us...
Yes, you can use GMP for this. The function that you're looking for is mpn_get_str: http://gmplib.org/manual/Low_002dlevel-Functions.html#Low_002dlevel-Functions Now the only issue is the size of mp_limb_t. It is either a 32-bit integer or a 64-bit integer depending on the platform. If it's a 32-bit integer, then you ...
7,863,411
7,863,434
What's wrong with this class?
I think the problem is in main() but this compiles fine but I get no output. I think maybe it's not initalizing correctly because in debug mode it says "myCharQ {item=0x0018fa00 "ÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌ̺yâpú" front=-858993460 rear=-858993460 ...}" How would you rewrite this so that it is proper? I'm just starting...
You never initialize the member variables front, rear, and count. You shadow them in your constructor by declaring variables with the same names again. Drop the int and just assign them (though this is not why the values aren't printed correctly, more on that in a bit). Actually, don't do that either; use an initia...
7,863,467
7,863,483
Use double colons (::) in #define
May I use double colons in #define ? I'd like to save some writing in the implementation files, e.g. like this: // foo.h #define template template <class T> #define foo:: foo<T>:: template class foo { T& baz(); }; #include "foo.tpp" #undef template #undef foo:: // foo.tpp template T& foo::baz() { // do stuff. ...
No. The name of a macro must be an identifier; it can't consist of other characters and it can't consist of multiple tokens. #define template is invalid because template is not an identifier, it is a keyword. #define foo:: foo<T>:: was valid in C90 and C++98: it defines a macro named foo that is replaced by :: foo<T>...
7,863,513
7,863,650
(C++) where do I put all my templates?
I have different classes all arranged in a hierarchy. To reduce the amount of code, I started creating template functions. The base class will use the template functions and some of the derived classes will also use the same functions. Where am I suppose to put all of these templates so I don't get undefined referenc...
I see a lot of people confused by this thing... templates are not types. They become types when instantiated. For this reason members of templates must stay in the same data unit you are going to use them. If you template is generic and you want to use it in all your code, just put everything in header files. Now, if ...
7,863,538
7,863,616
Recursive functional explanation in binary tree
I was going through the tutorial of binary tree . And I am slightly stuck in use of recursive function . say for example I need to count no of nodes in a tree int countNodes( TreeNode *root ) { // Count the nodes in the binary tree to which // root points, and return the answer. if ( roo...
With recursive functions, you should think recursively! Here's how I would think of this function: I start writing the signature of the function, that is int countNodes( TreeNode *root ) So first, the cases that are not recursive. For example, if the given tree is NULL, then there are no nodes, so I return 0. Then, ...
7,863,603
7,863,645
How to make template rvalue reference parameter ONLY bind to rvalue reference?
I'm writing a network library and use move semantics heavily to handle ownership for file descriptors. One of my class wishes to receive file descriptor wrappers of other kinds and take ownership, so it's something like struct OwnershipReceiver { template <typename T> void receive_ownership(T&& t) { // takin...
You can restrict T to not be an lvalue reference, and thus prevent lvalues from binding to it: #include <type_traits> struct OwnershipReceiver { template <typename T, class = typename std::enable_if < !std::is_lvalue_reference<T>::value >::type > void ...
7,863,606
7,863,641
"Undefined reference to" function error
I'm getting a really frustrating error that I've been struggling with for some time now. I had the program working fine before I started changing the data type from int to use templates. This is the error I get: g++ -c UseList.cpp g++ -c List.cpp g++ UseList.o List.o -o UseList UseList.o: In function `main': UseList.cp...
You need to put all Template implementations in the header file. As the compiler will not know what type the function might have, he is not able to compile the cpp file. So move all stuff from List.cpp to List.h and it should work.
7,863,648
7,863,658
Function that given these 2 values produces this third value?
I'm trying to write a function that when given 2 arguments, the 2 leftmost columns, produces the third column as a result: 0 0 0 1 0 3 2 0 2 3 0 1 0 1 1 1 1 0 2 1 3 3 1 2 0 2 2 1 2 1 2 2 0 3 2 3 0 3 3 1 3 2 2 3 1 3 3 0 I know there will be a modulus involved but I can't quite figure it out. I'm trying to figure out...
If a and b are the positions of the two persons, their "distance" is: (4+b-a) % 4 This also shows that the forth block in your example is wrong.
7,863,956
7,863,971
Default value of an unset boolean in C++?
Possible Duplicate: Why is a C++ bool var true by default? Say I were to do something like this: class blah { public: bool exampleVar; }; blah exampleArray[4]; exampleArray[1].exampleVar = true; In exampleArray, there are now 3 unset instances of exampleVar, what are their default values without me setting the...
The default value depends on the scope that exampleArray is declared in. If it is local to a function the values will be random, whatever values those stack locations happened to be at. If it is static or declared at file scope (global) the values will be zero initialized. Here's a demonstration. If you need a member v...
7,863,972
7,864,303
Why is my loops for reading into Vector <vector <string> > not working? Linux C++
I am trying to read in a file that only have one column, and write it out to terminal in 3 columns. I have decided to read the one column into separate vector<string>. Then put the vector string into one vector<vector <string> >, before writing out to terminal. I know it is suppose to be a roster for chores in a flat, ...
You need to call temptVec.clear() somewhere.
7,863,997
7,864,059
How to test for end of line when reading a double in Linux
Ok so I have this problem. For some reason whenever I read a file in Linux. It has an extra carriage return at the end of the line. This is causing errors in my program. So I would like to know how would I test for the end of line condition whilst extracting doubles from each line fin >> variable The file is formate...
Even with the extra carriage return, this loop should work: double d; while( fin >> d ) { std::cout << "The value is: " << d << "\n"; }
7,864,077
7,864,092
Handling multi-dimensional array lengths in C++
I would like to build a function that takes a multidimensional array and prints it like a grid. I'm having trouble with it because c++ doesn't allow a function to have a multidimensional array argument unless you specify its length. There is a question about it on here, that was answered using vectors. I haven't learn...
In C++ you can pass array by reference. With making an array a template, it's possible to receive any length in the function. For example, template<size_t SIZE1> void print (int (&arr)[SIZE1]) { ... } template<size_t SIZE1, size_t SIZE2> void print (int (&arr)[SIZE1][SIZE2]) { ... } template<size_t SIZE1, size_t SIZE...
7,864,106
7,864,136
Using structs as paramaters and accessing their elements in a template class
I have a template class btree and have defined a struct Node in the public definitions of the header file struct Node { vector<Node> chi_; vector<T> val_; Node *par_; Node(size_t n, Node *parent) : par_(parent) { chi_.reserve(n+1); val_.reserve(n); } ~Node() { chi_.clear...
one and two are references to pointers, so you need to use the -> operator to access the members. one->val_.push_back(two->val_.at(a)); Also, in C++ you don't need to use the struct keyword when referring to the type. template <typename T> void btree<T>::addAll(Node* &one, Node* const& two)
7,864,162
7,864,246
Comparing to items in an Array c++
alright guys, this should be an easy one... I have an int array and I want to see if the the numbers in the array are in succession. For some reason when I do this (below) my array goes from int values to ascii and gets all funky and doesn't work. Any suggestions would be greatly appreciated. In this exampleit should ...
I would write something like this, a little simpler to read. bool issequential(const int* array, int size) { for (int i = 1; i < size; ++i) if (array[i - 1] + 1 != array[i]) return false; return true; }
7,864,173
7,864,204
Converting array of type char into a int variable
Compiling this on Codepad: #include <iostream> using namespace std; void main (void) { char ch[2]; int value; cout<<"Enter two integers between 0-9"<<endl; cin.getline(ch,2); //testing with char array //(...) //how could I do operations like '*', '+', '-', or '/' to the char arrays } Give...
There are a few different problems with the code you've posted. main needs to have a return type of int. int main() { /* .. */ } Your call to cin.getline will only fill a single character in the array you've declared, because the function call will null terminate the array. You need char array[3]; cin.getline( array,...
7,864,418
7,864,451
How to declare struct A that contains instances of class B, where class B has functions that return struct A?
I tried my best to describe the goal in the title, but here it is in code: struct Bar { Foo one; Foo two; } class Foo { Bar function(); } I know this won't work, but how would I accomplish the idea? The reason I'm wanting to make the struct global is because it's used in main.cpp as well. I've already tri...
Since Bar contains instances of Foo, the latter cannot be incomplete in the declaration of the former. So you'll need to declare Foo before declaring Bar. However, since Foo contains a function that returns a Bar object you'll have to forward declare Bar before declaring Foo. struct Bar; class Foo { Bar function()...