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,864,702
7,867,057
Audio editing through C++/Java
I wrote text-to-speech engine (from scratch) and it works pretty fine. But sound needs to be a little bit smoother. I can achieve it in audio editing programs (editing output file). But how can I do complex editing through C++/Java? How other text-to-speech engines do it?
Text to speech engines are applying complex filters on the output audio. These filters depend on the language. I recommend you to find a good book on audio processing. Since the topic is very complex, a good book might shed some light on the problem.
7,864,726
7,864,774
Pointers to vector returns only last value of vector
I've got the following code, with a vector of struct HE_face's and an array of struct HE_edge's. Based on some test I set add a new face to the vector of faces, and set each proceeding edge to the last face added to the vector of faces. However, for some reason the output is that all the edges are being set to the sa...
You take the address of an element of f_list, which address is subsequently invalidated by a push_back(). Quoting my favorite non-official reference: This effectively increases the vector size by one, which causes a reallocation of the internal allocated storage if the vector size was equal to the vector capacity befo...
7,864,736
7,864,802
Mixing getters/setters and normal variables
I'm writing a C++ wrapper around a C library and, as such, need to use getter/setter methods to call the original C functions. class View { public: GR_COLOR getBackgroundColor(); void setBackgroundColor(GR_COLOR color); GR_COLOR getBorderColor(); void setBorderColor(GR_COLOR color); }; Is it consider...
If you define getters and setters for all of your variables, and make the variables private, future changes to your code would be much easier. This is one of the principles behind getters/setters in OOP. People wouldn't have direct access to your members, and you don't have to worry about how they use it because YOU co...
7,864,781
7,864,794
Creating a vector of class pointers inside another class?
I'm running in to an issue with two classes that I created. It's a simple sports season program. I created one class called Season which is creating a vector of pointers to Game objects. The compiler is complaining about Game being an undeclared identifier even though I have the class defined and tested that it worked....
The compiler reads your program line-by-line, starting at the beginning. At the point where you first reference Game: vector<Game*> games you have not yet declared Game. You must either move your Game declaration prior to Season, or you must forward-declare Game. To forward-declare Game, add this declaration prior to...
7,864,827
7,864,846
Segmentation fault at different places
I have a pretty decent sized program (~1000 loc) . When i run the program , ./indexer Gives segmentation fault on 800th iteration . But when i do gdb indexer run It goes well beyond 800th and shows seg fault at around 1200th iteration . I dont understand why it is happening like this . Any pointers to possible m...
The conditions under which your program runs can be very different when run with the debugger and without. If you have a bug in your program, especially a bug that is undefined behaviour, then anything could happen. Since the problem still happens when using the debugger, I would debug that first, and then if the probl...
7,864,918
7,864,952
Compile and run C++ code in single key stroke using vim in Mac OS
I am using Mac OS X version 10.6.8. Is there any helpful script to compile and run my c++ file from inside vim using single command?
Yes there is: :nnoremap <F5> :<C-U>make %:r && ./%:r<CR> This will run make with the C++ file (less its extension) as the target and run the file in the same directory with that target's name. See the following :help for more information... nnoremap: Create a normal-mode mapping <F5>: for F5 (other function keys are ...
7,864,924
7,864,946
Is it possible to keep a reference as a class member in C++? Please give an example
As far as I know, References need to be declared and initialized at the same time. I guess, its only use lies in passing arguments and in some cases Polymorphism. Is it possible to keep a reference as a data member in a class? If yes, when should we need that? Please give me an example.
You would use a reference as a class member when it is an integral part of the class, without which the class cannot function, and you want to either share this part among several classes or use it polymorphically: class Presenter { IView & view; IModel & model; Presenter(IView & view, IModel & model) ...
7,865,010
7,865,022
What to inherit from when I want to create a new fstream?
I want to define a new type of filestream in C++. What should I inherit from?
Inherit from basic_filebuf, or basic_streambuf if you're writing the I/O parts from scratch. You might also want a class derived from basic_[i/o]fstream, but that is strictly optional, for convenience. If templating is not required, drop the basic_ and inherit from the classes, not the templates. The *stream classes al...
7,865,127
8,272,734
Cannot run Opencv with C++ syntax
Im using Opencv 2.3.1 on Visual studio 2010 (vc10) I have configured opencv based on many tutorials and can compile & run C-syntax program like: #include "StdAfx.h" #include <iostream> #include <opencv2/opencv.hpp> using namespace std; using namespace cv; int main () { IplImage* img = cvLoadImage("D:\cat_helme...
You say that you have followed a multitude of guides and tutorials. I've had great success with this one http://www.anlak.com/using-opencv-2-3-1-with-visual-studio-2010-tutorial/ The thing is that this guy walks you through the 'park' and helps you unravel two major issues whilst setting up OpenCV 2.3.1; one of which i...
7,865,262
7,865,338
Linker stripping unused classes
I am working on a cross platform project in C++, under IOS and Android, and I am having the following situation : I am writing a library used to load scene graphs directly from xml files describing them. The library has a base tree node class, that implements all the functionality to make a class constructable by it's...
It is implementation-defined whether the dynamic initialization of a non-local variable with static storage duration is done before the first statement of main. If the initialization is deferred to some point in time after the first statement of main, it shall occur before the first odr-use (3.2) of any function o...
7,865,280
7,865,303
how can a derived class function call a function of the base class?
Derived class function cannot access even the public members of the base class when the access specifier is private. But how is it that the function 'xyz' of my derived class able to call 'showofb'? I even tried it by calling the function 'showofb' in the constructor of C. In both cases it works. How is it able to call...
B::showofb() is a public function. So it can be called by C. If you modify B to make showofb private, C will no longer be able to call it. The private inheritance means that all public and protected members of B are inherited as private by C. So C can still call public and protected members of B, but any classes derive...
7,865,413
7,865,547
"Nested" scoped_lock
My shortened, simplified class looks as follows: class A { public: // ... methodA(); methodB(); protected: mutable boost::mutex m_mutex; sometype* m_myVar; } A::methodA( int someParam ) { boost::mutex::scoped_lock myLock(m_mutex); m_myVar->doSomethingElse(); } A::methodB( int som...
This is what boost::recursive_mutex for it allows to obtain the lock by the same thread without deadlocking several times. Use it instead of boost::mutex
7,865,543
7,865,586
How to create precompiled header with codeblocks and gcc
I have a file which has been tested and works as intended: #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> template<class Integral> struct Promote { typedef boost::mpl::vector<char,s...
From the docs you link: To create a precompiled header file, simply compile it as you would any other file, if necessary using the -x option to make the driver treat it as a C or C++ header file. So: g++ -x c++ -o header.gch -c header.h for C++ code will create the precompiled header. It wont speed up the build proc...
7,865,552
7,865,852
Can a template argument be an expression?
I want to do this: template<T> bool AssertThrows() { try { T; // T is an expression, so evaluate it here return false; } catch(...) { return true; } } int main() { bool throws = !AssertThrows<5 + 2>(); return !throws; } But this does not work: all I get is these compiler errors: $ clang++ a.cc a...
In this case a function taking another function to simulate pass by name could work if you don't mind template<typename T> bool AssertThrows(T t) { try { t(); // t contains an expression, so evaluate it here return false; } catch(...) { return true; } } int main() { bool throws = !AssertThrows([]{ ...
7,865,555
7,866,333
OpenMP shared vs. firstprivate performancewise
I have a #pragma omp parallel for loop inside a class method. Each thread readonly accesses few method local variables, few call private data and a method's parameter. All of them are declared in a shared clause. My questions: Performance wise should not make any difference declare these variables shared or firstpriva...
Well, they're not the same thing. With shared, they are shared between all the threads. With firstprivate, each thread gets it's own copy. If you're only reading the variable, then it's better to leave it as shared as to avoid copying it. (In C++, firstprivate will implicitly invoke the copy constructor.) Correct, mul...
7,865,590
7,865,650
What are some open source C++ projects with excellent coding style?
I'm looking for a practical C++ coding style for medium to large projects which maximizes readability. I am indifferent to clever design patterns or constructs as long as the code is obvious when you browse it. C++ style guides are also welcome, but I prefer to browse real code so I can easily determine if their guide...
I would recommend ITK. It has a large codebase, but it's extremely coherent imho.
7,865,700
7,866,585
create new visual studio project, add files and run it - command line
is there any way to create a new visual studio project without using IDE, Instead use command prompt?? I am working on a project which will generate small C++ program, so i want to create a new project, add that C++ file to that project, compile and run it, all using command prompt (batch file) only.. so could anyone p...
Let CMake make your project files for you. It uses a much more legible syntax, and you can also generate project files for a variety of other build systems. As an example, here's a very basic CMake file: project(Foo) cmake_minimum_required(VERSION 2.8) #project source files file (GLOB HEADER_FILES "*.h" "*.hpp") file ...
7,865,715
8,007,644
String passing from JavaScript to Qt/C++ object
I'm stuck on a QtWebKit bridge issue on Windows and I ran out of options. I don't have access to the exact code used but its something like below. C++ class MyObject : QWidget { Q_OBJECT public: QString data() const; void setData(QString); Q_PROPERTY(QString data READ data WRITE setData) }; /* ... */ M...
I'm partly there. String passing works as expected. However, the C++ object is embedded on a webpage and wraps an ActiveX (ActiveQt) object. For this, I've seen some pages where you create a class that inherits from a QWebPage. There you have a createPlugins method that asks the QUiLoader to construct the widget for yo...
7,866,113
7,866,126
Should this be a namespace or a class?
When you have a set of functions that have no interaction between them, you place them in a namespace. (Example, a math namespace.) When you have some public attributes and optionally a set of functions that act on those attributes, that should become a class. But what about when you have a set of related functions but...
Any time you have behavior and state it should be a class, even if the state isn't publicly accessible. One practical reason for this is it makes it easier to unit test other modules that interact with the module in question.
7,866,166
7,866,356
Accessing methods after inheritance error
I am using inheritance for my code. ChangeRequest is my base class. The code is as follows. ChangeRequest.h #include <iostream> #include <string> using namespace std; class ChangeRequest { int swapDay; int newDay; public: void setSwapDay(int newDay); int getSwapDay(); void setNewDay(int newDay); int getNewDay(); };...
What is type of changeList? Although you have created an object of the derived class, I suspect that you are pushing it into the container of the base class. Possibly you are getting few warnings before this error as well, because of pushing derived object into the container of type base. If you want to make a conta...
7,866,188
7,866,247
Implementing the warp/liquify tool in C++
Im looking for a way to warp an image similar to how the liquify/IWarp tool works in Photoshop/Gimp. I would like to use it to move a few points on an image to make it look wider than it was originally. Anyone have any ideas on libraries that could be used to do this? I'm currently using OpenCV in the same project so ...
From this search 'image warp operator source c++' i get: ..... Added function 'CImg ::[get_]warp()' that can warp an image using a deformation .... Added function 'CImg ::save_cpp()' allowing to save an image directly as a C/C++ source code. ... then CImg could do well for you.
7,866,218
7,866,345
How to serialize a tree structure in C++?
I'm trying to serialize/deserialize a game scene for network sending/receiving and saving/loading from/to disk. My game engine uses Nodes and Components and as such those are the only objects that need serializing. A scene might look like this: Root Node - Node - SpecializedComponent - SpecializedComponent ...
A descent recursive parser usually it's the simpler and sufficiently powerful option to handle the reconstruction part. I could try to setup some code to show in concrete, in pseudocode some thing like this: Node *parse(stream s) { content = new Node; s >> content >> nsons; for (int c = 0; c < nsons; ++c) con...
7,866,293
8,266,780
Definite guide to make QWidget app Portrait oriented on Harmattan
Is there any definite guide how to make QWidget app portrait oriented on MeeGo Harmattan device? I'm currently working on N950 (devel version of N9) and my app is in landscape mode all the time. App was previously written as QApplication with QMainWindow
According to this Nokia documentation, QWidgets are not supported on Harmattan. I think there is some backward compatibility, but if you keep using QWidget you will not have full integration in the platform. This blog post also provides some guidance on porting a Qt application to Harmattan. If you convert your applica...
7,866,576
7,866,616
Difference between declaration of function with extern and without it
There is such code: #include <iostream> extern void fun(); int main(){ fun(); return 0; } void fun(){ std::cout << "Hello" << std::endl; } Is there some difference between declarations: extern void fun(); void fun(); ? Code above behaves the same with extern and without extern keyword.
Function declarations do have external linkage by default, so adding the extern keyword to a function declaration makes no difference, it is redundant.
7,866,637
7,866,659
Passing by value a type struct to a function, Error:two or more data types in declaration of 'average'!! -
Hello to all that read I have a small problem(or it could be large!), just one error at compile time but as we all know one error is all it takes to hinder progress. Basically I am fairly new to C++ and have been tasked with writing the following code and passing by value a type stuct argument to the function. But I g...
See this? int void average(student programming){ That's "two or more types" in a row, in the part where you say what the return type is for the function. Make up your mind. There are several other problems with your code, mostly just stylistic. You don't want your function declaration to be extern (since it's right th...
7,866,692
7,866,705
Why can extern be applied to definitions?
Why is this legal? extern int foo = 0xF00; // Gets a warning, still compiles extern void bar() { // No warning int x; } Is there a reason to why this is allowed?
Sometimes it's useful extern const int foo = 0xF00; Without the extern, in C++ foo would be static and have internal linkage (which means you could not use foo from another translation unit). The extern in both cases in your example is redundant. In C99 an extern can make a difference for inline functions..
7,866,838
7,867,102
Instance of a non-templated class using templated constructor interpreted as a function definition?
My issue is best demonstrated by the following code: #include <fstream> #include <iterator> class Bar { public: template <class Iterator> Bar(Iterator first, Iterator last) {} }; void foo(const Bar& bar) { } int main(int argc, char** argv) { std::ifstream file("file.txt"); Bar bar(std::istream_iterator<...
ArunMu gets partial credit, it is indeed an example of Most Vexing Parse, but that term was coined in Meyer's Effective STL (Chapter 1, Item 6) not Exceptional C++. It is being interpreted as a function pointer (the (__cdecl *) portion of the error is a dead give away), and apparently the C++ standard requires it to be...
7,866,861
7,866,917
g++ doesn't inline functions
There is such code: int fun1(){ return 2 + 3; } inline int fun2(){ return 4 + 5; } int main(){ int a = fun1(); int b = fun2(); return 0; } and corresponding assembly code: .file "prog47.cpp" .text .globl _Z4fun1v .type _Z4fun1v, @function _Z4fun1v: .LFB0: .cfi_startproc .c...
GCC has an attribute which forces inlining: always_inline inline int fun2() __attribute__((always_inline)); inline int fun2() { return 4 + 5; } Will cause it to work on any optimization settings.
7,866,866
7,866,871
Evaluate several bools, break on first true c++
All, quick and easy one here... I'm writing an Evaluate function that runs through a bunch of other bool functions. Right now, I'm basically doing an if, else if loop (seen below). Any suggestions on another way of doing this??? I'm assuming I could do this with a switch but have never used them before like this. int...
You can't use a switch because the labels have to be constant. What you are doing is the correct way.
7,867,220
7,867,285
std::make_tuple doesn't make references
I've been experimenting with std::tuple in combination with references: #include <iostream> #include <tuple> int main() { int a,b; std::tuple<int&,int&> test(a,b); std::get<0>(test) = 1; std::get<1>(test) = 2; std::cout << a << ":" << b << std::endl; // doesn't make ref, not expected auto test2 = std::m...
Try forward_as_tuple: auto test3 = std::forward_as_tuple(ar,br);
7,867,320
7,867,375
Assignment-Operator for templated class
For clarification, I'm citing James McNellis answer in the post "Template assignment operator overloading mystery": The implicitly-declared copy assignment operator, which is declared as follows, is still generated: Wrapper& operator=(const Wrapper&); Now I have a similar class and would like to know what the defini...
This template<typename T> Wrapper& Wrapper<T>::operator=(const Wrapper&) which is really just shorthand for template<typename T> Wrapper<T>& Wrapper<T>::operator=(const Wrapper<T>&) The other version would apply to a non-template class named Wrapper, it has no effect on your templates.
7,867,414
7,867,567
Display Image in Visual c++ windows application
I am a beginner to visual c++ Windows application programming and I want to display an image on the screen but I don't know how. Can anyone help me? Most of the stuff I found on the net was about MFC application which I'm not interested in. I want this application to be as simple as possible so it's not surprise that ...
BitBlt, look it up on MSDN. Also see, http://www.winprog.org/tutorial/bitmaps.html.
7,867,649
7,867,821
c++ win32 create a text only button
I would like to add a simple text button to my c++ win32 application. I'm creating the button using CreateWindowEx function, but can't figure out the correct style to do so. I would like to display a text only button and be able to recive messages when the user clicks on it. The style i would like to get is identical t...
You could create a "Button" class window with the BS_OWNERDRAW style and handle the WM_DRAWITEM messages. In your WM_DRAWITEM message handler you can simply display the text.
7,867,769
7,867,792
BIOS like UI with C++
Does anyone know how I can make a program with user interface like BIOS has? Like an API or something. I've seen some shops having software using an interface like BIOS has at the shop's computer(s) for checking product availability etc. I'm talking about a UI like this:
it is called NCurses, and is basically a library to create UI interfaces in text virtual terminals Here is a somewhat decent tutorial about how to use it EDIT for windows platforms, you need a port library called PDCurses. I Think it relies on mingw but i can't tell for sure since i've haven't used it
7,867,842
7,867,980
Why do I get a compiler warning for converting a string literal to a char*, is it bad?
So the compiler tells me this is a deprecated conversion from a string-literal to char*: char* myString = "i like declaring strings like this"; Should I be worried about this? Is this the wrong way to do this? I need to pass myString to a function that accepts a char* , who should I properly initialize the char* with...
It shouldn't even compile. If you need to pass it to function that you are sure won't change the string you need to use const cast, its one of its correct uses: functionName(const_cast<char *>("something")); Or if you don't want the const cast, you can copy the string to the stack: char str[] = "something"; functionNa...
7,867,996
7,868,014
Should I use `inline` on heavily used functions?
I have a class cnVector that represents a point in 3 dimensional space. Its operators + - * / are used intensively. Their implementation is very short: cnVector cnVector::operator + (const cnVector& v) const { return cnVector( x + v.x, y + v.y, z + v.z ); } My question is, because this func...
Yes you probably should. The good use case for the inline keyword in c++ is: small functions, heavily used. See also http://msdn.microsoft.com/en-us/library/1w2887zk%28v=vs.80%29.aspx
7,868,009
7,868,542
Why is no qualification necessary?
OK, I'll just post the complete program even though it has extraneous stuff and the code in question is the dead code… #include <iostream> #include <fstream> namespace detail { // Solution by Johannes Schaub alias litb // http://groups.google.com/group/comp.std.c++/browse_thread/thread/b567617bfccabcad tem...
Some thoughts about why you have to specify std::ifstream in constructor's initializer . I think typedef is the culprit - ifstream is defined as typedef basic_ifstream<char, char_traits<char> > ifstream;). If you change your constructor to explicit InFStream( char const* filename, ios_base::openmode ...
7,868,036
7,870,849
How to capture signal from Q(double)spinbox
I'm writing a mini application by means of Qt 4.7. And I have a reoccurring problem with some QSpinBoxes and QDoubleSpinBoxes. I set the editingFinished() signal and when I change the value in any of these fields they send two signals: when the spinbox loses focus and when enter is pressed. So when I press the tab or e...
You could try checking if the spinbox widget has the focus at the beginning of your slot, it should tell you if the editingFinished() signal was the result of Enter/Return key or the loss of focus. void Dialog::on_spinBox_editingFinished() { if(ui->spinBox->hasFocus()) return; // rest of your code ...
7,868,100
7,870,724
QGraphicsView size in a GridLayout
I have found this: Getting the size of a QGraphicsView But I can't figure out what does it mean to "move my initialization code to showEvent" and I can't comment on that answer. I am want to resize a QPixmap so it could fit my QGraphicsView. I've placed my graphicsview in Designer and set GridLayout for my main window....
The QGraphicsView will be resized by the QGridLayout after the widget is shown, and can be also resized later when the window is itself resized. So you should change the size of the pixmap as a result of a QResizeEvent, either by subclassing QGraphicsView to redefine resizeEvent(), and then promoting your view object t...
7,868,115
7,868,162
fastest way to compute angle with x-axis
What is the fastest way to calculate angle between a line and the x-axis? I need to define a function, which is Injective at the PI:2PI interval (I have to angle between point which is the uppermost point and any point below). PointType * top = UPPERMOST_POINT; PointType * targ = TARGET_POINT; double targetVectorX = t...
Check for y being zero as atan2 does; then The quotient x/y will be plenty fine. (assuming I understand you correctly).
7,868,217
7,868,520
Swapping keys and values of a map in C++
I'm looking for a function in C++ that for swap the contents of a map ... that is: those that were the keys now become the items and those that the items were now the keys. Can you tell me if there is something about this?
As Geoffroy said, std::map doesn't allow this behaviour. However, you might want to use a STL-like container Boost.Bimap - bidirectorial map. A Bimap is a data structure that represents bidirectional relations between elements of two collections. The container is designed to work as two opposed STL maps. A bimap betwe...
7,868,237
7,868,245
C++ header guards won't compile
Can't get any code using header guards to compile in vs 2010. For example: #ifndef SIMPLE.H #define SIMPLE.H #include <iostream> class Place { private: int m_xplace; int m_yplace; Place(){} public: Place(int x, int y) : m_xplace(x), m_yplace(y) {} void Move(int x, int y); void set_place(int x, int y) {m_xplace = x, m...
You can't use . in the identifier. Try this instead: #ifndef SIMPLE_H #define SIMPLE_H
7,868,248
7,868,334
Simulating templated constructor. Too odd?
I wanted to make a templated constructor, but I found I had no way of explicitly listing the template arguments, so I had to find another solution. Here's what I did: ResourceManager rm = ResourceManager::Create<physfs::ifstream>(); Do you have any other ideas how I might achieve this upon construction? or is this a g...
I think your code should do. To improve design, consider declaring types inside (for instance) ResourceManager and using that to qualify the constructors, as needed.
7,868,936
7,868,998
Read file line by line using ifstream in C++
The contents of file.txt are: 5 3 6 4 7 1 10 5 11 6 12 3 12 4 Where 5 3 is a coordinate pair. How do I process this data line by line in C++? I am able to get the first line, but how do I get the next line of the file? ifstream myfile; myfile.open ("file.txt");
First, make an ifstream: #include <fstream> std::ifstream infile("thefile.txt"); The two standard methods are: Assume that every line consists of two numbers and read token by token: int a, b; while (infile >> a >> b) { // process pair (a,b) } Line-based parsing, using string streams: #include <sstream> #include...
7,868,948
7,871,533
Debugging SWIG PHP extension: undefined symbol: _ZN15SplashOutputDev9updateAllEP8GfxState
I just reinstalled my server, switching from Ubuntu 11.04 to 11.10 and from 32 to 64-bit. Afterwards I tried to reinstall my custom SWIG PHP extension. I compiled with swig -I/usr/local/include/poppler -Wall -php -c++ popplig.i g++ -g -I. -I/usr/local/include/poppler -I/usr/include/php5 -I/usr/include/php5/main -I/usr/...
g++ -Wall -Wextra -g -lpoppler -shared popplig_wrap.o... This command line is incorrect: libraries are supposed to follow objects that use them on the link line. See if moving -lpoppler to the end of the link line will Make it show up in ldd popplig.so and Fix the unresolved symbol problem.
7,869,014
7,869,142
Most appropriate associative STL container when key is part of object [C++]
I have a class like this: struct Thing { unsigned index; // more data members }; I am using a std::map<Thing> to contain my Things. Calling code looks something like this: Thing myThing(/*...*/); std::map<Thing> things; things[myThing.index] = myThing; // ... Thing &thing3 = things[3]; I was wondering if the...
I don't see why inline bool operator<(const Thing& a,const Thing& b) { return (a.index<b.index); } std::set<Thing> things; // Uses comparison operator above Thing &thing3 = *things.find(Thing(3)); doesn't do exactly what you want. No duplication/copying of the index field, and key comparison as efficient as the ...
7,869,102
7,869,137
Including a 'set' inside of a 'struct'
I'm trying to include a set, inside a struct, but I don't know how to pass the callback compare function to the set constructor when doing this. This is a basic example of what I've tried: struct pointT { int x; int y; }; struct pathT{ Stack<pointT> pointsInPath; Set<pointT> pointsIncluded; // need ...
Your struct in c++ is automatically a class. therefore you can provide a constructor struct pathT { public: pathT(); private: Stack<pointT> pointsInPath; Set<pointT> pointsIncluded; }; pathT::pathT() : pointsIncluded(ComparePoints) { } regards
7,869,114
7,869,179
Erasing element from Vector
In C++, how can I delete an element from a vector? Delete it right from where it is, i.e. let the vector resize Swap the element to be deleted with the last element s.t. pop_back() can be used (which I hope doesn't involve copying everything around...) For (1), I've tried the following, but I'm not quite sure if it d...
void removeItem(Item*item){ for(int i=0; i<items.size(); i++){ if (items[i]==item){ swap(items[i], items.back()); items.pop_back(); return; } } } Though, if the order doesn't matter, why not just use a std::set?
7,869,322
7,869,416
What is the source of this segmentation fault?
I've got a bizarre error here: 882 Segmentation fault ./a.out The segment of code: int end=array.Length, loop=0; cout<<end<<" about to print"; for(;loop<end;loop++){ cout<<"\nMr. loop says: "; array.get(loop).print(fout); } Output of my program: enpty initializer called for llist enpty initializer called ...
Unless you're doing low-level memory operations (and you're not doing this in the posted program), a segmentation fault is a sign of memory corruption, i.e. you've messed up some coding. Note that the memory corruption typically occurs before the error is triggered. In extreme cases, initial memory corruption and actua...
7,869,493
7,869,519
Variadic template acting weird
I wonder if I'm doing something wrong or if this is a compiler bug. I'm using Intel C++ Composer XE 2011 for Windows with SP1 (or update 6, which is currently the latest). See the commented lines in the code. #include <tchar.h> #include <iostream> #include <conio.h> template <typename ...T> struct first_va_arg {}; te...
Since you have dependent name, you need to say typename: template <typename ...T> inline typename first_va_arg<T...>::type getFirstArgTypeDefaultValue( const T& ...values ) // ^^^^^^^^ { typedef typename first_va_arg<T...>::type FirstArgT; //.. } Note that you are missing the base case...
7,869,541
7,869,556
C++ - Concatenating strings (like PHP?)
I've looked around and I haven't found a good answer. I have files like this: text1.txt text2.txt text3.txt user wants to specify which file to open: int x; string filename; cout << "What data file do you want to open? (enter an int between 1 -> 3): "; cin >> x; filename = "P3Data" << x << ".txt" ; //does not compile ...
To use the streaming interface, you need a stringstream: std::ostringstream filename; filename << "P3Data" << x << ".txt"; myfile.open( filename.str().c_str() ); Otherwise, you can concatenate two strings using +.
7,869,606
7,869,647
Error: passing 'const T' as 'this' argument of 'bool T::operator<(T)' discards qualifiers
#include <iostream> #include <vector> #include <algorithm> class MyData { public: int m_iData; bool operator<(MyData rhs) { return m_iData < rhs.m_iData; } }; int main () { std:: vector <MyData> myvector(2, MyData() ); myvector[0].m_iData=2; myvector[1].m_iData=4; std::sort(my...
The comparison operator will be called on a const-reference of a class instance, so it must be declared as a const member function. It is also good practice to pass the argument by const-reference rather than by value, although it doesn't make much of a difference for your simple class: bool operator<(const MyData & rh...
7,869,660
7,869,718
could not determine size if fclose not done twice
I'm made a File class that is a sort of wrapper of the FILE type and added some methods. This is the code of my file class : #include <Fs/File.h> File::File(Path& p): m_path(p), m_openned(false) { } int File::open(const string& mode) { m_f = new FILE; fopen(m_path, mode.c_str()); if (m...
In File::copyTo: if (ch == -1) return 0; you are jumping out of the function without properly closing the files. When the target file is not closed, it's contents is probably not sent to the OS, which later reports bogus filesize.
7,869,704
7,869,725
When should I use non-member operator overloading?
Should I be using non-member overload or member overload? How do I tell which I should use?
If you're thinking about something like operator< or swap, there's a rule of thumb ( though it's not terribly strict or mandatory): If the function only requires access to the public interface of your class, make it a free non-member function. Otherwise make it a member function. (Alternatively you may consider a frien...
7,869,716
7,869,869
Dereferencing a member pointer error: cannot be used as member pointer
I've got the following (truncated) class declaration: template <typename T> class btree { public: btree(const btree<T>& original); //This is btree's copy constructor private: struct btree_node { btree_node(const btree_node &other) { //This is ...
If you look at the precedence table you will see that first the . operator is evaluated and then the * (dereference) operator is evaluated. * takes a pointer as argument. If you write original.*headNode, it's meaningless. Somehow you are telling it to get the member *headNode of original, but *headNode is not a member ...
7,869,818
7,869,884
Getting started with FPGA development
I would like to get an FPGA development board with the goal to emulate a CD-ROM drive. My questions are: Is there any fpga that allows writing code in C/C++ and not VHDL? If you had to recommend a board , which one would that be ? Which book would you recommend to buy ? Is there anything else that i should know before...
A) Well directly writing C++ code does not make sense, however you can emulate a processor and write C/C++ to it. I have done this. I would recommend a starting kit from ALTERA don't buy something really expensive for starters. B) http://www.altera.com/products/devkits/altera/kit-cyc2-2C20N.html This is pretty nice f...
7,870,040
7,870,085
NULL vs throw and performance
I have a class: class Vector { public: element* get(int i); private: element* getIfExists(int i): }; get invokes getIfExists; if element exists, it is returned, if not, some action is performed. getIfExists can signal that some element i is not present either by throwing exception, or by returning NULL...
Its a matter of design, not performance. If its an exceptional situation -like in your get function- then throw an exception; or even better fire an assert since violation of a function precondition is a programming error. If its an expected case -like in your getIfExist function- then don't throw an exception. Regardi...
7,870,048
7,870,163
Matching CRTP in template class
lately I've been toying around with templates and stumbled upon the following problem. I am implementing the CRTP pattern like this: template<typename derived_t> struct protocol_object { ... }; struct data_object : public protocol_object<data_object> { ... }; I now would like to match instances of class proto...
This isn't related to CRTP. It's a general case of the following: Design a template function, such that all derived classes use a particular specialization. The issue is that T& value is an exact match for Derived&, while Base& is an inexact match. So we shall make the general form a worse match: struct conversion_...
7,870,141
7,870,171
C++ - Class members when Destructor is called during overwrite
im trying to understand the order of Constructor and Destructor calls when overwriting an object. My code is : class A { public: A(int n): x(n) { cout << "A(int " << n << ") called" << endl; } ~A( ) { cout << "~A( ) with A::x = " << x << endl; } private: int x; }; int main( ) { cout << "ente...
Why should it be 11? You reassign z to A(14), so it's 14 at the end. (After your edit: You also see the destructor of the temporary A(14) object that gets destroyed at the end of the assignment.)
7,870,154
17,652,567
Compile XCode Projects online
I'm using the mosync library for develop iPhone applications. It generates the Xcode project , now I need to compile it to make it run on a iphone. So for that I need a mac. do anybody know somewhere online to find online compiler which do that with a web based interface? --thanks in advance--
Its really a difficult ask, since apples terms of use on certificates stop people from doing this. But I got a paid solution for the same problem you mentioned which provides Xcode on Macintosh with latest updates. It just cost about 10$-20$ per month. Initially, you will get the trial offer too. If you like it, then y...
7,870,261
7,870,273
calling function whose name is class name itself?
I do not know what methodology they use since the code base is huge. It defined a class like this: class ABC { member_func(string c); }; main() { ABC("").member_func("this random string"); } What is the missing code that would enable us to call ABC("");? I did not see any object of that class created anywhere...
That simply constructs an object of type ABC, but doesn't initialize any permanent memory location with that object. I.e., the initialized object the call to the ABC constructor creates is a temporary, and is lost after the call since it is not constructed in a memory location that can be accessed after the call such ...
7,870,276
7,870,604
C++/Win32 enumerate windows belonging to my process & close them
I have a Windows app that houses a web browser (Internet explorer) embedded in it. The app can be closed from another process by means of IPC. It works just fine except the situation when the embedded web browser may be displaying a pop-up dialog window (say, during saving of contents). In that case my app crashes when...
OK, I guess I got it myself. Here's if someone is interested: #define SIZEOF(f) (sizeof(f) / sizeof(f[0])) typedef struct _ENUM_POPUPS_INFO{ DWORD dwProcID; HWND hThisWnd; int nNextHWNDIndex; HWND hFoundHWNDs[256]; }ENUM_POPUPS_INFO; void CloseAllOpenPopups(HWND hWnd, int dwmsWait) { //'hWnd' = our...
7,870,315
7,870,975
C++ Primer Plus this pointer example
Sorry for turning to here for such a basic question, but can someone just quickly clear this up for me? I'll then delete the thread so as not to cause noob clutter. In the following example from the C++ Primer Plus text, doesn't the & operator in the function declaration designate that the function returns a pointer t...
Yeah, that's confusing. C++ massively overloads every symbol, because there just aren't enough symbols on the keyboard. The ampersand & is used for two different meanings which are conceptually similar, but are actually completely different language features. Meaning 1: Reference type declaration. Append an ampersand t...
7,870,318
7,870,367
C++: is there a point to having a header file?
Possible Duplicate: C++ - What should go into an .h file? I know this is general, but I find it really annoying coding things twice, and would find it a lot easier if I didn't have to browse between two files (my .h and .cc) rather than just keep it all in one. So, what is the point in having a header file if most o...
C++ doesn't tell you where to put your code. Actually, in your case it might be better to use one file: struct VoterData { // raw data Voter::States state; bool vote; unsigned int numBlocked; // flags bool _hasState, _hasVote, _hasNumBlocked; // No getters, setters and other cruft needed }; ...
7,870,410
7,933,747
How to make a C macro pre-build pre-processor?
Let's say I have a string that I would like to obfuscate in my code. (This example is just for learning.) My plan is to wrap the string literal with a macro, e.g. #define MY_STRING "lol" const char *get_string() { return _MY_ENCRYPTION_MACRO(MY_STRING); } and, as a pre-build step, to run my source file through my own ...
If you used a recent GCC (i.e. GCC 4.6) on Linux, you could also have a plugin which provides a builtin function to "encrypt" compile time strings, or you could even make it a GCC MELT extension (MELT is a high-level domain specific language to extend GCC). If you use some other C++, you might have your own pre-process...
7,870,411
7,870,587
__restrict and shared_ptr hacks
Is the following safe? struct K { ... } struct A { A(int psize) : size(psize), foo(nullptr), bar(nullptr) { auto dataptr = (K*)_aligned_malloc(sizeof(K) * psize * 2, 32); data = shared_ptr<K>(dataptr, ptr_fun(_aligned_free)); foo = data.get(); bar = data.get() + psize; } ...
You don't need __restrict qualifiers here, and in fact you shouldn't use them, because __restrict is supposed to tell the compiler that you don't have any aliases to the same memory, but in fact you do have aliases -- foo and data are aliases to the same memory. I think the semantics of your code are fine, otherwise. Y...
7,870,426
7,891,534
How can I properly render faces from a 3ds file
I have implemented the ability to load 3DS files into an OpenGL program of mine, and run into a slight problem. All of the vertices are placed properly, and the faces are drawn, but the issue is that most(or all) of the vertices seem to retain a connection to one or two vertices, creating a large number of extra edges....
The fact that glBegin and glEnd are outside the loop is absolutely no problem. Drawing triangles using every vertex one after the other is just the correct way. It will build a triangle form every 3 consecutive vertices, which is what you want. Your problem was, that you increased tLoop inside the else block, and there...
7,870,429
7,873,633
A map-like container
I need a special container which is like a multimap of two types: T1 and T2: each "row" in the container contains a T1 and T2. The requirements I need from it are: Fast insertion of a row(T1 and T2), O(log n) in multimap which is ok. Fast query of all rows which contain T1, O(log n) in multimap which is ok. Fast remov...
Did you consider using a std::set ? Using your elements as a single composite key: Insertion and Deletion are covered as usual. Search is covered by a combination of lower_bound and upper_bound (both O(log N)) which works as you can define a minimum and maximum elements for your pair.
7,870,480
7,870,620
What method/algorithm/library can securely encrypt then decrypt
The following project is done in C++ with WinAPI, for encryption/encoding I am using CryptoC++ but I am open to better libraries. I need to encrypt/encode email data, transmit it, then decrypt it at the other end so privileged users can read the email. My original idea was just to encrypt the email text using SHA256 us...
As said by Captain Giraffe, a hash algorithm is not an encryption algorithm (though they are both counted in the area of symmetric cryptography). A good hash function has no way to recover a message which fits to the produced hash (other than trying all possible messages to see if they give the same hash). (And also, a...
7,870,498
7,870,614
using declaration in variadic template
This question is inspired in the following solution to multiple inheritance overloading pseudo-ambiguity, which is a nice way to implement lambda visitors for boost::variant as proposed in this answer: I want to do something like the following: template <typename ReturnType, typename... Lambdas> struct lambda_visitor :...
Ok i found out a pretty decent solution: basically i need to unpack one extra lambda case and apply the using clause to the unpacked lambda and the rest, but in this case, since i apparently i cannot make a variadic list of using declarations (at least i don't know the syntax, if its possible), the rest is wrapped by i...
7,870,506
7,873,998
OpenGL - Sweep Representations
I have a set of points, confined to a two dimensional coordinate plane, specifically the first and fourth quadrants (positive x values). I am able to draw a line through these points. I can also draw these points in 3D space, in another window, as a line. How would I go about sweeping them around an axis, say, Y, so t...
There are many ways to do this, but the overriding principle is to rotate the original line around some axis, and then emit vertices from the current line to the next line in order to generate triangles, remembering to "close" the shape by joining the last line with the first. Personally I would generate a vertex buffe...
7,870,533
7,870,925
C++ triangle rasterization
I'm trying to fix this triangle rasterizer, but cannot make it work correctly. For some reason it only draws half of the triangles. void DrawTriangle(Point2D p0, Point2D p1, Point2D p2) { Point2D Top, Middle, Bottom; bool MiddleIsLeft; if (p0.y < p1.y) // case: 1, 2, 5 { if (...
I kind of got lost in your implementation, but here's what I do (I have a slightly more complex version for arbitrary convex polygons, not just triangles) and I think apart from the Bresenham's algorithm it's very simple (actually the algorithm is simple too): #include <stddef.h> #include <limits.h> #include <stdlib.h>...
7,870,600
7,870,610
Boost::bind 'Call to empty boost::function' fails only if not set in constructor
Why might using the following fail unless called from the constructor of the class? updateState = boost::bind( &PhysicsObject::updateActive, this ); However the following fails at runtime, with a 'what(): call to empty boost::function' exception void PhysicsObject::setState( PhsyicsObjectState aState ) { _state =...
Calling a boost::function that wasn't set would raise such exception. You should initialize it in your constructor according to the default "state", otherwise your setState won't set it if passed a state same as the current. Note that in your second bind, you are passing a copy of the object pointed by this.
7,870,746
7,928,853
Creating a moveable and resizeable line in winforms
I want to create a program in which the user has an area where he can take lines which I provide him with (for example three lines) and adjust their sizes and locations to create a small diagram. How can I do that with winforms? What classes and properties should I use? Thanks a lot
I understand from your question, that you want to give users ability to adjust the size and locations ( similar to anchors in Powerpoint and several other products ) and let him/her draw a figure out of that. You need to use the graphics functions in that case, though some of your work like resizing might need usage of...
7,870,787
7,870,805
Can you cast a QReal digit to a float?
I have a QPointF, where it has .x() and .y() methods, which are qreal objects. Can these be cast to floats? How?
Yes, they can. On ARM platforms, they already are floats. Otherwise, it's a double. A static cast or a C-style cast will do it. http://doc.qt.io/qt-5/qtglobal.html#qreal-typedef
7,870,829
7,870,894
Header File error: expected '=', ',', ';', 'asm' or '__attribute__' before
I'm currently running a c++ project, with a class called Relation. I'm trying to compile it, but I constantly get this error, regardless of the file extension that I'm using. Compiler is cc, and the class I'm trying to compile, even when empty as below, causes this error. I've tried the c++ header extensions, and the s...
That's the error you get when you try to compile C++ code with the C compiler. pax$ cat qq.cpp class Relation { public: Relation(); virtual ~Relation(); }; pax$ g++ -c -o qq.o qq.cpp pax$ cp qq.cpp qq.c pax$ gcc -c -o qq.o qq.c qq.c:4: error: expected '=', ',', ';', 'asm' or '__attribute__' before 'Relation'...
7,870,851
7,876,496
Gprof results: what is "alloc_mmap"?
My results for a short run of my program are as follows: 67.93 3.24 3.24 grid::rKfour(int, int) 9.43 3.69 0.45 alloc_mmap 5.03 3.93 0.24 30001 0.01 0.01 grid::timeStep() 3.04 4.08 0.15 42007105 0.00 0....
I assume you're asking because you want to see what you could do to improve the program's speed. If not, forget this. In gprof output, the number that matters is the second column, cumulative seconds, because if that routine could be made to take no time, that is the amount by which your total time would shrink. One of...
7,870,897
7,876,109
Why some include files only reside in tr1?
When I try to include things like <unordered_map> it fails and says the file doesn't exist, while when I try to include <tr1/unordered_map> it works. however, the include files that are present also in c++03 are found, and are c++11 (like <vector> has move constructor). Also, headers that are only in c++11 and not in t...
TR1 (technical report 1) is not a standard, but merely a report. It is an official way of letting people know that the committee is interested in this area. Any tr1 implementation is an experimental release aimed at getting field feedback for the purpose of bettering a future standard. Using Apple's Xcode 4.2 you can...
7,871,172
7,881,692
Strange case of C++11 overload resolution
I came across a rather strange case of overload resolution today. I reduced it to the following: struct S { S(int, int = 0); }; class C { public: template <typename... Args> C(S, Args... args); C(const C&) = delete; }; int main() { C c({1, 2}); } I fully expected C c({1, 2}) to match the first c...
For C c({1, 2}); you have two constructors that can be used. So overload resolution takes place and looks what function to take C(S, Args...) C(const C&) Args will have been deduced to zero as you figured out. So the compiler compares constructing S against constructing a C temporary out of {1, 2}. Constructing S from...
7,871,212
7,871,320
C++11: what is the proper way to migrate from old-style enum to enum class?
I am currently migrating my code from the old-style enum to enum class. The strong-typing is nice, but I came across a point in the code where I needed to call ncurses's init_pair() function which takes a short int as its first argument, but which I have converted to an enum class for developer-friendly reading. To mak...
The cleanest way is probably to define an overloaded inline version of init_pair that takes an enum and casts it to call the normal version: inline int init_pair(enum_type pair, short f, short b) { return init_pair(static_cast<short>(pair), f, b); } That way users can call it with you enum type and it will just wo...
7,871,599
7,872,686
Reading till the end of a line in C++
I have a text file like this : Sting Another string 0 12 0 5 3 8 Sting Another string 8 13 2 0 6 11 And I want to count how many numbers are there. I think my best bet is to use while type cycle with a condition to end counting then another line starts but I do not know how to stop reading at the end of a line. ...
Split your input stream into lines std::string line; while (std::getline(input, line)) { // process each line here } To split a line into words, use a stringstream: std::istringstream linestream(line); // #include <sstream> std::string word; while (linestream >> word) { // process word } You can repeat this for e...
7,871,614
7,871,638
Why calling template member functions gives error?
template <class T> class Test{ public: Test(T){ } template <class U> U to() const{ return U(0); } }; template <class Real> class Base{ typedef Test<Real> TST; protected: Base(const TST& t){ _i = t.to<int>(); // <- but this gives error } int _i; }; template <class Real, class T> class Child;...
Because t is of type Test<Real> where Real is a template argument, so the type of t is actually a dependent type. You need to let the compiler know to is a template function by using: _i = t.template to<int>(); Otherwise you could be attempting to use the operator< on a member of t called to (causing some errors), whi...
7,871,691
7,871,732
STL container insert element
I was looking into std::set code. I see insert signature as _Pairib insert(const value_type& _Val). Why is the input parameter passed by reference? I know that standardcContainers copy their elements into memory of the container. Does anybody know how this is achieved? Where do allocators enter the picture? Any small ...
The allocator is a template parameter. Look at the definition here: template < class Key, class Compare = less<Key>, class Allocator = allocator<Key> > class set; If you don't specify allocator of your own, it will take the default allocator (which would probably be just a new). You can use STL containors o...
7,871,721
7,872,474
Tokenize a string excluding delimiters inside quotes
First let me say, I have gone thoroughly through all other solutions to this problem on SO, and although they are very similar, none fully solve my problem. I need a to extract all tokens excluding quotes (for the quoted ones) using boost regex. The regex I think I need to use is: sregex pattern = sregex::compile("\"(?...
I answered a very similar question here: How to make my split work only on one real line and be capable to skip quoted parts of string? The example code uses Boost Spirit supports quoted strings, partially quoted fields, user defined delimiters, escaped quotes supports many (diverse) output containers generically su...
7,871,959
7,872,584
STL Container insert element and memory perspective
This question is extension of the question I want to understand how the elements are inserted into the STL Container. Suppose I have A object;, which I want to insert into any of the STL Container, I understand that there is concept of allocators which handles the memory. But I fail to understand that how the actual o...
The approach is not that complicated. Basically the container will obtain memory from the allocator and then perform copy-construction (with placement-new over that memory). The easier container to see is vector: void push_back( T const & value ) { ensure_enough_capacity(); new (end_ptr++) T( value ); } Where en...
7,872,461
7,875,793
Can I instantiate matrix in Armadillo and then set it to use auxiliary memory in a later line of code?
I am using Armadillo with RcppArmadillo. Is it possible to declare a matrix with arma::mat A and then later assign some memory to this matrix that I have created before with arma::mat(aux_mem*, n_rows, n_cols, copy_aux_mem = true, strict = true) ? The intention is to create an Armadillo matrix from an Rcpp::NumericMatr...
Provided I understand what you are asking, the answer is probably yes. The boolean toggles at the end control whether new memory is allocated, or whether you re-use the existing object's memory. Not sure what you mean by "assign some memory to this matrix". See the Writing R Extensions manual on what you can and cannot...
7,872,537
8,089,734
CPU Affinity in Boost::Thread API
Is it possible to set CPU affinity in boost threads ((i.e. setting each thread to run on a different CPU)? Is there any tutorial/documentation you can suggest on this? Googling does not return much info except the following thread where the specified example (boost-bind_processor.v1.tar.gz) is no longer present in the ...
Just don't. Most of the time when you think this will help things, it just makes them worse. Every restriction you place on the system has a cost. The scheduler is very smart and the more restrictions you force on it, the worse it will perform. The scheduler will not move a thread from one core to another unless it ha...
7,872,578
7,877,659
How to properly use qRegisterMetaType on a class derived from QObject?
I've been searching far and wide for an answer to this but to no avail. My lament is as follows: I have a ClassA that roughly looks like this: class ClassA : public QObject { Q_OBJECT public: ClassA() { mName = "lol"; } ~ClassA(); void ShowName() { std::cout << mName << std::endl; } std::string mNam...
A few things: The reason that registering ClassA* isn't working is because your call to construct() is constructing a pointer to a ClassA object, but not an actual object. It is worthy of noting the following quote from the QMetaType documentation: Any class or struct that has a public default constructor, a public ...
7,872,701
7,872,764
Reading text files of unknown encoding in C++
What should I use to read text files for which I don't know their encoding (ASCII or Unicode)? Is there some class that auto-detects the encoding?
I can only give a negative answer here: There is no universally correct way to determine the encoding of a file. An ASCII file can be read as a ISO-8859-15 encoding, because ASCII is a subset. Even worse for other files may be valid in two different encodings having different meanings in both. So you need to get this i...
7,872,742
7,872,801
Typesafe callback system in modern C++
I'm working at a module that use a callback system that wasn't implemented very nice. The clients are registering with an ID and will be called back with a variable (or two, or none). The problem is that for almost every ID is a different variable. (Ex: Id1 -> char*, Id2 -> int). This is achieved by passing variable vi...
Your problem is not that of callbacks, but rather that you want to treat all callbacks as the same type, when they are not (the signatures are different). So either you do the nasty C void* trick or if you want to use a type-safe approach you will have to pay for it, and provide different methods to register the differ...
7,872,759
7,873,058
Complicated multi-argument #define macro for strings
I'm working on a project and have a problem that I believe can be solved with macros, but given the nature of the issue I don't have the experience to write one myself. Here's what I would expect as input and output of the #define macro: Inputting code such as this printf(foobar(Hello World.)); Should result in the pr...
The only solution I can think of is to run your code through a suitable script (probably just some light awk), that does the substitution before your code reaches the pre-compiler. Depending on your environment you could do this as a "Pre-Build Event" in Visual Studio, or just add a step directly into your makefile.
7,872,958
7,872,986
Implementing the same method signature from two 'interfaces'
Using pure virtual methods for faux-interfaces in C++, what happens when a concrete class derives from two 'interfaces' which have an identical method declaration? e.g X sub-classes Iaaa and Ibbb and implements a method virtual void setVisible(bool);. Does the fact Iaaa and Ibbb have no method body make things easier/b...
what happens when one class uses MI to derive from 2 classes which have identical signatures for a pure virtual method The behavior is well defined. The derived class overriding method will constitute implementation of both the interfaces (i.e. abstract classes with all pure virtual functions) methods. Also, 2 othe...
7,873,067
7,873,100
Good resource to practice C++ Arrays and Pointers
I'm learning C++ from book. I think I understand basic concept but the book provide not much exercise. I want to know website, opensource project or any resource that provice exercise or souce code that I can read and get my hand dirty with C++ Arrays and Pointers.
There is conceptually no difference between C and C++ when it comes to pointers and arrays.Practice K&R questions. They are good and comprehensive. The theory provided in it is good enough to get you started with complex logic related to pointers and arrays.
7,873,103
7,873,128
When I need to declare my own destructor?
If no user-defined destructor exists for a class and one is needed, the compiler implicitly declare a destructor. When I need to declare my own destructor?
When the implicitly declared destructor won't do what you need it to. This is somewhat involved. You should look up and research the rule of three.
7,873,313
7,873,371
Different behaviour between std deque/vector in MSVCC/g++/icc
I have this very simple piece of code; #include <deque> #include <vector> using namespace std; class A { public: A(){}; ~A(){}; deque<A> my_array; // vector<A> my_array; }; int main(void) { } If I compile this code with both g++ and icc/icpc on linux it compiles fine, even with -Wall it gives no warning...
It's undefined behavior (both with std::deque and with std::vector, so whatever an implementation does with it is fine, as far as the standard is concerned. You're instantiating a standard container with an incomplete type. When compiling with g++, -Wall (and in general, all options starting with -W) only concern the ...
7,873,536
7,873,557
Different results using atoi
Could someone explain why those calls are not returning the same expected result? unsigned int GetDigit(const string& s, unsigned int pos) { // Works as intended char c = s[pos]; return atoi(&c); // doesn't give expected results return atoi(&s[pos]); return atoi(&static_cast<char>(s...
None of your attempts are correct, including the "works as intended" one (it just happened to work by accident). For starters, atoi() requires a NUL-terminated string, which you are not providing. How about the following: unsigned int GetDigit(const string& s, unsigned int pos) { return s[pos] - '0'; } This assu...
7,873,728
7,873,762
Does a getter have zero cost?
I have a simple class: class A { public: int get() const; private: void do_something(); int value; } int A::get() const { return value; } The getter function is simple and straightforward. Getters are to use them, so in do_something I should use get() in order to access value. My question is:...
When the method is not virtual, compilers can optimize it. Good compilers (with link-time optimization) can optimize even if the method is not inline and defined in separate .cpp file. Not so good ones can only do that if it's declared inside the class definition, or in the header file with inline keyword. For virtual ...
7,873,803
7,875,505
Getting subset of QSet limited by non-existent elements
I need to store QSet[QTime] (or similar) data. The thing that i want to do is to get subset of elements in range , where A and B may not exist i.e. vector[int] 5 7 9 11 13 range ( 6, 11) => 7 9 11 Is it possible? Maybe there is better way of doing that? Thanks for advice
The obvious solution would be std::set<QTime>. It is ordered, and offers lower_bound and upper_bound methods. These do not require that the actual bounds are present in the set.
7,873,871
7,873,907
Which C++ operators can not be overloaded without friend function?
Which C++ operators can not be overloaded at all without friend function?
The operators where the left-hand-side operand is not the class itself. For example cout << somtething can be achieved via defining a std::ostream& operator<<(std::ostream& lhs, Something const & rhs); function, and marking them as friend inside the class. EDIT: Friending is not needed, ever. But it can make things sim...
7,873,989
7,879,015
C++ CRTP class hierarchy
From Wikipedia: // The Curiously Recurring Template Pattern (CRTP) template <typename T> struct base { // ... }; struct derived : base<derived> { // ... }; Now if I want derived_from_derived, I can write: // The Curiously Recurring Template Pattern (CRTP) template <typename T> struct base { // ... }; templ...
My own answer is this: struct base { template <typename T> struct type { // ... }; }; struct derived { template <typename T=derived> struct type : base::type<T> { // ... }; } struct derived_from_derived { template <typename T=derived_from_derived > struct type : ...