question_id int64 25 74.7M | answer_id int64 332 74.7M | title stringlengths 20 150 | question stringlengths 23 4.1k | answer stringlengths 20 4.1k |
|---|---|---|---|---|
6,025,466 | 6,025,575 | Why use static_cast rather than dynamic_cast in here? | I copy the following text from the book More Effective C++.
Item 31: Making functions virtual with respect to more than one object.
class GameObject { ... };
class SpaceShip: public GameObject { ... };
class SpaceStation: public GameObject { ... };
class Asteroid: public GameObject { ... };
The most common approach ... | For the record, here is the idiomatic way of doing that:
void SpaceShip::collide(GameObject& otherObject)
{
if (SpaceShip* ss = dynamic_cast<SpaceShip*>(&otherObject)) {
// process a SpaceShip-SpaceShip collision;
}
else if (SpaceStation* ss = dynamic_cast<SpaceStation*>(&otherObject)) {
// ... |
6,025,655 | 7,138,126 | Coderloop not accepting Project Euler solution | I discovered this website where you submit your solution and the "puzzle master" processes it and verifies it. I have two solutions, both of which work fine on my compiler and yet the "puzzle master" is rejecting them.
Solution 1: Brute Force
#include <iostream>
using namespace std;
int main()
{
int s=0,i;
for(i=1;i... | If you submitted your code using the online editor, I guess it simply did not compile.
Indeed the online editor allows submissions only for interpreted languages, whereas compiled languages must be provided via file upload, along with a Makefile or an Ant file that indicates the judge how to compile it.
It is a bit con... |
6,025,740 | 6,025,789 | can't store an object into array? C++ | I'm trying to do something simple and store an object into an Array in C++ but it keeps saying that I can't use the = operator with the right hand operand being of my class. Here's the code:
class Player {
string name;
double points;
bool wonLastRound;
public:
Player() {}
Player(string n)
{
... | It should be,
Player& operator = (const Player &); // remove "const" (it's not mandatory though)
Actual problem lies in assignment inside for loop. You don't have to new the objects, as you are storing value and not the pointer.
Usage:
players[i] = Player("Player " + i); // no need to do "new"
|
6,026,065 | 6,026,110 | Single linked lists C++ | Hey guys,
I'm studying for a midterm right now and am working on trying to create a simple program using single linked list. All I want it to do is insert "1", "2", "3", "4" into the list and print it out. Please take a look at the following code:
#include <iostream>
#include <string>
using namespace std;
class node... | node::node(int data) {
data = data;
next = NULL;
}
The line data = data is a problem for you. Rename the parameter to be different from the member. This ought to give you a series of garbage values (not pointers) for the member variable data.
Note: this is one of the reasons for naming convention distinguishin... |
6,026,114 | 6,026,740 | boost filesystem version 3 issue? | the example code on the boost website is not working. http://www.boost.org/doc/libs/1_46_1/libs/filesystem/v3/doc/tutorial.html#Using-path-decomposition
int main(int argc, char* argv[])
{
path p (argv[1]); // p reads clearer than argv[1] in the following code
try
{
if (exists(p)) // does p actually exis... | This section (for's body) is problematic:
path fn = it->path().filename(); // extract the filename from the path
v.push_back(fn); // push into vector for later sorting
it points to path objects, so I don't see why path() is called. Seems that it should be replaced with it->filename()
you push ... |
6,026,234 | 6,026,293 | C++ templated return value with pure virtual function | I have an abstract Handle<T> class that contains references an objects of type T. I want to be able to have that class be able to be converted to Handle<U>, where U is a superclass of T. I would use inheritance, but that doesn't work here. How would I go about doing this? What are good alternatives?
Example psuedo code... | virtual template<class U> operator Handle<U>* () const =0;
Template virtual function is not allowed by the language specification.
Consider this code at ideone, and then see the compilation error:
error: templates may not be ‘virtual’
Now what can you do? One solution is this:
template<class T>
class Handle {
publ... |
6,026,446 | 6,026,477 | Direct3D strange crash | I have Direct3D rendering library compiled with VS2008. The another application (built with VS2008) uses my library and everything works fine.
Recently, parent application was moved to VS2010 but my library is still being built under VS2008. And still everything works fine BUT one call on only ONE sprite.
D3DXSprite->D... | This may not be want you want to hear, but all I can suggest for debugging something like this is the liberal use of break points and special debugging if-statements.
Place a try-catch statement around the render function that is failing and place a breakpoint in the catch block.
You may need to add some counters and d... |
6,026,467 | 6,027,005 | How To Create TimerHandler Using Boost Library | I'm working on a project using C++.
I want a TimerHandler to be called after a specified time, but at the same time I don't want to block the current thread or any code after io.run() in the following code:
#include <iostream>
#include <string>
#include <boost/format.hpp>
#include <boost/asio.hpp>
#include <boost/bind... | Here is an example . Run the io_service in a separate thread
asio::io_service io_service;
asio::thread t(boost::bind(&asio::io_service::run, &io_service));
or run it in a thread group
boost::thread_group threads;
for (std::size_t i = 0; i < my_thread_count; ++i)
threads.create_thread(boost::bind(&asio::io_service:... |
6,026,519 | 6,026,549 | which is a better approach for fibonacci series generation | The two general approaches for Fibonacci series generation are:
The traditional approach, i.e., running through a for loop inside a function.
Recursion
I came across another solution
#include <iostream>
using namespace std;
void fibo() {
static int y = 0;
static int x = 1;
cout << y << endl;
y = x + y;
x = y -... | Disadvantages I can immediately see:
By essentially making the state global, it's not thread-safe
You can only ever run through the sequence once, as there's no way to reset
I would favour an approach which keeps the state within an object which you can ask for the next value of - an iterator, basically. (I've never ... |
6,026,838 | 6,026,861 | How do you determine the path of the file that a symlink points to? | In Linux, if you have a path to a file which you know is a symlink, how do you programmatically determine (in C or C++) the path to the file that it points to?
| The readlink function. Do a man 2 readlink. This function is part of the Posix API, so it should work on almost any Unix.
If the path starts with a '/', then its an absolute symlink and you have the full absolute path of the file to which it refers (which may be another symbolic link, and you'll have to repeat the proc... |
6,026,980 | 6,027,030 | C++ QueryPerformanceCounter and QueryPerformanceFrequency | I have been attempting to create a timer for my game and I heard about QueryPerformanceCounter and QueryPerformanceFrequency. Could someone please explain how these can be used to calculate time/fps/ticks in a game loop?.
| Microsoft support has a Knowledge Base article specifically about this:
How To Use QueryPerformanceCounter to Time Code
Basically you use QueryPerformanceCounter to get a high resolution timer value before and after the event you want to time.
Then use QueryPerformanceFrequency to get the number of ticks per second. D... |
6,027,371 | 6,027,440 | C++ including a ".h" file, function duplication confusion | I'm currently writing a program, and couldn't figure out why I got an error (note: I already fixed it, I'm curious about WHY the error was there and what this implies about including .h files).
Basically, my program was structured as follows:
The current file I'm working with, I'll call Current.cc (which is an implemen... | You can't have two global functions with the same name (even in 2 different translation units). To avoid getting the linker error define the function as static so that it is not visible outside the translation unit.
EDIT
You can use the function in the other .cpp file by using extern keyword. See this example:
//Test.c... |
6,027,955 | 6,059,889 | Problem with typedefing enums. And bug in visual studio 2005 | struct A
{
enum E
{
FIRST,
SECOND
};
};
struct B
{
typedef A::E E;
};
int main()
{
B::E e0 = A::FIRST;//OK (this case is clear for me)
B::E e1 = A::E::FIRST;//OK (this case is clear for me as well)
B::E e2 = B::FIRST;//Compile Error: FIRST is not member of B (Why isn't this... | After adding the missing semicolon in B::E e3 = B::E::FIRST, the following holds:
In C++03, only the first line (B::E e0 = A::FIRST;) is correct, the other three are errors:
B::E e1 = A::E::FIRST; // error: ‘A::E’ is not a class or namespace
B::E e2 = B::FIRST; // error: ‘FIRST’ is not a member of ‘B’
B::E e3 = B::E::F... |
6,028,158 | 6,028,358 | parsing string with respect to string format |how | I have ;
string str = "";
in str, I store data is in following form "_ : _, _ "
"_" can be just a word like "X" or a composition of words like "a sds 23 dsds 1"
I want them parse it to three different string ;
in str : X:y dfj kd kk,sdd 12 89 ++
string parsed[i] ;
in parsed[0] : X
in parsed[1] : y dfj kd kk
in... | You can split your string using the following std:string methods for example:
size_t index1 = str.find( ":" ) + 1;
size_t index2 = str.find( ",", index1 ) + 1;
std::string sub1 = str.substr (0, index1-1);
std::string sub2 = str.substr (index1, index2-index1-1);
std::string sub3 = str.substr (index2, str.length()-index... |
6,028,233 | 6,028,254 | A simple "javac" style command-line C/C++ compiler for Windows 7 | Over the last couple of months I practiced console programming with Java just with the help of JDK and a text editor of my choice (Notepad++). And I loved the simplicity as a program can be compiled from the command line plainly using javac and run using java.
Now, I'm looking for similar compiler for C/C++, such that ... | You can download MinGW which is basically GCC for windows.
Then you can simply gcc somefile.c to create an executable.
|
6,028,279 | 6,028,363 | Comparing doubles to double literals? |
Possible Duplicate:
How should I do floating point comparison?
Is it not recommended to compare for equality a double and a double literal in C++, because I guess it is compiler dependent?
To be more precise it is not OK to compare a double which is hard-coded (a literal in the source code) and a double which should... | You've misunderstood the advice a bit. The point is that floating-point computations aren't exact. Rounding errors occur, and precision is gradually lost. Take something as simple as 1.0/10.0. The result should be 0.1, but it isn't, because 0.1 cannot be represented exactly in floating-point format. So the actual resul... |
6,028,339 | 6,035,083 | ICU and string compare | can anybody explain why the following compare are not equal?
void CompareTest()
{
UErrorCode status = U_ZERO_ERROR;
UChar ruleset[500]; *ruleset = 0;
int32_t rlen = 0;
UCollator *coll = ucol_open("de_DE", &status);
static const UChar rules[] = L"&\\u0000 = '' = '-'";
int32_t len=(int32_t)u_strlen(rules);... | You don't need to do any rule customization.
UCollator * collRule = coll;
ucol_setAttribute(collRule, UCOL_NORMALIZATION_MODE, UCOL_ON, &status); // no effect for these samples.
ucol_setAttribute(collRule, UCOL_STRENGTH, UCOL_PRIMARY, &status);
ucol_setAttribute(collRule, UCOL_ALTERNATE_HANDLING, UCOL_SHIFTED, ... |
6,028,345 | 6,037,062 | How to use JNI registerNatives inside c++ class? | I have a c++ class called androidGPS with public methods and variables. Inside this class I am using JNI to calls some java code. But I am stuck in the registerNatives function.
My c++ class has this void method:
void LocationChanged(JNIEnv* env, jobject object, jstring paramsString);
Implemented in this way:
void and... | One option is that you give your Java code a means of getting a pointer to your native androidGPS object and passing it down to the non-class-function LocationChanged(), and it calls androidGPS::LocationChanged().
Callbacks into non-static C++ objects are problematic and typically are solved using a static helper funct... |
6,028,472 | 6,028,529 | singleton implementation question | template <class T>
class Singleton
{
public:
static T& instance()
{
boost::call_once(init, flag);
return *t;
}
static void init()
{
t.reset(new T());
}
protected:
~Singleton() {}
Singleton() {}
private:
static boost::scoped_ptr <T> t;
static boost::once_flag flag;
};
template <cl... | TestClass class1 = TestClass::instance();
You're making a copy of the object returned by the factory, so you get a different object each time.
To prevent this, get references to your singleton:
TestClass& class1 = TestClass::instance();
Still there is something strange because making a copy of MyClass issues compil... |
6,028,473 | 6,028,562 | How can I safely make a float *x into a const float *const *y? | I have a function audioReceived (float * input, int bufferSize, int nChannels) inside of which I want to call a function from a library that needs const float *const *inputBuffers.
Obviously casting const float *const *inputBuffers = (const float* const*)input; compiles but is a terrible idea, crashes the program, kill... | Semantics is important here. From the parameter names, I can guess that the function you want to call accepts multiple buffers, so it wants an array of pointers to float (i.e. an array of arrays). Since you only have an array, you need to create an array that contains the original pointer, and pass that to the function... |
6,028,524 | 6,029,598 | How to layout C++ code: namespaces and similar file names in visual studio 2010 | This is more of a general question as I have found relatively little information on the net on how to best organize source code.
The way I currently have laid out my code is to have one project in VS compiling a lib, and then two console application projects on top of that, one for unit tests and one to execute the cod... | IDE's usually let you arrange your files logically. (Visual Studio and XCode at least both let you create heirachal groups to arrange your source files, that does not correspond to the locations on disk of the files).
Because most IDEs compile all the source files to a common intermediate folder for the linking step an... |
6,028,736 | 6,028,783 | template class inheritance problem | Can you please tell me, what am I missing?
template <class T> struct Base
{
T data;
Base(const T &_data):data(_data) { }
};
template <class T> struct Derived : Base<T>
{
Derived():Base(T()) {} //error: class 'Derived<T>' does not have any field named 'Base'
};
| template <class T> struct Derived : Base<T>
{
Derived():Base<T>(T()) {}
};
|
6,028,884 | 6,042,030 | Not all native global variables are destructed in mixed-mode .Net application because of a 2-second time-out | I my mixed-mode C++ application I notice the following strange effects:
If I start the executable outside Visual Studio, all unmanaged global variables are correctly destructed.
If I start the executable outside Visual Studio, then attach the debugger, all unmanaged global variables are correctly destructed.
I I start... | Hmm confirming the problem. I'll need to think/read more about this. It is starting to look like a bug, really.
Note at no time did I run any of this with debugging, because my VS setup is somehow borked. Kudos for doing the commandline build!
For the record, here is my initial run (without recompiling, just your bina... |
6,029,092 | 6,029,595 | Compare boost::any contents | I am using a container to hold a list of pointers to anything:
struct Example {
std::vector<boost::any> elements;
}
To insert elements in this container, I had written a couple of helper functions (members of the struct Example):
void add_any(boost::any& a) {
elements.push_back(a);
}
template<typename T>
void... | The only easy way to do this I can think of involves hardcoding support for the types that you're storing in the any instances, undermining much of the usefulness of any...
bool equal(const boost::any& lhs, const boost::any& rhs)
{
if (lhs.type() != rhs.type())
return false;
if (lhs.type() == typeid(st... |
6,029,257 | 6,030,473 | Why am I getting invalid data from my QTouchPoint? | I have a QGraphicsScene with QGraphicsItems. I have reimplemented the sceneEvent function and handle multi-touch.
The problem is that randomly I get invalid values out of this section:
QTouchEvent *touchEvent = static_cast<QTouchEvent *>(event);
QList<QTouchEvent::TouchPoint> touchPoints = touchEvent->touchPoi... | Are you blindly casting events or using a switch-case statement as below ?
bool MyItem::sceneEvent(QEvent *event)
{
case QEvent::TouchBegin:
case QEvent::TouchUpdate:
case QEvent::TouchEnd:
{
QTouchEvent *touchEvent = static_cast<QTouchEvent *>(event);
QLi... |
6,029,305 | 6,029,599 | Too few template-parameter-lists problem | Can anybody please tell me how to make the following pseudo-code compatible with GCC4? I wonder how it works under MSVC...
typedef int TypeA;
typedef float TypeB;
class MyClass
{
// No base template function, only partially specialized functions...
inline TypeA myFunction<TypeA>(int a, int b) {} //error: Too few t... | The proper way of coding that construct would be:
typedef int TypeA;
typedef float TypeB;
class MyClass
{
template <typename T>
T myFunction( int a, int b );
};
template <>
inline TypeA MyClass::myFunction<TypeA>(int a, int b) {}
template <>
inline TypeB MyClass::myFunction<TypeB>(int a, int b) {}
Note that... |
6,029,312 | 6,031,189 | invalid null pointer in xstring | So I'm almost done with this assignment but now I'm having difficulties again. When I try to draw text from a question class I get invalid null pointer from xstring. I have about 2 hours, so any help would really be appreciated
Here's the question class:
class Question {
public:
int col;
int row;
bool dai... | Your operator=(const Question&) is wrong, it does nothing but returning the current object. If that object was created with the default constructor, "question" and "answer" are not initialized, and your program may crash if this operator is used.
The operator "=" is supposed to copy each field. For string pointers like... |
6,029,697 | 6,029,848 | how to split a string value that contains characters and numbers | I have a std::string s=n8Name4Surname. How can I obtain in 2 strings the Name and the Surname? THX
| One way to do this is using Boost.Tokenizer. See this example:
#include <string>
#include <boost/tokenizer.hpp>
#include <boost/foreach.hpp>
int main()
{
using namespace std;
using namespace boost;
string text="n8Name4Surname.";
char_separator<char> sep("0123456789");
tokenizer<char_separator<char>... |
6,029,875 | 6,029,898 | Problem with EOF when determining stream end | When I try to determine end of file with function feof(FILE *), I find it does not work as I expected: an extra read is required even if the stream does end. E.g., feof(FILE*) will not return true if invoked on a file with 10 bytes data just after reading 10 bytes out. I need an extra read operation which of course ret... | Do not use feof() or any variants—it is as simple as that. You want it to somehow predict the next read will fail, but that's not what it does - it tells you what the result of the previous read was. The correct way to read a file is (in pseudocode):
while(read(file, buffer)) {
// Do something with buffer
}
In othe... |
6,030,001 | 6,030,093 | SetWindowsHookEx failing with google chrome. Error code 87 invalid parameter | I am making a tutorial based program and want to be able to hook my code into certain apps to get the tutorial interacting with the app.
My hook code works for most apps except google chrome. I have stripped my code down to the following so you can see it going wrong.
Main.cpp
#include <Windows.h>
#include <iostream>
#... | One possible problem would be if you're building 64bit code, but chrome.exe is 32bit (or the other way around). [See comment & update, this is not the case.]
One suspicious thing in your code is that you're not calling Process32First, and that seems to be required. See for ex: Taking a Snapshot and Viewing Processes.
... |
6,030,339 | 6,030,427 | Which is quicker/more efficient? | Currently learning about efficiency in C++ and wondered about the efficiency of returning parameters in methods.
Imagine a Vector3f class with an add method.
Code One:
Vector3f Vector3f::add(const Vector3f &rhs) const {
Vector3f result;
result.x(x() + rhs.x());
result.y(y() + rhs.y());
result.z(z() + rh... | It probably has to do with the return-value optimisation (RVO). Because the second form constructs the object as it returns it, the compiler is allowed to (and usually will) skip the copy-constructor by constructing the object directly in the caller's context.
The first form can also be optimised in similar fashion, bu... |
6,030,360 | 6,030,380 | return code of console application |
Possible Duplicate:
How do I get the application exit code from a Windows command line?
I have a console application. It will be executed from command prompt. It will return either 0 or 1 from main method. How can I know that what value is returned by the application?
| Assuming you're on Windows (C# tag)
echo %errorlevel%
|
6,030,466 | 6,033,868 | Change parameters of random number generator | I am using the boost::random to generate random velocity values and I want to change the mean and variance in response to user input.
I am using the following:
typedef boost::mt19937 RNG;
static RNG rng();
typedef boost::normal_distribution<double> DIST;
DIST dist_east(vel_e, sigma);
DIST dist_north(vel_n, sigma);
bo... | In my opinion the quickest way is just to have a normal distribution with sigma 1 and mean 0. In that way, you can get values from any normal distribution just multiplying for your new sigma and adding the mean.
y = mean + sigma * x
|
6,030,503 | 6,030,577 | std::enable_shared_from_this ... Does a new shared_ptr know to take shared_from_this()? | I have a class that derives from enable_shared_from_this ... (Recently been added to std from Boost)
class Blah : public std::enable_shared_from_this<Blah>
{
};
I know I should create shared pointers from an instance like this:
Blah* b = new Blah();
std::shared_ptr<Blah> good(b->shared_from_this());
Question is, wil... | Blah* b = new Blah();
std::shared_ptr<Blah> good(b->shared_from_this()); // bad, *b is not yet owned
This is incorrect. For shared_from_this to work, b must already be owned by at least one shared_ptr. You must use:
std::shared_ptr<Blah> b = new B();
Blah* raw = b.get();
std::shared_ptr<Blah> good(raw->shared_from_thi... |
6,030,556 | 6,030,769 | How to add a new row to Excel file using unmanaged C++? | How can I add a new row (with contents) to an existing Excel .xls file using unmanaged C++ running on Windows?
I don't mind using OLE, COM, or any external free library, whatever is the easiest way.
| There is a COM interface which is well documented.
I'd suggest you start with the Workbooks.Open method to open an existing excel file.
If you only need basic features (no formatting, formula's, ...), you can also use BasicExcel: A c++ library which doesn't have any dependencies (it reads and writes the excel file as a... |
6,030,620 | 6,045,359 | Is there a way in Eclipse CDT to automatically switch from . to -> | The Qt Creator have a neat feature I really like. When I'm typing obj.method, it would automatically replace the period (.) with an arrow (->), if obj is a pointer.
Makes sense actually. You never want to type pointer.something, it wouldn't be legal.
Is there a way to achieve a similar function with Eclipse CDT?
This q... | The upcoming CDT 8.0 for Eclipse Indigo has that feature.
|
6,030,763 | 6,030,880 | c++ self in initialisation list | i have this code snippet
class Osoba{
Osoba(char* imie,int wiek){
this->imie=new char[strlen(imie)+1];
strcpy(this->imie,imie);
this->wiek=wiek;
cout<<"Utworzono Osobe "<<this->imie<<endl;
}
... | You cannot call a constructor except for creating another different object.
If you need to have some code in common between constructors you can place it in a separate method and call that method. Note that in the constructor you can call methods of the object but virtual methods are not going to dispatch do derived cl... |
6,030,830 | 6,031,048 | Vector capacity and reserve | Consider the following code snippet:
std::vector<int> v;
v.reserve(100);
v.insert(v.end(), 100, 5);
v.erase(v.begin(), v.end());
std::cout << v.capacity << std::endl;
This prints out 100. Does it mean that vector still holds the 100 memory locations? Is it required to call reserve(0) after calling erase(begin,end) o... | You are looking for the (in)famous swap trick:
vector<T>().swap(myVector);
See here for backgrounder
How to downsize std::vector?
|
6,030,993 | 6,031,013 | C++ to Java Code Conversion | I have in C++
r.bits[k] &= 0xFF ^ msk;
So in Java
r.bits[k] = r.bits[k] & 0xFF,
but what is the meaning of the caret symbol? msk also will contain hexadecimal values.
I know the caret symbol is a type of pointer in C++ but not sure what it is doing here.
Please explain.
| The ^ symbol represents the bitwise XOR operator in C, C++. List of operators in C, C++.
The same operator is available for Java as well. XOR Operator in Java.
|
6,031,078 | 6,031,160 | Control other app over gui from my program | I would like to write a simple C++ program for Linux (Ubuntu) to control other GUI programs. For example, to be able to read text labels and put text into entry boxes of other programs written using gtkmm. I have looked at X11 but I don't seem to find any relevant information or examples.
Thank you very much for any in... | One way of doing it is via the XTEST (pdf) extension.
An example usage for key events is here: X11 Fake Key Event Generation using XTest Extension.
|
6,031,185 | 6,031,238 | priority queue and structs | #include <iostream>
#include <queue>
using namespace std;
struct Call
{
Call( int callNum, long callTime, int callLength ) :
CallNum( callNum ), CallTime( callTime ), CallLength( callLength ) { }
int CallNum;
long CallTime;
int CallLength;
};
bool operator>( const Call& lhs, const Call& rhs ) {
... | Are you just looking for:
cout << q.top().CallNum << endl;
and so on?
|
6,031,296 | 6,040,464 | c++ memory leak when using std::string in shared memory array | I have this class
class LayoutEntry
{
unsigned int id_;
string name_;
bool isInput_;
};
The copy constructor looks like this:
LayoutEntry(const LayoutEntry &other)
: id_(other.id_),
name_(other.name_),
isInput_(other.isInput_)
{
}
Objects of this class are put inside a map wit... | The reason for the leak was the LayoutEntry class that stores a string. The base object (before modification) was placed in an array within a shared memory area. After altering the string a resize operation was performed, this memory was lost. After replacing the string by an array of chars (fixed length) the memory le... |
6,031,409 | 6,031,503 | Why can't I call a templated method from a derived class instance in C++? | Please consider these types:
struct X
{
static std::string fullyQualifiedName();
};
struct A
{
template <class T> void foo()
{
return foo(T::fullyQualifiedName());
}
protected:
virtual void foo(const std::string& name) = 0;
};
struct B : public A
{
protected:
void foo(const std::str... | The problem you are facing is called hiding. Basically the lookup rules in the language will start in the most derived type and work their way back up until it finds the appropriate symbol. In your case it will stop while looking at the B class as it finds void B::foo(const std::string& name). At that level, the only p... |
6,031,431 | 6,031,589 | GetProcAddress function in C++ | Hello guys: I've loaded my DLL in my project but whenever I use the GetProcAddress function. it returns NULL! what should I do?
I use this function ( double GetNumber(double x) ) in "MYDLL.dll"
Here is a code which I used:
typedef double (*LPGETNUMBER)(double Nbr);
HINSTANCE hDLL = NULL;
LPGETNUMBER lpGetNumber;
hDLL =... | Checking return codes and calling GetLastError() will set you free. You should be checking return codes twice here. You are actually checking return codes zero times.
hDLL = LoadLibrary(L"MYDLL.DLL");
Check hDLL. Is it NULL? If so, call GetLastError() to find out why. It may be as simple as "File Not Found".
lpGe... |
6,031,470 | 6,031,665 | manual object constructor call | Can you please tell me if it is possible to call object constructor manually? I know it's wrong and I would never do something like that in my own code and I know I can fix this problem by creating and calling initialization function, however the problem is that I stumbled at a case where there are thousands of lines o... | You can still move construction/destruction into separate functions and call those directly. i.e.
class MyClass {
public:
MyClass() { construct(); }
~MyClass() { destruct(); }
void reset() {
destruct();
construct();
}
private:
void construct() {
// lots of code
}
v... |
6,031,795 | 6,031,841 | Software for browsing classes in a C/C++ project | I have seen that some developers have a graphical representation of all their classes in an image file which comes with their project. How can I myself create these graphics?
Basically they show what classes exist in a file and how these files relate to each other.
Thanks
| Doxygen allows you to generate interactive class diagrams. Check out this page: http://www.doxygen.nl/manual/diagrams.html how to set it up.
|
6,032,096 | 6,032,165 | Static function leading to more static functions | I have a class that has a few functions that are useful on their own, which are static. Now these functions depend on other functions that are not useful on their own (but don't interact with class member variables) but are also static, so they are private. Now I have a class with many non-static functions, and couple ... | I think you should declare those functions as free functions. If they do not need the members it should be not a big deal.
Maybe you should read this article. I found it very useful to improve my class designs.
|
6,032,372 | 6,032,397 | Prevent array decaying to ** from *[N] | I have declared my array like this:
FT_Interface<4096> *to_make_ft[3] = { /* initialization with existing objects */ };
my interface is declared like this:
template<cyg_ucount32 S, int N>
class FT_Thread {
FT_Thread(FT_Interface<S> *entry[N]){}
};
And i call it (as expected with):
FT_Thread<4096, 3> ft(to_make_ft);... | You need
FT_Thread(FT_Interface<S>* (&entry)[N]){}
// note these ^^-----^
With that, you get a reference to the array.
Edit: Of course, if you want a pointer to the array, you can have just that:
FT_Thread(FT_Interface<S>* (*entry)[N]){}
Though you need to call it with FT_Thread<4096,3> ft(&to_make_ft).... |
6,032,638 | 6,032,889 | Default variable value | If I don't assign a value to a variable when I declare it, does it default to zero or just whatever was previously in the memory?
e.g.
float x;
| A declared variable can be Zero Initialized, Value Initialized or Default Initialized.
The C++03 Standard 8.5/5 aptly defines each:
To zero-initialize an object of type T means:
— if T is a scalar type (3.9), the object is set to the value of 0 (zero) converted to T;
— if T is a non-union class type, each nonstatic d... |
6,033,076 | 6,033,128 | How to catch substr exception? | I'm using substr for generating substring. How I can catch substr exception? For instance:
terminate called after throwing an instance of 'std::out_of_range'
| Like this:
try
{
/// use substr
}
catch( std::out_of_range& exception )
{
// print out an error, and fail, or restart if appropriate.
}
|
6,033,184 | 6,054,897 | How computer does floating point arithmetic? | I have seen long articles explaining how floating point numbers can be stored and how the arithmetic of those numbers is being done, but please briefly explain why when I write
cout << 1.0 / 3.0 <<endl;
I see 0.333333, but when I write
cout << 1.0 / 3.0 + 1.0 / 3.0 + 1.0 / 3.0 << endl;
I see 1.
How does the compute... | The problem is that the floating point format represents fractions in base 2.
The first fraction bit is ½, the second ¼, and it goes on as 1 / 2n.
And the problem with that is that not every rational number (a number that can be expressed as the ratio of two integers) actually has a finite representation in this base 2... |
6,033,201 | 6,043,626 | Passing an object from Javascript to C++ | I have found Passing an array from Javascript to C++ solution, but I have another task: Passing an object from Javascript to C++ (if I use IWebBrowser2 with IDispatch)
I mean that I need call C++ method via window.external.method with JavaScript object argument
var obj = {name: "Petr", group: "Friend"};
window.external... | You can access the object's properties via the IDispatch interface and its methods GetIDsOfNames and Invoke.
Depending on your definition of myMethod, you should be receiving obj as either a VARIANT or an IDispatch * in your C++ code. If a VARIANT, vt should be VT_DISPACTH, in which case you can safely dereference pdis... |
6,033,212 | 6,033,272 | Loading a third party dll in visual c++/qt application | I have third party dlls that I need to use with my application. The interface is defined in the third party dlls and I have to make the interface call from my application. I have the function prototype of the interface, but no lib files or header files. It looks like loadlibrary should be used, but is it possible with... | You load the library with the API function LoadLibrary. After loading the DLL you use GetProcAddress to get the entry point for a specific function.
If it's a C++ library, you may have to care for the decorated names. The tools dumpbin and undname may help to identify what is really exported by the DLL.
|
6,033,456 | 6,033,859 | Efficiently maintain slightly different (logging/non-logging) functions | I have a number of algorithms for community detection on graphs that I want to now visualise them. This visualisation requires me to 'hijack' these algorithms while they execute and log what they are doing. Specifically this will mean passing a reference to a std::vector<graph_partition> as an argument to these algor... | If you fancy using templates, I don't think you really need variadic templates. If you're happy to recompile in order to switch logging on and off:
struct NoLogging {
void log(const graph_partition &) {}
};
struct Logging {
std::vector<graph_partition> vec;
void log(const graph_partition &p) {
vec.... |
6,033,601 | 6,033,677 | Deduce parameter pack w/out passing it explicitly as a template parameter? | Forgive any ignorance of C++ type deduction in this, but I'd like to be able to carry around the parameter pack's definition, so that later I could test for an inner type. Is this possible? Something like:
template <typename... Args> struct Entity {
struct Inner {
typedef Args... entity_args_t;
};
... | Define:
template<typename ...> struct types;
Then:
template <typename... Args> struct Entity {
struct Inner {
typedef types<Args...> entity_args_t;
};
struct SomeOtherInner {
typedef types<Args...> entity_args_t;
};
};
Then you can pass entity_args_t to a template that has a partial ... |
6,033,783 | 6,033,864 | problems importing a C++ dll | I am trying to access this C++ function from the C# code in my program
Tridiagonal3 (float** mat, float* diag, float* subd)
{
float a = mat[0][0], b = mat[0][1], c = mat[0][2],
d = mat[1][1], e = mat[1][2],
f = mat[2][2];
}
The call is as shown below
t... | Tridiagonal3 (float** mat, float* diag, float* subd)
mat is a double-pointer type (pointer to pointer).
In C#, float[,] is not a double-pointer. It's just syntactic sugar for accessing a multi-dimensional array, just like you would do mat[x + y * width] instead of mat[y][x];
In other words, you are passing a float* to ... |
6,033,970 | 6,034,027 | passing typedef (fixed sized) array by value | I am having hard time understanding typedef pattern for arrays.
typedef char Char10[10];
void fun (Char10 a) // not passing reference (interested in pass by value)
{
if(typeid(Char10) == typeid(char*))
throw 0; // <--- never happens
}
int main ()
{
char a[10]; fun(a); // ok
char b[11]; fun(b); // why w... | They are different types, you're right.
It's a misleading quirk of C++ that you can be seen to have a function
void fun(char a[10])
Since you cannot pass arrays by value, and C++ is silly, this is actually the function
void fun(char* a)
And, of course, both inputs degrade happily to char*.
It would be nice if C++ did... |
6,034,145 | 6,034,177 | C++ command line strings like Java? | Is there a way to get c++ strings from the commandline like in Java?
public static void main(String[] args)
where args is an array of C++ strings?
| Not precisely but you can come close easily.
#include <iostream>
#include <vector>
#include <string>
using namespace std;
typedef vector<string> CommandLineStringArgs;
int main(int argc, char *argv[])
{
CommandLineStringArgs cmdlineStringArgs(&argv[0], &argv[0 + argc]);
for (int i = 0; i < cmdlineStringArgs... |
6,034,156 | 6,034,375 | suggestions for improving an allocator algorithm implementation | I have a Visual Studio 2008 C++ application where I'm using a custom allocator for standard containers such that their memory comes from a Memory Mapped File rather than the heap. This allocator is used for 4 different use cases:
104-byte fixed size structure std::vector< SomeType, MyAllocator< SomeType > > foo;
200-b... | For the fixed sized objects, you can create a fixed sized allocator. Basically you allocate blocks, partition into subblocks of the appropriate size and create a linked list with the result. Allocating from such a block is O(1) if there is memory available (just remove the first element from the list and return a point... |
6,034,342 | 6,035,540 | CUDA - memcpy2d - wrong pitch | I just started CUDA programming, and was trying to execute the code shown below. The idea is to copy a 2dimensional array to the device, calculate the sum of all elements and to retrieve the sum afterwards (I know that this algorithm is not parallelized. In fact it is doing more work, then necessary. This is however ju... | In this line of your code:
cudaMemcpy2D(devPtr,pitch,testarray,0,8* sizeof(int),4,cudaMemcpyHostToDevice);
you're saying the source-pitch value for testarray is equal to 0, but how can that be possible when the formula for pitch is T* elem = (T*)((char*)base_address + row * pitch) + column? If we substituted a value ... |
6,034,478 | 6,034,582 | What is the most suitable way to return base object to up-casted derived class? | struct B {}; // B contains data members
struct D : B {}; // D doesn't contain ANY data member
B g_b; // global object
D& fun () // want to return by reference ONLY
{
return <???>(g_b); // how ???
}
[Note: I want to avoid overloading constructor (or assignment) such as D(const B&).]
| That is undefined behavior.
You can use dynamic_cast for performing safe down casting of Base class pointer/reference to derived class pointer/reference. It returns a null in case of pointers or throws an exception in case of references.
|
6,034,654 | 6,034,698 | static keyword useless in namespace scope? | namespace N
{
static int x = 5;
}
What could be the importance/use-cases of declaring having a static variable at namespace scope?
| Annex D (Compatibility features) [C++03]
D2: The use of the static keyword is deprecated when declaring objects in namespace scope.
Use unnamed namespaces instead as mentioned in this post.
static keyword imparts internal linkage to variables/objects in C as well as in C++ in namespace scope as others have mentioned ... |
6,034,689 | 6,034,782 | Connection to host by Unique id, not IP? | I'm trying to make a program in c++...some kind of server software. And i want to know is it possible to connect to server/host not by IP, but by a unique ID, something like TeamViewer one.
Later edit: I perfectly understand that it's the tcp/ip protocol. My problem is NAT. So smth. like directly entering the host's ip... | I think this is not exactly possible.
TeamViewer is based on TCP/IP, it enables remote connections over port 5900. That means, to connect two TeamViewer clients, you connect to a partner`s PC on port 5900.
Even if you introduce just a code, it might be a unique key based on the IP.
|
6,034,713 | 6,034,767 | Run "While loop" in background | I have a Credential Provider dll application in C++. Inside this dll i create a process that will write some data in a file. I need somehow to read that data from file till the value is > -1. I can not use a while loop because my dll will stop loading till the while loop will end. Can i use a separate thread to do this... | The only really practical way to achieve concurrency is using threads. Take a look at boost threads.
|
6,034,822 | 6,034,935 | Why do we need a pointer to a class if we can instantiate an object of it and access members of the class? |
I am a little confused here. If we can instantiate an object of a class and access member methods then why a pointer to a class? Is there any benefit to it? And when do we use a pointer to a class and when do we instantiate an object of it?
Thank you.
| You might not need a pointer to a class. If your class is small, doesn't exhibit polymorphic behavior through a base class, or cost anything to instantiate, you can probably just rip one off on-the-fly and be done.
But in many cases, we need pointers because:
The class is "big," as in, is expensive to instantiate or ... |
6,034,943 | 6,036,854 | Fatal Error in MPI_Wait | Here is the output for a source code implementation shown below. I am not sure what it means and how i should remedy the code.
aborting job:
Fatal error in MPI_Wait: Invalid MPI_Request, error stack:
MPI_Wait(139): MPI_Wait(request=0xffffd6a4, status0xffffd690) failed
MPI_Wait(75) : Invalid MPI_Request
rank 0 in ... | It looks like you're calling the MPI_Wait() even from rank 0, even though you're only doing nonblocking communications in rank 1 and 3. So there's no valid send_request in rank 0, so the MPI_Wait is invalid. In the above, it looks like you should have
if ( (my_rank == 1) || (my_rank == 3))
MPI_Wait(&send_... |
6,035,026 | 6,037,840 | How to avoid console output about unsupported operations ? (IWebBrowser2, DISP_E_MEMBERNOTFOUND) | CONTEXT:
I'm trying to use IWebBrowser2 to create little embedded browser for viewing local html files. I'm doing this with help of MFC and CWnd::CreateControl in particular. Everything works well, except one moment: When I clicking on html links I recieve messages (to Visual C++ debug console) about COleException has ... | cause: COleControlSite::GetStyle() check DISPID_ENABLED and DISPID_BORDERSTYLE, two dispatch ids that IE did not implement. The GetStyle call is right on the call stack.
solution:
Ignore the debug output, or
Derive a class from COleControlSite to override GetStyle, copy COleControlSite::GetStyle's implementation excep... |
6,035,360 | 9,347,181 | Code::Blocks and Lapack |
How do you add Lapack libraries to Code::Blocks IDE on Windows?.
The files I have are these: (Victor's Compiled binary libraries for Windows on this page:
http://www.stanford.edu/~vkl/code/libs.html)
lapack_win32.a
lapack_win32.def
lapack_win32.dll
lapack_win32.exp
lapack_win32.lib
How would look like a simple ... | First assuming you have installed these libraries in C:\LapackLib.
Click on the Settings Menu and then select the Compiler menu item.
From the Compiler Settings Dialog select the Directories Tab.
Click the Add button.
In the window that pops up type in your library path in this example it is C:\LapackLib\.
Select the ... |
6,035,404 | 6,035,883 | Qt locale formatting of large currency (or number) on linux | I am trying to format a number as a currency and having problems. I've tried with both the default locale and a specific one (like below). The number is formatted in scientific notation nonetheless.
QLocale::setDefault( QLocale(QLocale::English, QLocale::UnitedStates) );
reportCost->setText( QString("$%L1").arg( cost ... | Unfortunately, the current implementation of QLocale falls short in a lot of these areas. See "QLocale: It’s about time (and dates, and languages, and …)" for an explanation of where this is headed in the future.
For now, a quick-and-dirty solution would be:
QString("$%L1").arg(amt, 0, 'f', 2);
If you need real locali... |
6,035,547 | 6,035,658 | unordered_map insert error C++ | I am trying to insert into an unordered_map with a std::set value declared as such:
class Database {
...
private:
struct CountryRCID {
int RCID;
int Vote;
};
struct comp {
bool operator() (const CountryRCID& left, const CountryRCID& right) const {
return left.RCID < right... | CountryRCID is a type struct, it is not a std::set ... you would first need to construct a std::set of type std::set<CountryRCID> and use that in your arguments to makePair() in order to match the template arguments for your unordered_map.
I also think the struct comp functor is redundant ... just define operator<() an... |
6,035,555 | 6,035,752 | Emacs indent an extra level for every continued line | How do you tell emacs to indent the current continued line (e.g. after a dot or indirection operator) one level deeper than the previous one? Arguments about which one is prettier are irrelevant here since this is the style we use at my work, so I don't really have a choice.
I'm guessing it's an offset (maybe statement... | This is not possible with the built-in indentation options.
You can verify this by using C-c C-s (aka c-show-syntactic-information) on the lines where you want the /* extra indent */ and the line above them, and you'll see that the syntactic information for those lines is always the same. In other words, as far as the... |
6,035,845 | 6,035,884 | Simple C++ Inheritance Example, What's wrong? |
Possible Duplicate:
Function with same name but different signature in derived class
I'm trying to compile this and I can't figure out what is wrong with the code. I'm using MacOSX Snow Leopard with Xcode g++ version 4.2.1. Can someone tell me what the issue is? I think this should compile. And this is not my ho... | The presence of Child::func() hides all overloads of Parent::func, including Parent::func(string&). You need a "using" directive:
class Child : public Parent
{
public:
using Parent::func;
Child():Parent(){}
virtual ~Child(){}
virtual void func(){cout << "Child::func(" << this->str << ")" << endl;}
};
EDIT:
Or,... |
6,035,991 | 6,036,046 | C++ non-direct Inclusion Scenario | Ok, I have this scenario.
A class called a which includes windows.h.
#ifndef a.h
#define a.h
#include <windows.h>
class a
{
};
#endif
A class called b which includes windows.h.
#ifndef b.h
#define b.h
#include <windows.h>
class b
{
};
#endif
A main class as such.
#include "a.h"
#include "b.h"
MAIN STUFF
T... | #windows.h should be (read: is) clever enough that this is not a problem.
They use "header guards" to guarantee safety of multiple inclusion within a TU, the same way you did in your files a.h and b.h (though you should really pick better names for those guards... oh how easily they can conflict at present!).
To guara... |
6,036,227 | 6,036,308 | mkstemp() implementation for win32 | Can anybody point me to the code that implements mkstemp() (C/C++) on Win32, or very close analog.
Must be race-free.
It's supposed to look like
#include <windows.h>
#include <io.h>
// port of mkstemp() to win32. race-free.
// behaviour as described in http://linux.die.net/man/3/mkstemp
//
int mkstemp(char *templat... | You can use the following function which is extracted from wcecompat library (from file src/stdlib_extras.cpp)
/* mkstemp extracted from libc/sysdeps/posix/tempname.c. Copyright
(C) 1991-1999, 2000, 2001, 2006 Free Software Foundation, Inc.
The GNU C Library is free software; you can redistribute it and/or
m... |
6,036,292 | 6,036,855 | Select a graphic device in windows + opengl | I know how to open a window with openGL (using Win32 or other toolkits). But when the system have 2 graphics cards. How do I select a graphic device to render? My programming language is C++ and I'm focusing on windows but any sample will be welcome.
Edit: Maybe Its a good idea to explain my problem better, in order to... | I am not 100% sure, but I seem to remember that under Windows this is not possible, other than to create a window on a specific screen.
NVidia provided an extension called WGL_NV_gpu_affinity. I'm not sure if this is still available and whether it works as you would like.
Edit:
I see that similar information is alread... |
6,036,347 | 6,036,487 | Memory corruption with fftw mingw precompiled binaries and vs 2010? | I would like to know if anyone has never experienced memory corruption problems using precompiled mingw fftw binaries linked with visual studio 2010 project. The strange thing is that just the fftw libs linking (generated with lib /def:libfftw3-3.def as explained by fftw doc) brings troubles in my project even if none ... | I don't know that the fftw library is, so I'm not sure what it might specifically be doing to cause instability. It's possible for a DLL to execute code when it's loaded, so the fact that you're not actively calling it doesn't necessarily mean it's not doing anything.
However, MinGW links to the msvcrt.dll runtime tha... |
6,036,478 | 6,036,547 | clr:oldSyntax prevents ofstream | I have a fairly old unmanaged C++ program that called managed c# code (vs2003) that I need to convert. (the original c# code was written in .NET1.1, and needed to be recompiled, it was compiled into 4.0) While ultimately I need to have the entire thing re-written, I was hoping to get the original code to run a little... | If I'm not wrong VS has continued shipping with a 'legacy' iostreams library (the pre-standard version from Dinkumware). (reference) I'm not sure whether VS2003 still included it, but knowing Microsoft, I wouldn't be surprised.
It might still be in use and not be compatible with the new C++ standard library containers/... |
6,036,518 | 6,037,273 | Parsing a C# object into a C++ object | I need to use a DLL coded in C++ in a C# application, there is a method in the DLL with receives a object declared in the C++ and I don't know how to parse a equivalent object maded in C# to the function of the DLL
Can someone help me?
| You will need to use the System.Runtime.InteropServices namespace with Platform Invoke if the c++ code is not managed or COM. You will need to define the structure in your C# application and pass an object of whatever type your structure is to the method you are using Platform Invoke on. To tell you anymore, I need to ... |
6,036,903 | 6,037,022 | Real positional string formatting? | (Note: I know of Boost.Format, I'm looking for a better way to do the following.)
First a use-case example: In some countries, you name a person by calling his / her surname first and the forename last, while in other countries it's the exact opposite.
Now, for my code, I currently solve this with Boost.Format in the f... | In my opinion, Boost.Spirit.Karma is the definitive modern output formatting library.
|
6,036,965 | 6,037,692 | Simple text editor in Qt/C++ | I would like to write a simple text editor. I would like it to be GUI-based, and written using Qt.
Qt provides the class QTextEdit, which is a pretty fully-featured text editor (it supports ctrl+c, x , and z, text highlighting, and moving the cursor around left-right-top-down). I would like to write something similar, ... | I think you are best off taking a look at some of the code here: http://kde-apps.org/index.php?xcontentmode=241
Take a look at the code, try coding something of your own, and realise that Qt requires one to know C++ fairly well. You will, at the very least, need to understand classes and pointers. If that feels manag... |
6,037,059 | 6,037,803 | c++ compile-time string concatenation using boost-mpl | I'm trying to concatenate strings at compile-time using boost-mpl but am getting errors from gcc. Here's the sample -
using namespace boost;
using namespace std;
template<class A>
struct type {};
template<>
struct type<int> {
typedef mpl::string < 'i' > value;
};
template<>
struct type<char> {
typedef mpl::... | OK, as per your final edits, I see several problems here.
First, you can use mpl::push_back to add an element to a sequence. Now you're concatenating two sequences. I changed the type of type<>::value to mpl::char_, then changed the order of the mpl::push_back arguments (first the sequence, then the element). Also, you... |
6,037,114 | 6,037,241 | How to find maximum number of intersectionS through set of line segments | Suppose I am given number of lines segments in Cartesian coordinate system.Each line is given as [x0,y0] and [x1,y1].Algorithm should find a perpendicular that cross maximum number of lines.
In this example it crosses four lines:
What algorithm can do it with minimum complexity?(i would prefer c++ but some kind of ps... |
Convert each line to a interval of [x_start,x_end] for each segment.
Create a datastructure that contains a flag for whether it is a start or end point, as well as the point value.
Sort all the points and then iterate through them incrementing a counter when you hit a start point and decrementing a counter when you... |
6,037,338 | 6,037,416 | How to sort a Vector of type <class*>? |
Possible Duplicate:
C++ how to sort vector<class *> with operator <
Hello everyone!
Please i am trying to sort a vector of type "class" based on one of its data members. As follows:
The Header File: (Undirected_Graph.h)
#ifndef UNDIRECTED_GRAPH_H
#define UNDIRECTED_GRAPH_H
#include <vector>
using std::vector;
#i... | By default, std::sort uses using operator<, but you can also supply a comparison function object.
So:
bool your_comparer(const Edge * left, const Edge * right)
{
// return true if left should come before right, false otherwise
}
// ...
sort (myGraph.edges_List.begin(), myGraph.edges_List.end(), your_comparer);
|
6,037,580 | 6,037,605 | Restart application on unhandled exception | Is it possible to have a program restart automatically if it crashes?
Something like:
An unhandled exception is thrown.
Release all resources allocated by process.
Start over and call main.
I would like this behavior for a server application I'm working on. If clients miss use the server it can get a std::bac_alloc e... | I've done this before in Windows by running said program from another program via a win32 CreateProcess call. The other program then waits on the "monitored" process to exit, and calls its CreateProcess() again if it does. You wait for a process to exit by performing a WaitForSingleObject on the process' handle, which ... |
6,037,678 | 6,038,745 | C++ , Cheat Engine / OllyDBG finding base "static" address from multi-level pointers | I'm back again, frustrated and desperately searching for help :D.
I am trying to create a cheat for a simple program, it's basically going to be a .dll file which will change an integer's value from the main program when it's injected to it using its base address. The thing is, I can't find it using cheat engine mainly... | I think you are misunderstanding the goal of Cheat Engine.
CE allows you to modify values that are stored in a durable way in memory. For example, on the heap, or in the program's static data.
For example, C++ objects are allocated in a deterministic way, and hence, they never move. This is why they can be referenced b... |
6,037,947 | 6,038,006 | What is a correct formula of amplifying WaveForm audio? | I am wondering what a correct formula of amplifying WaveForm audio is from C++.
Let's say there's a 16 bit waveform data following:
0x0000 0x2000, 0x3000, 0x2000, 0x0000, (negative part), ...
Due to acoustic reason, just doubled the number won't make twice bigger audio like this:
0x0000 0x4000, 0x6000, 0x4000, 0x0000, ... | If you double all the sample values it will sure sound "twice as loud", that is, 6dB louder. Of course, you need to be careful to avoid distortion due to clipping - that's the main reason why all professional audio processing software today uses float samples internally.
You may need to get back to integer when finally... |
6,038,003 | 6,038,125 | Missing guiddef.h in project | I am new to Visual C++.
I am trying to use library A that in turn uses another library B. When I try to include the header of A, I get an "Error C2061: syntax error : identifier 'GUID'". This error is triggered in a header in library B. When I examine the line that throws the error, the issue is that the header in libr... | Don't know what you mean by add it to a project or create one that adds it ,but when guiddef.h is on your system and your directories (in common properties) to your MSVC environment are correctly setup ,you just have to add #include <guiddef.h> before the including of lib-headerfiles to your cpp or h files and everythi... |
6,038,137 | 6,038,254 | How can I do file i/o without fstream for competitions like google code jam? | Let me preface this question by saying I am not a very experienced programmer.
For competitions like google code jam, I write code like this:
#include <fstream>
using namespace std;
int main() {
ifstream fin("file.in");
ofstream oin("file.out");
//Etc. I'll now write out my solution.
//...
}
However,... | Imagine when you are using the shell in ubuntu. Almost everything is read by the console, cin and written to the console, cout. For instance
cat "file.txt" | grep "Hello"
cat would get the "file.txt" from the arguments given to main, i.e.
main(int argc, char ** argv){
// for the both cat and grep examples argc is ... |
6,038,160 | 6,038,248 | A way to enforce use of interface in C++ | In C++, let's say I have a class Derived that implements an interface class BaseInterface, where BaseInterface has only pure virtual functions and a virtual destructor:
class BaseInterface
{
public:
virtual void doSomething() = 0;
~BaseInterface(){}
};
class Derived : public BaseInterface
{
public:
Der... | I think you're looking for the non-virtual interface (NVI) pattern: a public non-virtual interface that calls a protected or private virtual implementation:
class BaseInterface
{
public:
virtual ~BaseInterface(){}
void doSomething() { doSomethingImpl(); }
protected:
virtual void doSomethingImpl() = 0;
};... |
6,038,312 | 6,038,449 | Assembler code in C++ code | How can I put Intel asm code into my c++ application?
I'm using Dev-C++.
I want to do sth like that:
int temp = 0;
int usernb = 3;
pusha
mov eax, temp
inc eax
xor usernb, usernb
mov eax, usernb
popa
This is only example.
How can I do sth like that?
UPDATE:
How does it look in Visual Studio ?
|
UPDATE: How does it look in Visual Studio ?
If you are building for 64 bit, you cannot use inline assembly in Visual Studio. If you are building for 32 bit, then you use __asm to do the embedding.
Generally, using inline ASM is a bad idea.
You're probably going to produce worse ASM than a compiler.
Using any ASM in ... |
6,038,372 | 6,038,388 | how to define const string in the c++ method | Inside class, I would like to define some const strings.however the compiler reports error when I use
class A {
static const std::string s = "test"
};
inside the class. How to do that? Do I have to define the const outside the class defination?
| I think you have to define it outside.
class A {
static const std::string s;
};
const std::string A::s("test");
|
6,038,430 | 6,049,564 | How do I call all functions from sub-classes when they were defined as pure virtual in the super-class? | The main question is how do I implement startTest() so that it calls runTest in all the subclasses. Thanks!
/*******************
COMPILER TEST
*******************/
class archeTest
{
protected:
short verbosity_;
public:
void setVerbosity(short v)
{
if( ((v == 1) || (v == 0) )
{
... | Since a lot of people were finding it difficult to follow through all the posts I listed. I implemented a version of this using boost.
The trick is the fact that when the definition for TestTemplate is expanded with the derived class definitions(new Test cases) it forces a call to the TestManager::Register method due ... |
6,038,431 | 6,038,493 | Inserting item into map, which holds 2 more map | I am trying to insert an item, into a map, which holds two other map.
map< map<int, int> , map<int, int> > GC;
map<int, int> A;
A.insert(pair<int,int>(1,1));
map<int, int>:: iterator p1 = A.begin();
map<int, int> B;
B.insert(pair<int,int>(2,3));
map<int, int>:: iterator p2 = B.begin();
GC.insert( pair< map<int,int>,... | I am not sure what are trying to achieve here .....
Your key and value needs to be an map object in order to work...
In that case only possibility is
GC.insert( pair< map<int,int>, map<int,int> > (A,B) );
|
6,038,718 | 6,038,889 | Convert integer to bits | I have byte to binary string function,
std::string byte_to_binary(unsigned char byte)
{
int x = 128;
std::ostringstream oss;
oss << ((byte & 255) != 0);
for (int i = 0; i < 7; i++, x/=2)
oss << ((byte & x) != 0);
return oss.str();
}
How can i write an int to bits in same way? I don't want ... | I'll just post this as an answer. It is shorter, safer and, what's most important, it is done.
#include <string>
#include <bitset>
#include <type_traits>
// SFINAE for safety. Sue me for putting it in a macro for brevity on the function
#define IS_INTEGRAL(T) typename std::enable_if< std::is_integral<T>::value >::type... |
6,038,727 | 6,039,057 | Values not passing properly? | I've been working on this project for a while, it's a new language for me but I had a partner with experience who kinda ditched me. Anyways, right now I'm having trouble with getting the text from one object to another. I instantiate an object in the game class, then try to get it and save it to another object in the m... | I tried your code on my computer, it seems that both the Question class and the Game class is correct, I also tried the Game::getQuestion() and the Game::getQuestionText() method, it's all correct, and returns the proper value.
By the way, there are no pointer members in the Question Class and the Game Class, so there ... |
6,038,882 | 6,038,952 | Examples of why declaring data in a class as private is important? | I understand that only the class can access the data so therefore it is "safer" and what not but I don't really understand why it is such a big deal. Maybe it is because I haven't made any programs complex enough where data could accidentally be changed but it just a bit confusing when learning classes and being told t... | Depends what you mean by "unintentional changes". All code is written by someone so if he is changing a member variable of a class then the change is intentional (at least from his side). However the implementor of the class might not have expected this and it can break the functionality.
Imagine a very simple stack:
c... |
6,039,231 | 6,039,298 | Help understanding const char* operators in c++ | I need to translate some code from c++ to java, and I am not so sure how to deal with the 'const char*' operators. Check code below:
const char* handText;
const char* index = strchr(handText, '-');
char handCeil[4];
char handFloor[4];
strncpy(handCeil, handText, index - handText);
strcpy(handFloor, index + 1);
What I ... | This
strncpy(handCeil, handText, index - handText);
strcpy(handFloor, index + 1);
is equivalent to
int index = handText.indexOf('-'); // I changed this for you
handCeil = handText.substring(0, index+1);
handFloor = handText.substring(index+1);
So it splits the string by the '-' and puts the first part (including the ... |
6,039,235 | 6,039,359 | Problem with cin.get() in C++? | I have the following code:
#include <conio.h>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
int x = 0;
cout << "Enter x: " ;
cin >> x;
if (cin.get() != '\n') // **line 1**
{
cin.ignore(1000,'\n');
cout << "Enter number: ";
cin >> ... | if (cin.get() != '\n'); // **Line 2**
// you have sth here -^
Remove that semicolon. If it is there, the if statement basically does nothing.
Also, you're not testing wether the user really inputs a number... what if I input 'd' instead? :)
while(!(cin >> x)){
// woops, something has gone wrong...
// display a mes... |
6,039,567 | 6,039,583 | const member function | I have following piece of code:
class Test{
private:
int id;
public:
Test(int v):id(v) {}
int getId() { return id;}; // however,I change this method signature
int getId() const { return id;};
and all the error... | bool operator()(const Test& t1, const Test& t2)
Your operator takes references to const Test objects. You can only call const-qualified member functions via a reference to a const-qualified type.
set<Test>::iterator it = s.begin()
The elements of a std::set are immutable: you cannot change them. Because of this, i... |
6,039,705 | 6,040,661 | Add Method to COM Interface | I created a ATL COM dll workspace with VS2008. It has generated MyCom.idl interface. Does it provide any easy way to add a method to this interface?
| Yes, there is an option to do that.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.