question_id int64 25 74.7M | answer_id int64 332 74.7M | title stringlengths 20 150 | question stringlengths 23 4.1k | answer stringlengths 20 4.1k |
|---|---|---|---|---|
5,524,027 | 5,527,612 | Store a file metadata in an extra file | I have a bunch of image files (mostly .jpg). I would like to store metadata about these files (e.g. dominant color, color distribution, maximum gradient flow field, interest points, ...). These data fields are not fixed and are not available in all images.
Right now I am storing the metadata for each file as a separate... | I thought long on this matter and went with ProtocolBuffer to store metadata for my images. For each image e.g. Image00012.jpg, I store the metadata in Image00012.jpg.pbmd. Once I have my .proto file setup, the Python class and C++ class got auto-generated. It works very well and require me to spend little time on pars... |
5,524,207 | 5,524,235 | How do I make a class assignable to primitives? Or, how do I make a scalar class? | I was wondering if it's possible to make my
class Time
{
public:
Time();
explicit
Time(
const double& d);
Time&
operator=(
const Time& time);
Time&
operator=(
const double& d);
};
assignable to the primitive double?
I'm... | You have to write/override an operator. In this case the cast-operator.
Define a method
operator double() { return double_however_computed_from_your_time; };
|
5,524,247 | 5,524,280 | Critical loop containing many "if" whose output is constant : How to save on condition tests? | I have a critical loop in my code with this shape :
int myloop(int a, .....){
/* some stuff */
// Critical loop
while(...){
/* Some Stuff */
if(a == 1){
// .....
}
else if(a == 2){
// .....
}
else if(a == 3){
// .....
}
els... | One common way of doing this is as follows:
// make function implementation inline...
static inline int myloop_inline(int a, .....){
/* some stuff */
// Critical loop
while(...){
/* Some Stuff */
if(a == 1){
// .....
}
else if(a == 2){
// .....
}
... |
5,524,744 | 5,524,838 | Typedef inside template class doesn't work | I have a problem with the following code:
template <typename U>
class lamePtr
{
public:
typedef U* ptr;
};
template <typename U>
class smarterPointer
{
public:
void funFun()
{
typedef lamePtr<U> someType;
someType::ptr query;
}
};
As you see, I have a typedef inside lamePtr. Inside... | someType, as lamePtr<U> is a "dependant name". It depends on what U is as to whether or not there is a member ptr and, if so, what kind of "thing" that member is.
Of course, you know that for all T, lamePtr<T>::ptr is a type, but at this stage of compilation the parser does not know that.
Use the typename keyword to hi... |
5,524,780 | 5,525,119 | I want to wait on both a file descriptor and a mutex, what's the recommended way to do this? | I would like to spawn off threads to perform certain tasks, and use a thread-safe queue to communicate with them. I would also like to be doing IO to a variety of file descriptors while I'm waiting.
What's the recommended way to accomplish this? Do I have to created an inter-thread pipe and write to it when the queue g... | Whenever one uses an event driven architecture, one is required to have a single mechanism to report event completion. On Linux, if one is using files, one is required to use something from the select or poll family meaning that one is stuck with using a pipe to initiate all none file related events.
Edit: Linux has e... |
5,524,809 | 5,525,286 | dynamic_cast to derived type fails, Why? | I'd like to have some help on an issue I face.
I'm using serialization (TinyXml to be precise) to save objects in a file and I have a problem on deserialization.
My objects contain pointers, which are not saved directly but instead the ID of the object pointed to is saved.
Every object I save derivate ASerializable, di... | Alright, thank you all for your time. I found the problem.
Everything was fine in my hierarchy, the problem was a vector that was being copied. The pointers it contained were then changing so my the ref_ptr of Reference was corrupted.
{enjoy}
|
5,525,005 | 5,525,028 | Cross platform, open source, console GUI | What would be the best, most portable, simplest way to create a GUI-like feeling in the command line?
Basically I'm asking for a library that allows you to change background and text colors, have a text input area on the bottom of the console, and be able to edit a certain area in the command line without having to cle... | You could use ncurses
|
5,525,162 | 5,525,231 | How to embed Node.js interpreter into C/C++? | I want to use Node.js scripts in my C/C++ applications. Some people suggested me to start with v8, libev and libeio; but it means rewriting Node.js from scratch.
So, is it possible to embed Node.js into C or C++?
| It probably is, V8 is written in C++, node.js can run on V8, but unless you have an extremely good reason why you would run javascript through C++ you are probably much better served finding an appropriate C++ library and implementing the needed functionality directly in C++. The task of integrating scripting languages... |
5,525,262 | 5,525,277 | C++ templates, problem with object allocated both "static" and "dynamic" | What is wrong in this code?
template <typename T>
class Sample
{
public:
T first;
T second;
typedef T Type;
};
and
template <typename Item>
class Process
{
public:
void process (Item *item)
{
typename Item::Type var = item->first + item->second;
//Some code...
}
};
The met... | Process <Item>::process() expects a Item*, so Process <Sample <double> *>::process() expects a Sample <double>**.
The solution is much easier, however:
Sample <double> *s = new Sample <double>();
Process <Sample <double> > a;
a.process(s);
For Process, it doesn't matter at all how the object was allocated, all it gets... |
5,525,289 | 5,526,004 | Getting the amplitude(or rms voltage) of audio signal captured in C++ by wavin lib.? | I am working on a very basic robotics project, and wish to implement voice recognition in it.
i know its a complex thing but i wish to do it for only 3 or 4 commands(or words).
i know that using wavin i can record audio. but i wish to do real-time amplitude analysis on the audio signal, how can that be done, the wave w... | There is no simple way to recognize words, because they are basically a sequence of phonemes which can vary in time and frequency.
Classical isolated word recognition systems use signal MFCC (cepstral coefficients) as input data, and try to recognize patterns using HMM (hidden markov models) or DTW (dynamic time warpin... |
5,525,470 | 5,526,638 | Interact with websites C++ | How do I interact with websites in C++?
For example, a website has a dropbox, text area and a button, and I want my program to fill text inside the text area, choose an option from the dropbox, and make the button fire its event("clicking" it).
How can I achieve something like that?
thanks!
| First you have to understand that on the server there is no text box or button.
These are constructs that are built by the browser to display to you.
The browser will then take user input into the text box and interprets the clicks on the button. What happens (usually) when the button is clicked is that the browser sen... |
5,525,510 | 5,525,546 | How do you do change from one variable to another? | I have a few questions:
How do you get a certain char from a string?
How do you get a char to a int?
How do you get a int to a char?
How do you append a char to a string?
I was just making a simple keyed cipher... just playing around to learn cpp. I do know java so if you could relate to that it would be great!
Here ... |
How do you get a certain char from a string?
By using index operator. string::operator[]
How do you get a char to a int?
int charToInteger = stringName[i] ;
How do you append a char to a string?
Using string::append
From the link -
string& append ( size_t n, char c );
Appends a string formed by the repetition... |
5,525,587 | 5,525,623 | C++0x decltype and the scope resolution operator | With a class such as Foo:
struct Foo { static const int i = 9; };
I find that GCC 4.5 will reject the following
Foo f;
int x = decltype(f)::i;
It will work if I use an intermediate typedef, such as:
typedef decltype(f) ftype;
int x = ftype::i;
but I prefer to keep the namespace clean. I thought precedence may be an ... | It is valid C++0x to say decltype(f)::i. GCC just doesn't support it yet. You can work it around with an identity template
template<typename T> struct identity { typedef T type; };
int x = identity<decltype(f)>::type::i;
identity is part of the boost::mpl namespace.
|
5,525,615 | 5,525,807 | C++ templates, problem with object allocated both "static" and "dynamic" 2 | My second question today is similar to the first one. What is wrong in this code?
#include <vector>
template <typename Item>
struct TItemsList
{
typedef std::vector <Item> Type;
};
Container of objects:
template <typename Item>
class Container
{
protected:
typename TItemsList <Item>::Type items;
p... | Error 1 error C2825: 'Item': must be a class or namespace when followed by '::
Here Item = 'Sample *' => This is a pointer, whatever what it target, pointer remain a plain old integer that contain an memory address, and has no attribute like Type.
Something like that should do the trick
template <typename T>
struc... |
5,525,625 | 5,525,721 | How to resolve ambiguous operator in ISO C++ | I'm pretty much out of ideas now with porting a big bunch of old C++ code from MS Visual C++ 7.0 to iOS 4 iPhone g++ 4.2.1 compiler. I get some ambiquity errors compiling this:
complex_d* cp;
complex_d qSt;
double zi;
// complex_d += complex_d * double
*cp += qSt * dVal; // ISO C++ says that these are ambiguo... | I see two ways to fix this (there's probably more):
Add explicit to the constructor:
explicit complex_d(double re = 0, double im = 0);
Remove the friend operator*().
The C++ std::lib went with solution #2 for std::complex.
|
5,525,629 | 5,525,776 | C++ - Memory leaks: where is the pointer (meta) information stored? | This is a basic question of which I can't find any answer.
Given the next code, a memory leak will occur:
int main(){
A* a = new A();
// 1
}
//2
Lets say that a got the value 1000. That is, the address 1000 on the heap is now taken by an A object. On 1, a == 1000 and on 2 a is out of ... | Typically new and delete operators are implemented on top of malloc and free, though this detail is unspecified. malloc and free both point to a data structure which tracks which regions of memory are allocated, which are not, and how big each region is. Knuth's Art of Computer Programming Vol 1 has a pretty good des... |
5,525,637 | 5,525,645 | Create and use a header in C++ | I've got three files, add.h, add.cpp and test.cpp
add.h creates a header for a class, and is nothing but skeletons for implementation later.
add.cpp contains the actual code for the class listed in add.h
test.cpp contains the main method and declares an instance of the class in add and uses some of its methods.
Howeve... | Compile each file separately, then link:
g++ -Wall -c test.cpp
g++ -Wall -c add.cpp
g++ -o test test.o add.o
Or compile and link all files in one command:
g++ -Wall -o test test.cpp add.cpp
|
5,525,668 | 5,525,712 | How to implement readlink to find the path | Using the readlink function used as a solution to How do I find the location of the executable in C?, how would I get the path into a char array? Also, what do the variables buf and bufsize represent and how do I initialize them?
EDIT: I am trying to get the path of the currently running program, just like the questi... | This Use the readlink() function properly for the correct uses of the readlink function.
If you have your path in a std::string, you could do something like this:
#include <unistd.h>
#include <limits.h>
std::string do_readlink(std::string const& path) {
char buff[PATH_MAX];
ssize_t len = ::readlink(path.c_str(... |
5,525,679 | 5,525,735 | Change startup form under Visual Studio 2010 Professional for C++ Windows Form Application | For some reason, I can't seem to find a way to do this: changing the start up form for C++ Windows Application under Visual Studio Professional 2010. As many websites have suggested that go into Project\properties\Application\startup from etc. My problem was that I could not find the "Application" or Startup Form an... | You are using the C++ IDE, it doesn't have these kind of goodies. You are supposed to change the code yourself. Double-click the .cpp file that has the same name as your project in the Solution Explorer window. Locate the main() function and change the Application.Run() call:
// Create the main window and run it
App... |
5,525,683 | 5,527,178 | QT: picture as window | I want to make window frame using some picture. Window shouldn't have borders, titlebars, etc. It also should be hidden from active windows list (in taskbar).
Second part of question I did with:
this->setAttribute(Qt::WA_NoSystemBackground);
this->setAttribute(Qt::WA_QuitOnClose);
this->setAutoFillBackground(true);
t... | regarding the first part of the question, you, probably, looking for smth like this:
void MainWindow::paintEvent(QPaintEvent * event)
{
QPainter painter(this);
QPixmap pixmap = QPixmap();
pixmap.load("/home/my_image.jpg");
painter.drawPixmap(event->rect(), pixmap);
}
as an alternative you can create ... |
5,525,742 | 5,525,846 | Specialize a class template within a class template? | The definition below is failing... I'm thinking it has something to do with specializing a class template (Vector) within another class template (Graph). Thanks!
this is the part giving me trouble (defined in Graph below) ->
std::map<KeyType, Vertex<KeyType, ObjectType> > vertexes;
template <class KeyType, class Obje... | Your vertex is a pointer. To access getKey you need to use -> operator, not .. Plus, you can use std::make_pair to avoid repeating the types.
vertexes.insert(std::make_pair(vertex->getKey(), *vertex));
|
5,526,005 | 5,526,114 | Pong physics problem | I have problem but I don't know how to describe it so I have drawn it.
As you can see ball bounces when collision is detected. Nevermind the angle - I have just drawn it that way.
But sometimes ball goes through the paddle leaving it other way.
Why that happens ? Becase when I detect the collision I change vx to -vx. ... | This is quite a common problem for people writing pong clones. The solution is to, upon detecting a collision, not only reverse the velocity but also alter the ball position so that it doesn't intersect the paddle.
Otherwise it is possible for the ball to become stuck inside the paddle, constantly negating vx = -vx =... |
5,526,019 | 5,526,052 | Compile Errors - std::set with const members | I can't for the life of me figure out what's wrong with this code:
ClassA & doSomething (std::set<boost::shared_ptr<ClassB const> const > const & someSet)
{
std::set<boost::shared_ptr<ClassB> > secondSet;
for (std::set<boost::shared_ptr<ClassB const> const >::const_iterator it = someSet.begin(); it != someSet.end()... |
but that mean I won't be able to enforce const-correctness in my code
I think you may be wrong there. As long it is a smart pointer to a const object, you may only manipulate the pointers in the set, not the objects referred to. This is kind of the whole point, because a set cannot organize itself if it cannot touch ... |
5,526,373 | 5,531,081 | Code::Blocks cannot find vector header | EDIT: I have solved this problem, with Tomalak's help. It appears that I mistakenly uninstalled libstdc++6-4.4-dev_4.4.3 when I was making space to install code::blocks into, thus removing the STL headers. Code::Blocks now works perfectly fine.
Hey everyone, I'm back yet again to bug you.
I have recently installed Cod... | As it turns out, it was not a Code::Blocks issue - I had mistakenly un-installed the libstdc++6-4.4-dev_4.4.3 package.
So, if any of you all get this same problem make sure the libstdc++ development files are installed! LOL
|
5,526,415 | 5,526,446 | Trouble passing an array of structs | I cant for the life of me figure out how to pass this array of structs throughout my program. Could anyone lend a hand? Right now i am getting an error in main that says: expected primary expression before ')' token.
Header:
#ifndef HEADER_H_INCLUDED
#define HEADER_H_INCLUDED
#include <iostream>
#include <fstream>
#... | Where you have:
struct arrayOfStructs;
You need:
struct contactType arrayOfStructs[200]; // assuming you want 200 structs
|
5,526,506 | 5,526,529 | C++ public constructor address | After writing the code below:
#include <iostream>
using namespace std;
typedef struct Node {
int value;
Node(int index) {
value = index;
}
} Node;
int main() {
Node* arr[10];
for(int i = 0; i < 10; i++) {
arr[i] = &Node(i);
}
for(int i = 0; i < 10; i++)
cout << ar... | This line: arr[i] = &Node(i); is storing a pointer to a temporary object. Node(i) creates a temporary object that can be destructed at the end of the statement, at which point all references to it become invalid meaning the results of any code that dereferences arr[i] will be undefined. The reason in this case you get ... |
5,526,570 | 5,526,722 | How to pass PWCHAR to C++ dll from C# | I have an dll written in C++, and I want to call it from C#. The function outputs outputChar and deadChar, the deadChar variable is also read by the C++ function.
I tried to call function from C# in different ways, but all time I got AccessViolationException: "Attempted to read or write protected memory. This is often ... | Note: The two PWCHAR arguments to your function convertVirtualKeyToWChar are ambiguous. They could be pointers to a single WCHAR or pointers to aWCHAR string. Given the name of the function and arguments, this answer assumes they are pointers to a single WCHAR.
You want to use the following:
[DllImport("keylib.dll"... |
5,526,583 | 5,526,619 | Timers in Abstract Gui API | Here is the basic idea of what I want to do:
Each widget, when part of the Gui has access to the event manager. The event manager is polymorphic so it contains functions from the underlying graphics / timer api. What I want to do is, allow Widgets to register timers, where they would call a function which would interna... | Event management and providing timing facilities are 2 very different functionalities, so I would try to decouple event manager into 2 separate classes. Then you could make TimerManager a singleton and register timers from any places you like.
Alternatively if you cannot decouple event manager class as it is now, you ... |
5,526,649 | 5,526,675 | Breakpoint in a particular case | Recently I coded up a function that wasn't working properly. I managed to find out what was wrong and fix it in a roundabout manner but I was wondering if there was an easier way. The function (stripped down) is something like this:
int func(int param)
{
if(param == 0) return SOMETHING;
//...
for(int i = 0;i < 4;... | In Visual Studio, you can right-click the breakpoint and modify it in all kinds of ways.
Under Condition... you can specifiy your condition, like param == 10. You can even use simple C library functions for string comparision strcmp(mystr,"hi") == 0!
|
5,526,888 | 5,526,921 | Comparison operator == is not working, how do I make it work? [cpp] | I am getting the following error:
C:\Users\*******\Documents\CodeBlocksProjects\encryptText\main.cpp||In function 'int main()':|
C:\Users\*******\Documents\CodeBlocksProjects\encryptText\main.cpp|14|error: no match for 'operator==' in 'givenText == 1'|
C:\Users\*******\Documents\CodeBlocksProjects\encryptText\main.cpp|... | There's no implicit type conversion for your string, so you either needed to:
a) change your test to compare strings: if (givenText == "1")
or
b) parse your givenText to an integer before comparing: if (atoi(givenText.c_str()) == 1)
Have fun!
|
5,527,063 | 5,529,998 | "Extern" with DirectX variables? | For some reason, whenever I declare a directx variable as extern, I receive a linking error.
Example:
In some header file:
extern ID3D10EffectMatrixVariable* pWorldVariable;
In some other cpp file where I include the .h file containing pd3dDevice:
pWorldVariable = NULL;
An error similar to this will pop up:
2>main.o... | The issue I was running across was a matter of not understanding extern declaration vs. definition. This answer helps, but you have to read the whole thing and then do some research to understand it:
What is the difference between a definition and a declaration?
|
5,527,091 | 5,529,100 | runtime_error was not declared in this scope for g++ 4.1.2 | The same code is working fine on gcc 4.5.2 but when trying to compile it on gcc 4.1.2, I get the error ‘runtime_error’ was not declared in this scope.
I do have
#include <stdexcept>
Is this a problem with gcc 4.1.2?
Code excerpt
// Constructor
if (resource cannot be acquired)
throw std::runtime_error("Blah Blah");
| Visual Studio says that runtime_error should be defined in <stdexcept>, so I'm guessing that GCC 4.1.2 is just out of date here.
|
5,527,226 | 5,527,256 | How to parse comma delimited integers from a string in c++ | I have a function recieving a string, which is a pair of comma delimited integers in a fashion such as "12,4". How can I parse the integers out of this string?
| Depends whether or not you can depend on the incoming data being valid. If you can, I'd do:
#include <cstdlib>
#include <utility>
#include <string>
std::pair<int, int> split(std::string const& str)
{
int const a = std::atoi(str.c_str());
int const b = std::atoi(str.c_str() + str.find(',') + 1);
return std:... |
5,527,260 | 5,527,298 | Why is the compiler giving me an error on my set_intersection? | I have a class which has two attributes :
set< int > ens1_;
set< int > ens2_;
Now, I have a method which finds the intersection between these two sets. Here is what I wrote in my method:
set< int > ens;
set< int >::iterator it;
it = set_intersection(ensEntier1_.begin(), ensEntier1_.end(), ensEntier2_.begin(), ensEn... | The 5th argument to the set_intersection overload you're calling expects an output iterator; ens.begin() does not return an output iterator. Try this instead:
set<int> ens;
set_intersection(
ens1_.begin(),
ens1_.end(),
ens2_.begin(),
ens2_.end(),
inserter(ens, ens.end())
);
return ens;
Note: make s... |
5,527,540 | 5,527,671 | conditionally testing for equality of vector's elements | Although it seems pretty simple, I'm not sure of the most efficient way of doing this.
I have two vectors:
std::vector<bool> a;
std::vector<int> b;
a.size() necessarily equals b.size().
each bool in a corresponds to an int in b. I want to create a function:
bool test(std::vector<bool> a, std::vector<int> b);
This fun... | Your solution looks good enough to me:
Each loop does a different thing anyway (so you shouldn't worry about duplication)
You don't use extranious variables or flags that complicate the code.
The only problems I see are:
You start the second loop at 0 instead of where you left off.
Doing if(condition == true) is ver... |
5,527,665 | 5,527,669 | Why am I getting string does not name a type Error? | game.cpp
#include <iostream>
#include <string>
#include <sstream>
#include "game.h"
#include "board.h"
#include "piece.h"
using namespace std;
game.h
#ifndef GAME_H
#define GAME_H
#include <string>
class Game
{
private:
string white;
string black;
string title;
public:
Game(is... | Your using declaration is in game.cpp, not game.h where you actually declare string variables. You intended to put using namespace std; into the header, above the lines that use string, which would let those lines find the string type defined in the std namespace.
As others have pointed out, this is not good practice i... |
5,527,748 | 5,527,794 | Template syntax question regarding member variable offsets | I'm using Luabind to integrate LUA into one of my projects, and the following thing struck me as odd (I'm a self taught beginner)
template <class C, class D, class GetPolicies, class SetPolicies>
class_& def_readwrite(
const char* name
, D C::*mem_ptr
, GetPolicies const& get_p... | if you substitute D and C with actual types, it makes sense:
struct Test{
int member;
};
typedef int Test::*memptr;
// ^^^ ^^^^
// D C
memptr p = &X::member;
|
5,527,793 | 5,527,939 | How do I avoid including the headers of every class that needs to be BOOST serialised? | I have the following situation (simplified):
a.h:
#include <boost/serialisation/serialisation.hpp>
class B;
using namespace std; using namespace boost;
class A {
B *b;
template<class Archive> void serialize(Archive & ar, const unsigned int version) { ar & b; }
};
b.h:
#include <boost/serialisation/serialisation.... | I think you could use explicit instantiation, and then define your serialize member functions in .cpp files. Then a.cpp can include b.h and c.h as needed, and users of a.h don't need to do that anymore.
Look into the pimpl-idiom examples http://www.boost.org/doc/libs/1_46_1/libs/serialization/example/demo_pimpl_A.hpp (... |
5,527,908 | 5,527,963 | Qt How to open QDialog when main application done fully to load all widgets | Hello all
I have main windows application and I like to popup dialog for settings when the application (the qMainWindow)
Is fully loaded ? I tried to just in the main window constructor:
SettingsDialog settingsDialog;
settingsDialog.exec();
but when I start my application I see the QDialog and the main window minimi... | Use QTimer::singleShot with zero time interval it will call specified slot from the event loop when constructor and show() have been completed. Here is an example:
#include <QtCore/QTimer>
#include <QtGui/QApplication>
#include <QtGui/QDialog>
#include <QtGui/QMainWindow>
class MW : public QMainWindow
{
Q_OBJECT
pub... |
5,528,053 | 5,528,085 | Issue with string to int conversion in C++ | I have an application where I get a vector<string>. I need to iterate through each element in the vector and see if a value is an integer value.
Although the vector represents strings, few of the elements can contain an integer. I need to figure out which of those elements are integers, and if an element is an integer,... | Just go through your string and check every character if it's an integer. If not, break out and report false.
bool IsDigit(char c){
return '0' <= c && c <= '9';
}
bool IsInteger(std::string const& str){
size_t i = 0;
if(*str == '-') ++i;
for( ; i < str.size(); ++i){
if(!IsDigit(str[i]))
return fals... |
5,528,096 | 5,528,100 | C++ When template argument deduction fails | Why can't C++ determine that I intend to create a unique_ptr<A> with this syntax? (a has previously been declared as unique_ptr<A>)
a = unique_ptr(new A());
It seems awfully redundant to have to include <A>. This works for most functions templates I use, why not unique_ptr?
EDIT: C++ now supports make_unique, with n... | std::unique_ptr is a class template, not a function template. Argument deduction only happens for function templates, not class templates.
A commonly used trick is to write a function template that creates an object of the instantiated class template type, for example:
template <typename T>
std::unique_ptr<T> make_u... |
5,528,177 | 5,528,246 | Boost - shared_mutex has to be same instance? | I want to use shared_mutex with shared/unique locks for read/write.
Now if I have 2 objects and i want them to use the same lock, can I assign the value of the first mutex to the second mutex ?
Or do I have to work create a pointer to the shared_mutex and then have them both point to the same object instance?
I mean, w... | This will not work correctly. shared_mutex derives from boost::noncopyable. What you want to use instead is a pointer or reference to the mutex.
|
5,528,207 | 5,537,654 | thread safe streams and stream manipulators | I am trying to write a thread safe logger class so that i can do the exact same as with cout but with thread safety.
here is the logger class (still working on the type of lock required)
class logger {
public:
logger(LOGGER::output_type type);
logger(const logger& orig);
virtual ~logger();
template... | After digging into iostreams and with hints from Bo Persson, I think i found a better solutions since I dont need to write a function each for each ios manipulator. So here it is
logger& operator<<(std::ostream& (*pf)(std::ostream&)) {
(*out)<<pf;
return *this;
}
For an explanation search for i... |
5,528,351 | 5,528,360 | How I can generate different random numbers in one moment in c++? | How I can generate different random numbers in one moment in c++?
Now I use
while ( flag )
{
....
srand( time( NULL) );
int rndSig = rand() % 10 + 1;
......
}
But at one moment all numbers are equal. How I can generate different numbers in while loop?
| Move the srand outside of the while loop. You only need to call it once, rand() keeps static state.
|
5,528,517 | 5,529,800 | Getting around Boost Multi-Index container's constant elements | I have some data class which is expensive to copy, but must be mutable, as it is frequently updated according to events. I also need a multi-index container to hold many such classes. I'm trying to set it up using boost::multi_index. For example:
struct MutableAndExpensiveToCopy {
int some_value;
std::map<int, ... | First of all, ImMutableAndExpensiveToCopy seems precisely to be the opposite --mutable, since you're trying to change its contents in the example. Try simply this:
struct CanBeMultiIndexed
{
mutable ImMutableAndExpensiveToCopy data;
int id;
std::string label;
}
(and possibly change the name ImMutab... |
5,528,569 | 5,528,586 | repeated calling - coding practice | which one do you prefer? (of course getSize doesn't make any complicated counting, just returning member value)
void method1(Object & o)
{
int size = o.getSize();
someAction(size);
someOtherAction(size);
}
or
void method2(Object & o)
{
someAction(o.getSize());
someOtherAction(o.getSize());
}
I kn... | I would go for method 1 not just because it's probably marginally faster, but mostly because it means I don't have to worry about whether the called method has any side effects.
Also, if this is called in a multi-threaded program this ensures that I'm always using my value of size - otherwise it might have changed betw... |
5,528,712 | 5,531,233 | h.264 bytestream parsing | The input data is a byte array which represents a h.264 frame. The frame consists of a single slice (not multislice frame).
So, as I understood I can cope with this frame as with slice. The slice has header, and slice data - macroblocks, each macroblock with its own header.
So I have to parse that byte array to extrac... | The H.264 Standard is a bit hard to read, so here are some tips.
Read Annex B; make sure your input starts with a start code
Read section 9.1: you will need it for all of the following
Slice header is described in section 7.3.3
"Frame number" is not encoded explicitly in the slice header; frame_num is close to what yo... |
5,528,754 | 5,528,771 | What is the best way to add a header to a large file | What 's the best way to add a header (e.g. file metadata) to an existing file if the file size is around 1-2GB?
in C++
| The best way is to simply write the header to a new file, then append the contents of the old.
C++ doesn't provide a way to insert at the start of an existing file so that's really the best bet. Just make sure you read large enough chunks from the old file and append them to the new one. While buffering will alleviate ... |
5,528,809 | 5,528,856 | *iterator causes segfault | I'm trying to walk through a list. Here are some declarations:
list<CG1_Edge*> ActiveEdges;
list<CG1_Edge*>::iterator ActiveEdgeIterator;
Sometimes, this code segfaults on line 2:
for (this->ActiveEdgeIterator = this->ActiveEdges.begin(); this->ActiveEdgeIterator != this->ActiveEdges.end(); ++this->ActiveEdgeIterator)... | You should use something like:
for (this->ActiveEdgeIterator = this->ActiveEdges.begin(); this->ActiveEdgeIterator != this->ActiveEdges.end(); ) {
CG1_Edge* currentEdge = *this->ActiveEdgeIterator;
if (currentEdge->y_up < y)
this->ActiveEdgeIterator = this->ActiveEdges.erase(this->ActiveEdgeIterator);
... |
5,528,840 | 5,528,870 | What does operator << do in this line? | I can not understand what this line does:
fBuffer[fByteIndex] += 1 << (fBitIndex - 1);
where:
unsigned char fBuffer[32];
int fBitIndex;
and:
for ( int i = 0; i < 32; i++ )
fBuffer[i] = 0;
fBitIndex = 8;
What << does there?
| << is the left-shift operator, and assuming fBitIndex is 8 the code
fBuffer[fByteIndex] += 1 << (fBitIndex - 1);
is equivalent to
fBuffer[fByteIndex] += 128;
Why? Because a left-shift means you shift the bits of the value "left"; in your case, 00000001 (1), is shifted left 7 times, becoming 10000000 (128).
|
5,528,998 | 5,529,875 | OpenMP threads appear to execute serially | I have an application which should essentially evaluate the reverse polish notation of a mathematical expression in parallel may times. My problem is i'm not seeing any gain in performance when using OpenMP. (Im using VS2008, the /openmp compiler option is set.)
My main loop looks like this:
int nMaxThreads = std::min(... | Classic Heisenberg, observing a thread affects its behavior. The printf() function is slow, surely much slower then your expression evaluator. And has to acquire a lock to prevent the characters in the string from getting intermingled with console output requested by other threads. The odds that more than one thread... |
5,529,066 | 5,529,248 | Store pointer to istream and ostream in a class C++ | game.h
#ifndef GAME_H
#define GAME_H
#include <string>
#include <iostream>
#include "piece.h"
using namespace std;
class Game
{
private:
string white;
string black;
string title;
istream* in;
ostream* out;
public:
Game();
Game(istream&, ostream&);
... | You simply want a reference variable, not a pointer.
class Game
{
private:
...
istream& in;
ostream& out;
public:
Game(istream&, ostream&);
};
Game::Game(istream& is, ostream& os)
: in( is ),
out( os )
{ }
The existing code compiles because of a couple language qu... |
5,529,067 | 5,563,376 | C++ - Appending one Vector to another, with removal of duplicates? | I'd like to append one vector (vectorAlpha) to the end of another vector (vectorBeta). There's two different approaches I could think of, and I'd like to know how to do each one.
The first approach was to append the second vector and remove all duplicate items from the new vector. The other approach is to leave duplica... | Since it became clear that
you only wanted duplicates remove entries from vecB if they existed in vecA, not duplicates in general
you wanted to preserve the ordering
The answer should (obviously?) be std::remove_copy_if. Call it thusly:
#include <vector>
#include <algorithm>
typedef std::vector<int> Vec;
struct Cont... |
5,529,134 | 5,529,165 | Object Oriented question | I recently gave in a piece of coursework and my teacher said that my approach is wrong and I got marks taken off. I would appreciate it if someone could tell me what I did wrong and how I can fix this.. (ignore the syntax but the idea is there, this was in objective c but I guess the same principle would apply)
main c... | The problem is that the assignment that was given to you is of a functional nature.
Naturally, your solution steered towards a functional solution and away from artificial object-orientation that was required on top.
You could put the solution in a "true" object-oriented garment like your teacher requires (putting vari... |
5,529,155 | 5,529,193 | Cannot specialize struct | Why this doesn't work?
template <class T>
struct Low;
template <>
struct Low<int> {};//Here I'm trying to specialize for int
int main()
{
Low<1> a;
}
| Low<int> a; will work - Your template takes a type not an integral argument.
|
5,529,212 | 5,529,589 | CUDA cufftPlan2d plan size question | I'm studying the code behind the convolutionFFT2D example of the Nvidia CUDA sdk, but I don't get the point of this line:
cufftPlan2d(&fftPlan, fftH, fftW/2, CUFFT_C2C);
Apparently this initializes a complex plane for the FFT to be running in, but I don't see the point of dividing the plan width by 2.
Just to be preci... | When you perform a real to complex FFT half the frequency domain data is redundant due to symmetry. This is only the case in one axis of a 2D FFT though. You can think of a 2D FFT as two 1D FFT operations, the first operates on all the rows, and for a real valued image this will give you complex row values. In the seco... |
5,529,263 | 5,529,958 | Qt QSettings try to create ini file but none created why? | Im trying to create ini file that will hold me the configuration data, I have singletone class
that setting the QSettings object like this :
... #DEFINE CONFIG_FILE_NAME "myconfig.ini"
m_pSettings = new QSettings(QDir::currentPath()+"/"+CONFIG_FILE_NAME,QSettings::IniFormat);
this is accourding the document, but when... | I believe in order to force QSettings file to appear you would need to set at least one value in it and then call sync() method. See if an example below would work for you:
QSettings* settings = new QSettings(QDir::currentPath() + "/my_config_file.ini", QSettings::IniFormat);
settings->setValue("test", "value");
settin... |
5,529,295 | 5,530,453 | C++ vs. D , Ada and Eiffel (horrible error messages with templates) | One of the problems of C++ are horrible error messages that we are getting from code which intensively uses templates and template metaprogramming. The concepts are designed to solve this problem, but unfortunately they will not be in the next standard.
I'm wondering, is this problem common for all languages, which ar... | The problem, at heart, is that error recovery is difficult, whatever the context.
And when you factor in C and C++ horrid grammars, you can only wonder that error messages are not worse than that! I am afraid that the C grammar has been designed by people who didn't have a clue about the essential properties of a gramm... |
5,529,382 | 5,529,468 | move semantics std::move | I don't understand very well the std::move function
template <class T>
typename remove_reference<T>::type&&
move(T&& a)
{
return a;
}
why remove_reference ?
could someone give me a simple explanation ?
| Think about what happens if T is an lvalue reference, for example MyClass &. In that case, T && would become MyClass & &&, and due to reference collapsing rules, this would be transformed into MyClass & again. To achieve the right result, typename remove_reference<MyClass&>::type&& first removes any reference decoratio... |
5,529,443 | 5,529,458 | What is >>> operation in C++ | In this blog post the author has suggested the following as the bug fix:
int mid = (low + high) >>> 1;
Does anyone know what is this >>> operator? Certainly its not there on the following operator reference list:
http://msdn.microsoft.com/en-us/library/x04xhy0h%28v=vs.71%29.aspx
http://www.cplusplus.com/doc/tutorial... | >>> is not a part of C++. The blog contains code in Java.
Check out Java online tutorial here on Bitwise shift operators. It says
The unsigned right shift operator ">>>" shifts a zero into the leftmost position, while the leftmost position after ">>" depends on sign extension.
|
5,529,881 | 5,529,970 | move semantics std::move how use it | #include <type_traits>
template<class T>
typename std::remove_reference<T>::type&& move(T&& v)
{
return v;
}
void main()
{
int a;
move(a);
}
Why doesn't this code compile?
error C2440: 'return' : impossible to convert 'int' in 'int &&'
| This is straight out of the C++0x draft standard (§20.2.3/6):
template <class T> typename remove_reference<T>::type&& move(T&& t) noexcept;
Returns: static_cast<typename remove_reference<T>::type&&>(t).
Consequently, if you change your move implementation to the following, it works just fine:
template<class T>
typena... |
5,529,888 | 5,529,952 | Is string::size_type really big enough to hold any string? | I browsed through some threads about string::size_type here and I do understand according to C++ standards that this size_type guarantees enough allocation for all string usage.
I just find that hard to believe. What if I put the whole text of say C++ Primer 4th edition into a string? Or worse, what if I put infinite c... | string::size_type is guaranteed to be large enough for all strings that the current implementation supports - not any string of any size. If your implementation supports strings up to e.g. 8 GB, size_type can contain numbers up to 8 billion.
|
5,529,928 | 5,531,423 | Perl Win32::API and Pointers | I'm trying to utilize the Win32 API function DsGetSiteName() using Perl's Win32::API module. According to the Windows SDK, the function prototype for DsGetSiteName is:
DWORD DsGetSiteName(LPCTSTR ComputerName, LPTSTR *SiteName)
I successfully wrote a small C++ function using this API to get a better understanding of h... | Win32::API can't handle char**. You'll need to extract the string yourself.
use strict;
use warnings;
use feature qw( say state );
use Encode qw( encode decode );
use Win32::API qw( );
use constant {
NO_ERROR => 0,
ERROR_NO_SITENAME => 1919,
ERROR_NOT_ENOUGH_MEMORY => 8,
};
use cons... |
5,530,011 | 5,532,763 | Erase a row from a Gtkmm::Table | How do I erase a row from a Gtkmm::Table in C++?
Documentation is really poor :-(. I have tried using resize() with no effect, and also calling remove at a Gtk::Widget& that I obtained through get_children(), but the I get segfault...
| If Gtkmm::Table is GtkTable then gtk_container_remove should, probably, do what you need. I've made a small example (see below) it removes all label widget from the table container.
#include <gtk/gtk.h>
void remove_widgets(GtkWidget *widget, gpointer data)
{
if (GTK_IS_LABEL(widget))
{
g_print("remove ... |
5,530,022 | 5,530,043 | How to override non-virtual functions? | The very new syntax of override allows to let the compiler to report an error, if one does not really override a virtual function N3206.
class Base {
virtual void vfunc();
void afunc();
};
The following cases will be an error in class Derived : public Base, as mentioned in the Std examples:
void vfunk() overr... | The spec draft (n3242) says
If a virtual function is marked with the virt-specifier override and does not override a member function of a base class, the program is ill-formed.
Since the function declarations you show are not virtual, you also run afoul of
A virt-specifier-seq shall contain at most one of each virt... |
5,530,059 | 5,530,077 | Reg file - what does "dword" convert to? | I have a reg file which I'm trying to read.
There's a type "dword" in some of the values...
"check"=dword:000001f4
"blah"=dword:000000c8
"test"=dword:00000000
"hello"=dword:00000000
What C++ type should I convert it to ? and how ?
| A dword is a double word, where a word is the old (Intel 8086) 16-bit word.
So, it converts to the WinAPI-specific type DWORD, or the standard C (but not yet standard C++) type uint32_t. An unsigned long is guaranteed by C++03 to be large enough to hold 32-bits values as well, but may be wasteful on 64-bit platforms. A... |
5,530,106 | 5,531,318 | What is the prototype for Boost::signals2::signal::connect | I would like to encapsulate a signals2::signal object ans expose the connect and operator() functions, but how does their prototypes look like?
Example:
#include <boost/signals2/signal.hpp>
template<typename T> class A {
public:
typedef boost::signals2::signal<T> SIG_T;
void connect( TYPE1 arg ){
... | connect takes typename SIG_T::slot_type const &.
operator() takes typename SIG_T::argument_type (also defined as typename SIG_T::arg<0>::type).
Alternatively, you could use templates to avoid worrying about the exact definition and accept anything convertible to the correct types:
template <typename Slot> void connect(... |
5,530,236 | 5,530,644 | Detect PrintScreen / Screen scraping From Remote? | I've been trying to figure out how to detect this for months without any real progress. Whatever road I'll try out testing C++/C# code, all turns out to be dead ends.
The problem:
I have two computers, Comp1 and Comp2. The first is remotely administered by Comp2 (via local network).
Now, on Comp1 i want to be able to d... | I am not entirely sure i understand your question - but i will try to answer it anyway:
First let me rephrase the question the way i understand it:
Is there some way Host for a remote session can detect snapshots/screen scaraping done by the Client software running?
The short answer is "No".
A simple analog would be t... |
5,530,242 | 5,530,556 | CUDA FFT - power of two | I'm looking at the FFT example on the CUDA SDK and I'm wondering: why the CUFFT is much faster when the half of the padded data is a power of two? (half because in frequency domain half is redundant)
What's the point in having a power of two size to work on?
| I think this is your answer. It's using different algorithms
http://forums.nvidia.com/index.php?showtopic=195094
"I have been working on a similar
problem. In the cuFFT manual, it is
explained that cuFFT uses two
different algorithms for implementing
the FFTs. One is the Cooley-Tuckey
method and the other is... |
5,530,287 | 5,530,335 | 3d array c/c++ initialization/conversion | float sampleGrid1[5][5][5] =
{
{
{0.0, 0.0, 0.0, 0.0, 0.0},
{0.0, 0.0, 0.0, 0.0, 0.0},
{0.0, 0.0, 0.0, 0.0, 0.0},
{0.0, 0.0, 0.0, 0.0, 0.0},
{0.0, 0.0, 0.0, 0.0, 0.0}
},
{
{0.0, 0.0, 0.0, 0.0, 0.0},
{0.0, 0.0, 0.0, 0.0, 0.0},
{0.0, 0.0, 1.0, ... | Yes. that will not compile, because float[5][5][5] and float *** aren't same type. They're not even compatible type. One cannot convert to other automatically.
However, float[5][5][5] can convert to float (*)[5][5] automatically. So this is legal code:
float (*m)[5][5];
m = sampleGrid1; //legal - allowed!
Dem... |
5,530,367 | 5,531,049 | Quite strange MinGW ld problem - "collect2: ld returned 1 exit status" | I'm building an application for data visualization and the framework I'm using is beautiful OpenFrameworks. On Linux, it compiles and works perfectly, but now it's time to port it to Windows and I'm facing some very strange problems. I can't find relevant information from google. When linking, I get this:
mingw32-g++.e... | I found a solution by setting up an environment to directly call ld.exe with
-verbose
flag and got tons of information. I actually forgot to setup opengl32 development libraries, so linker could not find them.
|
5,530,505 | 5,530,998 | Why does this variadic argument count macro fail with VC++? | I got the following implementation to get the number of arguments in a variadic macro (currently limited to 16 args). However, for VS2010 the output is always 1, no matter how many arguments are passed. With GCC, the output is correct, bringing me to the conclusion that I must have missed something specific for MSVC (1... | Does the following work-around help?
#define EXPAND(x) x
#define PP_NARGS(...) \
EXPAND(_xPP_NARGS_IMPL(__VA_ARGS__,15,14,13,12,11,10,9,8,7,6,5,4,3,2,1,0))
I think your macro isn't wrong in particular, but
MSVC's __VA_ARGS__ expansion seems to behave differently from C99.
|
5,530,659 | 5,530,695 | C++ -The right way to throw and catch exceptions |
Possible Duplicate:
throwing exceptions of objects on the stack, mem leak with new?
Do you throw exceptions in C++ with or without the new operator? Because both of these would throw an exception.
void KillUnicorns()
{
throw IllegalActionException();
}
int main()
{
try
{
KillUnicorns();
}
... | I would throw exception without using new:
void KillUnicorns()
{
throw IllegalActionException();
}
And would catch it with const reference, as:
catch (const IllegalActionException & e)
{ // ^^^^ note const ^^ note reference!
}
It avoids copy. It avoids new, and so saves you from using delete.
|
5,530,750 | 5,539,382 | C++ memory leak auto detection library | I am searching for memory leak detection library.
Something like I would just include it into source code then it should start detecting. External programs might be good but i was looking for some library which can be linked into executable.
This i am searching for Windows.
| For me this was for very long time the best tool:
http://www.paulnettle.com/pub/FluidStudios/MemoryManagers/Fluid_Studios_Memory_Manager.zip
Just include 1 header file and you're done with it :)
|
5,530,867 | 5,531,504 | C++ multiplication of 2 strings representing decimal value of a number | The idea is to overload an operator * so it can multiply two strings representing decimal value of a number. The operator is part of a bigger class but that is not important. The algorithm is the same as in elementary school :)
Here's my code:
Bignumber operator* (Bignumber x, Bignumber y ){
int i, j, transfer=0, t... | While my first answer solves your issue (by my testing, anyway), here's an alternative implementation; I don't have your Bignumber class so I wrote a small fake one to test with:
#include <string>
#include <ios>
#include <iostream>
#include <ostream>
#include <sstream>
class Bignumber
{
static inline unsigned long... |
5,530,906 | 5,531,421 | Do I need to have 64 bit Processor to use 64 bit data type | I have a few questions:
Do I need to have 64 bit Processor to use 64 bit data type(__int64 or int64_t) ?
What means by, the "t" of int64_t?
Starting from what version of GCC and VCC are supporting data type?
Is the 64 bit data type are just doubling the data length or there are some other things going under the hood t... | You don't need 64 bit processor to use 64 bit data type. It all depends on the compiler and only on the compiler. The compiler can provide you with 128-bit, 237-bit or 803-bit data types, if it so desires.
However, keep in mind that normally 32-bit CPUs cannot handle 64-bit values directly, which means that the burden... |
5,530,933 | 5,530,940 | <dirent.h> in Visual Studio 2010 or 2008 | I want to use #include <dirent.h> in my code but this error happens:
Cannot open include file: 'dirent.h': No such file or directory
How can I solve this problem?
| Because this header file doesn't come with MSVC. Hence it cannot find it!
It comes with C POSIX library. The wikipedia says,
dirent.h is known to be included in
the following compilers:
Turbo C++ (DOS)
GCC (Cross-platform)
MinGW (Microsoft Windows)
Borland C++ Builder (Microsoft Windows)
Microsoft Visual C++ does... |
5,530,988 | 5,531,050 | What's the difference between scalbn and ldexp | The C99 standard defines ldexp(double a, int exp) as a × 2exp and scalbn(double a, int exp) as a × FLT_RADIXexp
What's the difference between the two if I'm using IEEE-754 arithmetic (i.e. FLT_RADIX == 2)?
| Appendix F:
F.9.3.6 The ldexp functions
[#1] On a binary system, ldexp(x, exp) is equivalent to
scalbn(x, exp)
|
5,530,991 | 5,531,138 | pthread_create segmentation fault | I'm using the method 'pthread_create' in my program, and get a segmentation fault INSIDE THIS METHOD.
What can possibly cause this? I'm calling this function with the correct arguments' types!
this is the code:
pthread_t* _daemon;
void* writer(void* arg){
// stuff that dont involve "arg"...
}
int initdevice(... | Your probelem is here:
pthread_t* _daemon;
This should be:
pthread_t daemon;
Then change the call to pthread_create:
if(pthread_create(&daemon, NULL, &writer, NULL) != 0)
The idea is that pthread_create takes a pointer to an existing pthread_t object so that it can fill in the details. You can think of it as the C ... |
5,531,143 | 8,357,863 | first function unknown | I am doing first steps with KCachegrind/Cachegrind.
I run Cachegrind on machine A then I moved the output files on machine B where I have KCachegrind installed.
I don't know why but I have always first function displayed as (unknown) and it is bad because I have there the 19.46 of the usage as displayed in the picture.... | I would check when this 'unknown' function is called in the lifetime of you program. If the unknown function is called before main then its not your code and you shouldn't really worry about it. If its after main then it still might not be your code, but will take some more investigating.
|
5,531,247 | 5,531,255 | allocating shared memory | i am trying to allocate shared memory by using a constant parameter but getting an error. my kernel looks like this:
__global__ void Kernel(const int count)
{
__shared__ int a[count];
}
and i am getting an error saying
error: expression must have a constant value
count is const! Why am I getting this error? And... | const doesn't mean "constant", it means "read-only".
A constant expression is something whose value is known to the compiler at compile-time.
|
5,531,310 | 5,531,371 | Validate DNA in C/C++ | I am iterating over DNA sequences pulling out chunks of 5-15 bases at a time into C++ std::string objects. Occasionally, my string will contain a non ATCG base, and I want to take an action when this happens. For example, I might see:
CTACGGTACGRCTA
Because there is an 'R', I want to recognize this case. I am famil... | A regular expression is overkill for this. You can use std::string::find_first_not_of().
|
5,531,896 | 5,531,919 | How to output an integer value in command line argument to characters of the equivalent length as the value in C++? | I got a value say 10 and i want to output this into xxxxxxxxxx (10 x). How do i do this?
The value 10 is passed in via the command line.
I have tried this, but it doesn't do what I want:
for (i = 1; i < argc; i++){
cout << argv[i++] << " " << argv[i] << endl;
} // i cant get the argv[i] to print ou... | if (argc>1)
cout << string(atoi(argv[1]), 'x');
|
5,532,046 | 5,532,195 | c++ "GetThreadTimes" but with a better resolution |
Is there a method with a better resolution than 100us that can get me the total time a thread was working (without the time it was sleeping or waiting).
thanks :)
| You could use QueryThreadCycleTime(), it counts cpu cycles. You can't do better than that. Available in Vista and up. It doesn't count sleep nor wait time, I verified on Win7.
|
5,532,464 | 5,532,574 | Rvalue reference parameters and template functions | If I define a function which accepts an rvalue reference parameter:
template <typename T>
void fooT(T &&x) {}
I can call it, using GCC 4.5, with either a, ar, or arr:
int a, &ar = a, &&arr = 7;
fooT(a); fooT(ar); fooT(arr);
However, calling a similar, non-template function,
void fooInt(int &&x) {}
with any of those... | The behavior of deduction in template parameters is unique, and is the reason your template version works. I've explained exactly how this deduction works here, in the context of another question.
Summarized: when the argument is an lvalue, T is deduced to T&, and T& && collapses to T&. And with the parameter at T&, it... |
5,532,884 | 5,532,909 | How to Initialize a Private Multidimensional Array | How would I initialize a private array where that one hundred items each equal a two-item array such as {-1, 0}. My code below obviously does not work since I am asking you all.
example.h:
#ifndef EXAMPLE
#define EXAMPLE
class Example {
private:
char grid[10][10];
public:
Example();
};
#endif
example.cpp:
#i... | This is not currently possible with C++. In C++0x it will be possible with braces, like
Example::Example() : grid{{-1, 0}} {}
And for the time being, you can wrap that array in a class, without any performance loss (the array will still be a normal, native multidimensional array)
class Example {
private:
struct da... |
5,532,969 | 5,532,981 | How to return a pair reference to data in a custom container? | #include <cstdint>
#include <utility>
class SimpleMap {
public:
typedef std::pair<const uint32_t, const uint32_t> value_type;
static const int SIZE = 8;
uint64_t data_[SIZE];
SimpleMap() { data_ = {0}; }
// Returning a reference to the contained data.
uint64_t const& GetRawData(size_t index) {
return ... | You're not storing pairs so you cannot return a reference to your stored pair. Return by value instead.
If your array was value_type data_[SIZE]; you could of course return references to these pairs - then you'd need to construct the uint64_t for GetRawData on demand, and return that as a value rather than a reference... |
5,532,991 | 5,533,017 | what is the difference between overloading an operator inside or outside a class? | In C++, i know there are two ways to overload. We can overload it inside (like class a) or outside (like class b). But, the question is, is there any difference between these two either in compile time or runtime or not?
class a
{
public:
int x;
a operator+(a p) // operator is overloaded inside class
{
... | The member operator+ requires the LHS to be an a - The free operator requires LHS or RHS to be a b and the other side to be convertible to b
struct Foo {
Foo() {}
Foo(int) {}
Foo operator+(Foo const & R) { return Foo(); }
};
struct Bar {
Bar() {}
Bar(int) {}
};
Bar operator+(Bar const & L, Bar co... |
5,533,159 | 5,533,232 | How to avoid long switch statements? C++ | I am working on a "dictionary" for my class. I have an int array called NumOfWordsInFile[] where NumOfWordsInFile[0] corresponds to how many words are in A.txt and NumOfWordsInFile[25] corresponds to Z.txt
As it is now I have a huge switch for the 26 different conditions of letters. I have a function called AddWord(str... | Chars are basically numbers. 'a' is 97, 'b' is 98 and so on.
The easiest way is to simply replace every numOfWordsInFile[n] with numOfWordsInFile[current_char - 'a'] and the whole code repeated for each case may reside in a function, like this:
int AddWord(char current_char) {
if(numOfWordsInFile[current_char - ... |
5,533,243 | 5,533,261 | Receive audio file via socket | I am trying to receive a file (audio, .CAF) from a socket in C (C++ solution ok as well). I have the socket communication working, having tested it with strings. My problem is I don't know what to supply to the 2nd arg in recv(socket, buffer, buffer_size, 0). What type should I make "buffer"? I basically want to rec... | Typically, you'll have the audio encoded in some format. For simplicity, let's assume it's Wave format.
One way of doing things would be to encapsulate chunks of the audio (Say, 50 ms chunks) for sending over the network.
However, you can't blindly send data over the network and expect it to work. On your computer, dat... |
5,533,354 | 5,533,450 | What does a call to 'this->template [somename]' do? | I've searched for this question and I can't find anything on it. Is there a better way to query something like this in Google or can anyone provide a link or links or a fairly detailed explanation? Thanks!
EDIT: Here's an example
template< typename T, size_t N>
struct Vector {
public:
Vector() {
this->templat... | Here is an example where this->template is required. It doesn't really match the OP's example though:
#include <iostream>
template <class T>
struct X
{
template <unsigned N>
void alloc() {std::cout << "alloc<" << N << ">()\n";}
};
template <class T>
struct Y
: public X<T>
{
void test()
{
... |
5,533,754 | 5,533,755 | DLL GetProcAddress Problem - Another Run-Time Check Failure | Well, i am having some issues with an error that i don't understand.
These are the two related files:
Inside DLLExporter:
#ifdef LOGGER_EXPORTS
#define LOGGER_API __declspec(dllexport) __stdcall
#else
#define LOGGER_API __declspec(dllimport) __stdcall
#endif
typedef long (CALLBACK *LPFNTIMER)( void );
// Exp... | Just thinking, perhaps if you call LogTimer() before LogRelease()?
And what about passing the proper parameters to Initialize and SetTimer?
|
5,533,756 | 5,533,766 | C++ commands executing out of order | I am attempting to make a simple shell program, and looking at a few examples have seen that most people use getline() to get input, however I have been trying to use read() and noticed a weird bug that I was wondering if other people saw or knew the cause of.
When I run the code using getline, everything works fine. A... | You should try "flushing" the output buffer to make sure it prints in order. Try:
cout << "SweetShell-> " << std::flush;
int test = read(0,buf,MAX_ARGS);
//temp is a string that is set to the input
cout << temp << " " << test << std::flush;
|
5,533,850 | 5,533,890 | template specialization round-lambda notation | template <class T, class I> struct A; //EDIT: template <class T> struct A; : OK
template <class T, class I>
struct A<T(I)>
{
};
void main()
{
A< int(char) > b;
}
This code doesn't compile. WHere is the mistake ?
THanks
| template <class T> struct A; and no template <class T,class I> struct A;
sorry to answer myself but perhaps that will useful for other users
|
5,533,919 | 5,534,131 | "Does not name a type" in header-only library | I'm trying to write a header-only library of helper functions for myself. (I'm using boost and SDL, and boost is much easier to use, so I want to emulate that for my own helper library.)
I'm getting the error "Does not name a type" for one of my classes, and it's confusing me. I know I can get this problem with a missp... | I see what you are trying to do: a header-only library implies that .cpp file is included into .h file and not the other way around (this is, of course, confusing for many people). But if you are doing it that way, then you should not attempt to compile your .cpp files as ordinary source files. In fact, it might be a b... |
5,533,935 | 5,533,963 | Compiling Error with C++ and namespace | Here's the whole code getting the errors:
Engine.h
#ifndef ENGINE_H
#define ENGINE_H
#include "DXManager.h"
namespace XEngine
{
class Engine
{
};
}
#endif
DXManager.h
#ifndef DX_MANAGER_H
#define DX_MANAGER_H
namespace XEngine
{
class Engine; // forward declaration
class DXManager
{
... | In the forward-declaration of class Engine the namespace XEngine doesn't exist at this point.
A workaround would be moving the declaration inside the namespace block.
|
5,534,029 | 5,534,103 | Simple (mostly) variable parser | In one of my projects, I need to be able to provide a very simple variable find-and-replace parser (mostly for use in paths). Variables are used primarily during startup and occasionally to access files (not the program's primary function, just loading resources), so the parser need not be high-performance. I would gre... | Simple solution is to search for the first ')' in the string, then move backwards to see if there's an identifier preceeded by "$(". If so, replace it and restart your scanning. If you don't find "$(" identifier, then find the next ')' - when there isn't one you're finished.
To explain: by searching for a ) you can b... |
5,534,508 | 5,534,537 | Problem with C++ Map | I am facing some problem with Map. I am developing an application where I am designing a database and I am facing a problem where I need to store table schema in Main Memory. The elements in the map are getting sorted automatically (as per the key) and I need the ordering to be as it is. I want the elements to be inser... | It depends on how you intend to use the data. If you only occasionally need to access the data by key but generally just need to access it in the order in which it is inserted, you should just store the data in a std::vector:
std::vector<std::pair<Key, Value> > data;
As long as you always add elements using push_back... |
5,534,530 | 5,534,798 | c++ Output Format to Console Based on User's Define Number Of Columnns | I like to display data information to dos console based on user's template or ini file.
Example,
UserTemplate.txt
ParamA=yes
ParamB=yes
ParamC=yes
ParamD=yes
ParamE=yes
ParamF=no
ParamG=yes
ParamH=no
..
..
My program will read this UserTemplate.txt and what parameter user wants to display to dos console.
while (!f... | I would probably create a small data structure that tells how (and if) to display each column:
struct column_display {
bool display;
int width;
column_display(bool d) : display(d), width(0) {}
};
Then we'd add some code to read each name:display pair from the file:
std::istream &operator>>(std::istream &i... |
5,534,620 | 5,535,415 | Mimicking the shell argument parser in C++ | I have been working on a program that mimics a shell terminal, and I've come across an implementation issue that is harder than I anticipated. Basically, I'm trying to split arguments, much like how the shell does to pass to its executable. So, imagining an input like:
$> ./foo some arguments
One would expect the argum... | I sometimes still use this plain C utility function for this. I mostly use this on embedded systems where there is a very limited standard library, so most of the code can be changed to be more efficient using standard lib controls, but the basic technique should remain the same being, mark the quoted parts of the stri... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.