question_id int64 25 74.7M | answer_id int64 332 74.7M | title stringlengths 20 150 | question stringlengths 23 4.1k | answer stringlengths 20 4.1k |
|---|---|---|---|---|
7,133,348 | 7,133,386 | Benefit of using gcc4 over gcc34? | Is three any performance benefit of using gcc4 over gcc34 ?
Currently we are using gcc34 with old c runtime to support all old os.
So is there any performance benefit of using gcc4 ?
| As per Bench-marking tests run by RedHat for g++ (GCC-3.4.2) & g++ (GCC-4.x) on identical platform and enviornment,
For Compilation Performance:
gcc-4 is faster than gcc-3.4, by a significant margin.
For Executable Performance:
There is little difference between the two.
Check the bench-marking comparisons here
For y... |
7,133,426 | 7,134,008 | Assertion Error During Running the program | I made a program in Visual Studio 2008 using C++ language and MFC Files. It is a graphical user interface which store student records in a file using file handling of C++. It is working properly and shows or adds records but when I try to modify and delete records it will give a assertion error to me while running.
P... | You seem to have removed one or more controls from the dialog resource, and DoDataExchange is still referring them (via of one DDX_Control functions). Find out what those resources are, and remove the references of them from DoDataExchange.
Later you may remove those control IDs (IDC_) from resource.h altogether if the... |
7,133,600 | 7,200,300 | I want to create a minifilter driver to transparently redirect disk i/o, but I'm having trouble getting started | A project I'm working on at the moment requires the implementation of a copy-on-w/m mechanism which will be used to redirect disk i/o in a similar manner to Deep Freeze or Sandboxie, on Windows XP. If I could I'd also like to be able to "mount" the user's modified files, similar to how VirtualCloneDrive simulates disk ... | The WDK has all the examples you need on minifilters under samples/filesys/minifilter, they are decently documented, but a little confusing in parts. However, as mentioned in the comments, this need admin privilages to use used, but so does any form of patching or hooking(see SeDebugPrivilege)
|
7,133,687 | 7,133,865 | C++ Return to command input function | I'm trying to make a simple program that takes a user command, executes a function, then returns to the original function so the user can enter another command, much like windows command prompt. Upon browsing the similar questions I read that returning to main is not good programming so I want to ask:
How can I make a ... | After a function returns, control is returned to the calling function.
Example:
#include <iostream>
int other_function(){
std::cout << "In other_function...\n";
return 0;
}
int main(){
std::cout << "Calling other_function()...\n";
int ret_value = other_function();
std::cout << "Back in main. other... |
7,133,936 | 7,133,964 | Visual C++ build error: Failed to register output | So I have this project I'm working on, and every time I build, it builds then executes the program, and then finishes with a build error. Why does this happen? I can't seem to find in the project properties where it would execute the file on the build.
It is kind of annoying, and it also ends up spawning an error. Her... | Start with Visual Studio with Administrator rights. You can do so by right clicking on VS shortcut and Select Run As Administrator. Or create a shortcut where you would enable Run As Admin.
Reason:
Look at the error:
error MSB8011: Failed to register output. Please try enabling Per-user Redirection or register the comp... |
7,134,003 | 7,134,406 | Problems with last recursion in metaprogramming | I have the following (partial) code in a class where I try to evaluate a value against a list of values via metaprogramming in C++11.
bool eval(GLenum value)
{
return false;
};
template<GLenum One, GLenum... Others>
bool eval(GLenum value)
{
if( value == One )
return true;
// Try out the rest
... | Since this tends to produce lots of ambiguity errors, the variation that seems to work unambigously looks like this:
template<GLenum One>
bool eval(GLenum value)
{
return value == One;
};
template<GLenum One, GLenum Two, GLenum... Others>
bool eval(GLenum value)
{
if( value == One )
return true;
/... |
7,134,197 | 7,134,218 | Error with address of parenthesized member function | I found something interesting. The error message says it all. What is the reason behind not allowing parentheses while taking the address of a non-static member function? I compiled it on gcc 4.3.4.
#include <iostream>
class myfoo{
public:
int foo(int number){
return (number*10);
}
};
int main ... | From the error message, it looks like you're not allowed to take the address of a parenthesized expression. It's suggesting that you rewrite
fPtr = &(myfoo::foo); // main.cpp:14
to
fPtr = &myfoo::foo;
This is due to a portion of the spec (§5.3.1/3) that reads
A pointer to member is only formed when an explicit & i... |
7,134,261 | 7,135,001 | Strange C++ rule for member function pointers? |
Possible Duplicate:
Error with address of parenthesized member function
In this recent question the OP ran into a strange provision of the C++ language that makes it illegal to take the address of a member function if that member function name is parenthesized. For example, this code is illegal:
struct X {
void... | This is just a personal opinion.
If &(qualified-id) is allowed as &(unary-expression),
qualified-id has to be an expression, and an expression is expected to have a type
(even if it is incomplete).
However, C++ didn't have a type which denotes a member, had only
a pointer to member.
For example, the following code cann... |
7,134,353 | 7,134,484 | How do color and textures work together? | I must be asking a very basic question. I've just learnt how to apply textures.
Basically, I have a scene (a plane) and a cube on it. I apply a texture to one of the faces of the cube. The face of the cube I am trying to apply the texture to is red, but I want the texture color to override it, but they somehow blend to... | If you intend to draw one side of the cube with a texture, and the other sides without it, then you need to glEnable(GL_TEXTURE_2D) for the side with the texture and glDisable(GL_TEXTURE_2D) for the sides without it. That's not your problem, but it still needs to be done.
If you're trying to render with just a texture,... |
7,134,357 | 7,134,432 | How do I assign vector of vectors of strings using pointers to multiple vectors in C++? | I need help figuring out bits of code. I am not sure how to populate vector> using pointers to multiple vectors of strings.
Please make suggestions only on lines that contain //HELP NEEDED HERE
#include <iostream>
#include <string>
#include <vector>
using namespace std;
vector<string>* pointerReturner (string str1, ... | MakeList = new vector<vector<string> > ();
MakeList->push_back(*vMakeList1);
MakeList->push_back(*vMakeList2);
MakeList->push_back(*vMakeList3);
|
7,134,403 | 7,134,468 | using namespace std; in header file | Some people claim that using namespace std; is bad practice. Others say it's OK in it's place. But everyone agrees that putting it in a header file is verboten.
So dear reader, who can explain this from Bjarne Stroustrup's own web site.
http://www.stroustrup.com/Programming/Graphics/std_lib_facilities.h
He didn't even ... | Seeing as this is a course header, I think students are supposed to include it and then use most of the standard library that way. I am surprised Stroustrup teaches it that way (it is, in my opinion, still bad practice), but it does mean that he has one less bit of syntax to explain to his students. I don't think any... |
7,134,617 | 7,134,902 | About C++ template and explicit declaration | I just spent about an 20 minutes trying to figure out why some template methods of mine passed compilation but not linkage.
Turns out I needed to explicitly declare my template method.
It was something of this kind :
class Test {
template<class Source> void Save(Source& obj);
};
Then I would use it like this somewh... | In a nutshell, you need to have the entire body (the definition) of a template function visible to the translation unit that instantiates the template. So when you say t.Save(obj);, that translation unit should have access to the definition of Save. Usually you achieve this by including the definitions of function temp... |
7,134,686 | 7,134,716 | C++ enum EXC_BAD_ACCESS | I have a problem with the enumerations in c++
I don't understand why if I define two variables with the same enumeration it give EXC_BAD_ACCESS
do you have an idea why? if I define only one varible it is fine
here is the code...
enum directions{
UP,
DOWN,
RIGHT,
LEFT,
IN,
OUT,
FW,
RW
}... | There's not nearly enough information in your question to point you in any particular direction. However, it's almost certainly because somewhere else in your code there is some pointer manipulation that goes wild and ends up accessing something undefined. Changing the memory layout of objects (such as adding or removi... |
7,135,135 | 7,135,155 | Long double does not print as the constant I initialized it with |
Possible Duplicate:
Floating point inaccuracy examples
Im having a problem... When i compile the src, the variable showed isn't the same that i initialized, see it:
#include <iostream>
using namespace std;
int main()
{
long double mynum = 4.7;
cout.setf(ios::fixed,ios::floatfield);
co... | Your variable is long double, but the default precision of the literal 4.7 is only double. Since you're printing it as long double, the interpretation chooses to print it with enough significant digits to distinguish it from neighbouring long double values, even though those neighbouring values are not possible doubles... |
7,135,255 | 7,135,287 | overloading > as member function | I have written a relational operator < as member of class Test
bool Test::operator<(const Test& t)
{
if (a<t)
return true;
}
this code is in the header file, which I have included in my .cpp. However, when I compile my program, I get the following error:
test.h: 134:6: error: ‘a’ was not declared in this scope
... | You're supposed to be defining how a Test object may be compared to another object of type Test but in your code you do not define how, only that "a" - whatever that is, is less than the other object.
class Test
{
public:
Test(int myscore) { score = myscore; }
bool operator<(const Test &t);
int score;
}
bool Tes... |
7,135,390 | 7,135,793 | Using fprintf at a C++ code | I have an odd problem. When I try to compile the code below, it works without a failure as expected:
#include <iostream>
#include <Windows.h>
int main(){
FILE *f = fopen("trystl.geo","w");
fprintf(f,"Merge \"trystl.stl\";");
fprintf(f,"\n");
fprintf(f,"Surface Loop(2) = {1};");
fprin... | The error is simple: Line 55 in fprintf.c in VC++ is _VALIDATE_RETURN( (str != NULL), EINVAL, -1); and str is the FILE* parameter (I've seen better named variables though).
For the curious (I was) _VALIDATE_RETURN is defined as follows:
#define _VALIDATE_RETURN( expr, errorcode, retexpr ) \
... |
7,135,446 | 7,135,454 | Question about strings | I'm trying to make my program check for bad user input.
In this case, I only want digits. (No alphabet, etc.)
if (someStringHere.find_first_not_of("0123456789") == string::npos)
Is it correct to say that this piece of code will give me the implementation to do so?
Based on my knowledge, this returns true if the string... | Your implementation looks good to me.
The following isn't an exhaustive testcase, but it's enough to prove the point given that frankly it's obvious that your approach is good (assuming ASCII input).
<tomalak> geordi << isAllNums("12345"), isAllNums("a3234e"), isAllNums("abcdef"); bool isAllNums(const std::string& str)... |
7,135,595 | 7,135,617 | Don't understand how variable I is getting assigned a value in a struct | I have the following code:
#include <iostream>
using namespace std;
struct S {
S(int i): I(i) { }
int & v () { return I; }
private :
int I;
};
S s1 (1);
int main() {
cout << s1.v() << "\n";
return 0;
}
And I get the output:
1
I am confused as to how it is working. For example with s1 it i... | It seems you have multiple questions:
The struct is not subclassing I, it is simply using Initialization Lists to construct the I variable. The same could have been done with the constructor S(int i) { I = i;}.
It is getting assigned in the constructor, see #1.
You are confusing references and pointers. References pr... |
7,135,598 | 7,202,837 | How to write data in >4GB file with C++? | I'm trying to write a large file, but ran into a problem.
I use long long for seeking a place to write, but can't write file more than 4,2Gb. What I forgot?
More details:
I open 4Gb-file:
ifstream ifs(db_name.c_str(), ios_base::binary);
if (!ifs)
throw Bad_archive();
ifs.read(as_bytes(seg_size), sizeof(int));
ifs.... | fseeko64 (Filename, 0, SEEK_END);
long size = ftello64 (Filename);
fclose (Filename);
For accessing the large files , fseek cannot be used , instead have to go for fseeko64();
|
7,135,838 | 7,135,852 | Pointers not actually pointing to objects themselves? | I currently have a vector of a class Foo and another vector of pointers that point to a subset of the Foo's in the vector. I currently have a function that selects some pointers from the vector<Foo *> and deletes them from the vector<Foo> that actually contains them. Thus, at the outset, the two vectors look like this:... | A vector stores its elements in an array. An array is a contiguous sequence of elements.
If you have a vector containing elements a, b, c, d and remove element b, then elements c and d are moved down one index in the array to fill the hole created by the removed element, leaving an array containing a, c, d.
The pointe... |
7,135,842 | 7,135,926 | Converting date class to string | I have a Date class
class Date { int dd, mm, yyyy};
I have written the rule of 3, and all that works. I want to convert the Date into a string. Do I need a conversion operator string() to do so?
thx!
| When I want to make a text representation of an object available, I usually write a (public) print() method that takes a std::ostream&. This makes it easy for me to unit test and it exposes the private data without needing to make friends.
void Date::print(std::ostream& s) const
{
s << yyyy << "-" << mm << "-" << d... |
7,136,023 | 7,137,151 | In a full specialization, why does inheritance make a forward declaration (without definition) no longer sufficient? | Why is it that in the code below template<typename T> struct Child : public Parent requires a definition, whereas template<typename T> struct Orphan does not require one (but the presence of one does not hurt)?
#include <iostream>
struct Parent {};
// A definition is necessary.
template<typename T>
struct Child : pub... | template<typename T>
struct Orphan;
This is a perfectly normal forward declaration.
I suppose the language simply forbids forward declarations containing declaration of the parent. Such a syntax doesn't exist.
So it doesn't have much to do with templates. You can't do the following either
class Base {};
class Derived... |
7,136,101 | 7,136,485 | c++ template containing object using same type T | I have a class MemoryPool with the following (shortened to relevant) code:
namespace System
{
template <class T>
class MemoryPool
{
public:
// only constructor
MemoryPool(const size_t itemsToInitNow, const size_t maxItems)
: _maxItemsInMemoryPool(maxItems)
{
... | You've cut out a lot of your code, but at a guess, you have something like this:
template<typename T>
class AbstractFactory {
// ......
template <typename T>
inline const std::shared_ptr<T> CreateItem()
{
return std::shared_ptr<T>(new T);
}
};
The inner template hides the outer value of T - to ... |
7,136,135 | 7,186,468 | How to cast back Boost::thread::id from string? | So I casted boost::lexical_cast<std::string>(boost::this_thread::get_id()) this thread id to string. Now I wonder is it possible to turn it back into thread::id?
| Since you mentioned calling ->interrupt I assume you need the boost::thread object, not the boost::thread:id object.
Your best option might be to create a mapping of string - boost::thread objects when spawning threads.
|
7,136,279 | 7,136,323 | count the number of distinct absolute values among the elements of the array | I was asked an interview question to find the number of distinct absolute values among the elements of the array. I came up with the following solution (in C++) but the interviewer was not happy with the code's run time efficiency.
I will appreciate pointers as to how I can improve the run time efficiency of this cod... | std::find() is linear (O(n)). I'd use a sorted associative container to handle this, specifically std::set.
#include <vector>
#include <set>
using namespace std;
int distict_abs(const vector<int>& v)
{
std::set<int> distinct_container;
for(auto curr_int = v.begin(), end = v.end(); // no need to call v.end() mu... |
7,136,344 | 7,138,243 | Want to translate/typecast parts of a char array into values | I'm playing around with networking, and I've hit a bit of a road block with translating a packet of lots of data into the values I want.
Basically I've made a mockup packet of what I'm expecting my packets to look like a bit. Essentially a Char (8bit value) indicating what the message is, and that is detected by a swi... | Was talking to one of the programmers I know on Skype and he showed me the solution I was looking for.
playerPosition.X = *(int*)(bufferIncoming+3);
I couldn't remember how to get it to work, or what its called. But it seems all good now.
Thanks guys for helping out :)
|
7,136,400 | 7,136,405 | How does boost::lexical_cast take only one template type? | I've looked through the mess that is lexical_cast.hpp and this continues to escape me.
How is lexical_cast, whose 'base definition' takes both a template source and destination, able to accept grammar such as lexical_cast<int>("7")? I don't see how it can only need a templated return type and not need you to give the t... | Template arguments can be deduced from the function arguments:
template <typename T>
void foo(const T& x)
{
// T is the type of X
}
foo(5); // T is be int
foo("hello"); //T is const char[6]
|
7,136,450 | 7,136,516 | Using .dll in Visual Studio 2010 C++ | I have a problem. I place my .DLL and .LIB file in the same directory as my project, go to Properties -> Common Properties -> Framework and References -> Add New Reference. But the list comes up empty.
Is there something else I should be doing?
| C++ is not C#. You don't include .dlls in C++ applications by adding "references". Unless it's C++/CLI, but that's not C++.
In C++, you would go, in the project configuration, to Linker->Input->Additional Dependencies. There, you would list the library name plus path to the .lib in question.
Normally, when you build a ... |
7,136,581 | 7,136,678 | Searching for Points close to a Vector in 3D space | I'm terrible with math, but I have a situation where I need to find all points in a 3D space that are arbitrarily close to a vector being projected through that same space. The points can be stored in any fashion the algorithm calls for, not that I can think of any particularly beneficial ordering for them.
Are there ... | You would probably want to store your points in some spatial data structure. The ones that come to mind are:
oct-trees
BSP trees
kd-trees
They have slightly different properties. An oct-tree divides the entire world up into 8 equally sized cubes, organized to themselves form a larger cube. Each of these cubes are the... |
7,136,712 | 7,136,742 | Read word by word from file in cpp | I tried to read word by word from a file and store it in corresponding array in cpp. I am facing problems in executing it. Can you guys help me find the problem. This is my code
void Read_file()
{
int i=1;
ifstream in_file("cust_details1.txt");
if(in_file.is_open())
{
cout<<"List of all bills:\n"<&... | Your while loop should look like this:
while(in_file >> ac_no[i] &&
in_file >> ac_name[i] &&
in_file >> ac_amount[i] &&
in_file >> ac_emi[i] &&
in_file >> ac_sanc[i])
cout<<"Accout no = "<<ac_no[i]<<" Name = "<<ac_name[i]<<" Amount = "<<ac_amount[i]<<" Emi = "<<ac_emi[i]<<" Sanction = "<<a... |
7,136,755 | 7,136,783 | Lagrange Polynomials | I have worked in C language, but now i have been given this work where i will have to use C++.
I have to generate lagrange polynomials. Now, i wont ask for the code or anything but i want to know a few of things:
How do i go about this code: I ask the user to enter the data (i.e. the x and y coordinates) around which ... | you can pretty much write C and compile it as C++. There might be some exceptions, but hopefully the compiler or a bit or Internet poking should help you there. C++ is a non-strict superset of C.
That said, if you are willing to invest some time in learning the particular facilities of C++, you'll probably find it rewa... |
7,136,760 | 14,287,880 | Qt QDialog Issue : QLineEdit Will Not Take Input | I have this basic Qt program that comes from the "C++ GUI Programming with Qt" book. However, when I follow the instructions (which differ since the book was written for Qt 4.4) my QLineEdit will not display text input from the keyboard.
The source code is as follows (I did not include the moc_*.cpp files).
For those t... | I recently had similar problem.
This is how I solved my issue:
mainwindow->centralWidget()->releaseKeyboard();
|
7,136,818 | 7,136,911 | Can I store some user data in every item of a QListWidget? | I want to store some filenames in a QListWidget. I need to have the full file paths, but I only want to show the base filename. I probably could store the full filename in the tooltip for each item, but I'd rather not have tooltips for the list items.
| You can set data for and get data from each QListWidgetItem. See QListWidgetItem::setData() and QListWidgetItem::data(). Data can be set for different roles. Use Qt::UserRole, which is "The first role that can be used for application-specific purposes."
Try something like this:
QListWidgetItem *newItem = new QListWidge... |
7,136,932 | 7,136,938 | Debug why does size_t not work as a data member? | Can somebody tell me why the first program crashes, yet the second one doesn't?
First one (crashes):
#include <cstdlib>
class test
{
public:
test(const char *cstr)
{
size_t j=0;
while(cstr[n++])
;
//n = j;
}
private:
size_t n;
};
int main()
{
test("Hello, world!\... | Quite simply because in your first example the constructor uses n before it's ever initialized (actually, n never gets initialized).
So the line
while(cstr[n++])
is undefined behavior.
Try:
test(const char *cstr) : n(0) // <-- initialize n
{
size_t j=0;
while(cstr[n++])
;
//... |
7,137,227 | 7,137,338 | why does allocator in c++ need a copy constructor? | It is said here that it's because of exception specification. I do not understand it. Does this question have any relationship with exception specification?
| After reading through the tutorial I was a little confused myself by the wording. But I believe it's as simple as this: the tutorial was explaining why the allocator's template header shows
allocator(const allocator&) throw();
and
template <class U> allocator(const allocator<U>&) throw();
even though the copy construc... |
7,137,243 | 7,137,399 | How can Visual Studio use boost::function with /GR- while GCC can't with -fno-rtti? | I recently started porting an application to Android using the NDK and I encountered the following error:
boost/function/function_base.hpp:220: error: cannot use typeid with -fno-rtti.
Ordinarily, I wouldn't think twice about that error, but the visual studio project file set /GR-, which disables RTTI and has no probl... | I'm not booted into my Windows partition, but it was just as simple to look this up in MSDN.
As per this link on MSDN:
If the expression is dereferencing a pointer, and that pointer's value
is zero, typeid throws a bad_typeid exception. If the pointer does not
point to a valid object, a __non_rtti_object exception... |
7,137,296 | 7,138,083 | Find length in characters of a std::wstring | I am working with std::wstring variables (C++ Language) & I am trying to determine the length(in characters) of the string.
The functions .length & .size() give results that aren't the length in characters(I think they tell me how many wide chars there are?).
So is there a way to determine the length in characters of a... | Depending on where your string comes from, you may not have any control over what it means, i.e. how it is encoded. To turn your string into something definite semantics, you may have to perform the following steps:
Read byte string from the environment via argv or getenv. This is a byte string with platform and local... |
7,137,315 | 7,144,080 | Is there a way to automatically manage memory allocated by native code with js-ctypes? | I've inherited a Firefox add-on which badly needs an update to the new Firefox 4+ line. I finally have some time to work on it, but it turns out that this add-on includes a native portion compiled as an XPCOM component, and XPCOM components are now strongly discouraged. Since I really don't want to recompile my binarie... | Unfortunately for you, it's an important concept in JavaScript that you cannot observe garbage collection (at least not from JavaScript itself). The only place where you have destructor-like functionality is XBL. In other words, you could define a XUL element that would serve as your wrapper object (similar to how <str... |
7,137,844 | 7,137,880 | Pass by reference declarations in C++ | I want to establish whether my understanding to some basic C++ reference principles are correct. To my understanding, declaring;
void foo(string &arg); //Means get the memory reference of passed argument
{
cout << arg;
}
string arg;
string& arg1; //Means pass the memory reference of arg
Am I correct?
EDIT... | string str;
string &arg1 = str;
string& arg2 = str;
string *ptr = &str;
Means arg1 & arg2 are references to a variable str which is of the type string, it means they are just an alias name for variable str.
They Both essentially declare a reference variable as said above it is just a matter of style where the & is p... |
7,138,037 | 7,138,328 | debug error in visual studio | can somebody please explain me what am I doing wrong here, I receive an error unexpected end of file and also missing function header, thanks in advance
static char debug[256];
#define DBGPRINT(...) {sprintf_s(debug, 256, __VA_ARGS__); OutputDebugStringA(debug);}
#define CHECK_READ(status, str) while(0){ ... | OK here's the real answer.
I copy and paste from your code above, and you have trailing whitespace on one of your macro definition lines
if(0 == status){ \ WHITESPACE HERE
For a blackslash to operate as a line continuation character, it must be the last character on the line, no whitespace afterwards. N... |
7,138,063 | 7,138,459 | Efficient cache and BLOB's - profiling cache hits/misses | For a program to be cache efficient the data used should be stored linearly right?
So instead of dynamic allocation I put my data in a blob using a linear allocator. Is this enought to improve performace? what should I do to improve cache efficiency even more?
I know that this questions arent specific but I don't know ... | If your looking for a profiler for windows, you can try AMD's CodeAnalyst or VerySleepy, both of these are free, AMDs is the more powerful of the two however( and works on intel hardware, but iirc you can't use the hardware based profiling stuff), it includes monitoring of things like branch prediction misses and cache... |
7,138,178 | 7,138,365 | Convert octal representation of a number to decimal | Assume one has an vector or array of N elements (N can be very large) containing the octal representation of a non negative integer. How do I get the decimal representation of the number from this array? The code has to be really fast.
EDIT: array A of N elements contains octal representation of a non-negative integer... | This is what I came up with:
template<typename Iter>
int read_octal(Iter begin, Iter end)
{
int x = 0;
int f = 1;
for (; begin != end; ++begin)
{
x += *begin * f;
f *= 8;
}
return x;
}
int main()
{
int test[] = {2, 6, 3};
int result = read_octal(test + 0, test + 3);
... |
7,138,234 | 7,138,275 | Why are inline constructors and destructors not a good idea in C++? | I remember reading in one of the C++ books (quite some time ago) that it is not a good idea to have inline Constructors and Destructors especially for derived class.
I understand that inlining would induce some bloating up of object code but are there any other design considerations that discourage inline constructors... | The compiler is free to inline code that you have not declared inline, and is free not to inline code that you have declared inline. I have seen compilers do both of these things. Because of this the inline keyword does not mean what most people think it does. It's meaning is to allow an exception to the one definition... |
7,138,253 | 7,139,229 | Open source library for voice based command activation | I need to develop an embedded device which can identify voice commands and then effect an operation. I plan to use C++. Which open source libraries can I use for speech processing?
| Pocketsphinx library is designed specifically for embedded low-resource devices
See
http://cmusphinx.sourceforge.net
Read the tutorial
http://cmusphinx.sourceforge.net/wiki/tutorial
|
7,138,360 | 7,138,390 | unexpected behavior on casting | I have a doubt about how C++ casts types when it has to do math.
The code below as it is ( i.e. with only the cast to int without casting to double ) works and builds without problem. If I define ENABLE_DOUBLE_CAST doesn't build and complains about operator*. Do you know why?
The doubts I have are 2:
why without the... | why without the operator cast to double, it is used the one to int in a multiplication between double. Is it because of the implicit cast?
Yes that is true.
It uses the operator int () to convert obj_2 to an int and then uses the inbuilt operator*(double, int)
why WITH the cast to double enabled ( adding more clarity t... |
7,138,376 | 7,138,496 | The C++11 way of initializing data members from arguments | Seeing as C++11 supports move semantics, when initializing data members from arguments, should we attempt to move the value instead of copying it?
Here's an example showing how I would approach this in pre-C++11:
struct foo {
std::vector<int> data;
explicit foo(const std::vector<int>& data)
: data(data... | My initial answer to your question was:
Don't copy data that you want to move. You can add a constructor using a rvalue reference, if performance is a problem:
explicit foo(std::vector<int>&& data)
: data(std::move(data)) // thanks to Kerrek SB
{
}
Not exactly matching your question, but reading
Rule-of... |
7,138,392 | 7,138,417 | rvalue references in Visual Studio 2010 | What are the differences between rvalue references as implemented in Visual Studio 2010 and as specified in the C++11? Are there any particular pitfalls to watch out for when using revalue references in Visual Studio 2010 that could make source invalid or working differently if compiled by C++11 conforming compiler?
| According to this table, VS2010 supports rvalue references version 2.0 (the current version is 2.1 IIRC).
The important difference between 2.0 and 2.1 is that the latter allows implicit conversions:
std::string&& x = "hello"; // legal in 2.1, illegal in 2.0
Also note that VS2010 does not yet support overloading on t... |
7,138,588 | 7,138,692 | C++11 auto: what if it gets a constant reference? | Please take a look at the following simple code:
class Foo
{
public:
Foo(){}
~Foo(){}
Foo(const Foo&){}
Foo& operator=(const Foo&) { return *this; }
};
static Foo g_temp;
const Foo& GetFoo() { return g_temp; }
I tried to use auto like this:
auto my_foo = GetFoo();
I expected that my_foo will be a constant r... | Read this article: Appearing and Disappearing consts in C++
Type deduction for auto variables in C++0x is essentially the same as
for template parameters. (As far as I know, the only difference
between the two is that the type of auto variables may be deduced from
initializer lists, while the types of template ... |
7,138,657 | 7,140,228 | developing plugins: DX or VST? | I'd like to get into plugin development using C++. Am undecided between developing VSTs or DXs. What are the considerations? I know that some hosts more readily support one format or the other (Cubase:VSTs, Cakewalk:DXs), but that's all I'm aware of.
Thanks in advance!
| Go VST all the way. Many more hosts support it, and it makes it easier to port to other platforms to the future (ie, Mac OSX or Linux). With DX you are essentially tied to Windows and the small handful of hosts which support it.
Furthermore, VST is much more widespread, meaning that there is a larger number of plugin d... |
7,138,720 | 7,138,737 | Why can't char** be the return type of the following function in C++? | I have the following function in C++ :
char** f()
{
char (*v)[10] = new char[5][10];
return v;
}
Visual studio 2008 says the following:
error C2440: 'return' : cannot convert from 'char (*)[10]' to 'char **'
What exactly should the return type to be, in order for this function to work?
| char** is not the same type as char (*)[10]. Both of these are incompatible types and so char (*)[10] cannot be implicitly converted to char**. Hence the compilation error.
The return type of the function looks very ugly. You have to write it as:
char (*f())[10]
{
char (*v)[10] = new char[5][10];
return v;
}
... |
7,138,726 | 7,138,775 | Question about c++ naming conventions | I'm trying to create a abstraction layer for platforms such as win32, mac os, linux, iOs etc.
I want this to be dynamically linked. On platforms that don't support this it shouldn't be a problem since from what I've seen everything that can be compiled as a dynamic library can be compiled as a static one as well with m... |
I use a function named CreateThread that's defined with extern "C" to be able to export it and call it outside the library.
This is bad. I can't talk for other platforms, but on windows it's perfectly fine to export C++ functions. They are just get mangled, and you get some sanity checking in case someone changes th... |
7,138,780 | 7,138,986 | Move semantics & returning const values | I have the habit (?!?!?) of returning everything as a "const" value. Like this...
struct s;
s const make_s();
s const &s0 = make_s();
s const s1 = make_s();
With move operations and r-value references and the following functions...
void take_s(s &&s0);
void take_s(s const &&s0); // Doesn't make sense
I can no lo... | You have two conflicting goals. On one hand, you want to prevent modifications from being made to the returned object, but on the other hand, you want to allow modifications to be made (that's what a move operation is. It modifies the source object, by stealing its internal resources).
You need to make up your mind. Do... |
7,138,960 | 7,138,981 | How do I convert vector of strings into vector of integers in C++? | I have a vector of strings. Need help figuring out how to convert it into vector of integers in order to be able to work with it arithmetically. Thanks!
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main(int argc, char* argv[]) {
vector<string> vectorOfStrings;
vectorOfStrin... | There are mulitple ways of converting a string to an int.
Solution 1: Using Legacy C functionality
int main()
{
//char hello[5];
//hello = "12345"; --->This wont compile
char hello[] = "12345";
Printf("My number is: %d", atoi(hello));
return 0;
}
Solution 2: Using lexical_cast(Most Appr... |
7,139,138 | 7,139,158 | C++/W32 Sharing Class - code design question | Here is what i am trying to do.
I have Three Classes:
1) CEngine
2) CLogManager
3) CWindowGL
Ad1.
This class 'does' the tricky things to get the game engine going,
an application utilizing it, can call only few public members to
get the game going -
class CEngine
{
public:
CEngine();
~CEngine(); // should t... |
I can't do this by adding "Instance()" type of method as this would cause my CLogManager to generate new filename each time when a constructor is called.
Actually no, the constructor would be called only once during your program lifetime. The singleton pattern is what you most likely want for your logging class.
|
7,139,280 | 7,140,479 | Strange result following glUnproject and redrawing a scene | For an algorithm I'm writing I need to unproject my screen coordinates and reproject them into lightspace. This goes as follows: I fill the depth buffer viewing from my eye point (using glLookAt), I then unproject all visible pixels to world space. Then I reproject them into light space.
I was checking everything to ma... | This looks like you've not properly set your pixel store parameters (stride, alignment, the like), notably the PACK parameters. Have a look at http://www.opengl.org/sdk/docs/man/xhtml/glPixelStore.xml for the full set of options. In your case you want to set
glPixelStorei(GL_PACK_ALIGNMENT, 1);
glPixelStorei(GL_PACK_R... |
7,139,311 | 7,139,668 | Compile and run OpenMPI program | The cluster I am using has several host types - different distributions/versions of Linux, some 32 bit, some 64 bit, different versions of GCC. I know that I should compile my program with platform specific MPI wrapper for GCC. This step is more or less clear to me.
My program uses fixed number of hosts and each host r... | You need passwordless SSH access to all machines, a hostfile, the executable on all machines.
Make sure the executable has the same (relative) path on all machines.
Hostfile (on the master machine):
# my_hostfile
192.168.0.205
192.168.0.208
Command for Open MPI:
mpirun --hostfile my_hostfile programname
For password... |
7,139,323 | 7,139,357 | What macro does Clang define to announce C++11 mode, if any? | What macro does Clang define to announce C++11 mode, if any?
GCC defines __GXX_EXPERIMENTAL_CXX0X__, at least some versions do. MSVC seems to have the support turned on by default at least for _MSC_VER >= 1600.
| It uses different preprocessor tests for each separate feature, like
#if __has_feature(cxx_decltype)
for testing if decltype is implemented.
See the complete list here
http://clang.llvm.org/docs/LanguageExtensions.html#checking_upcoming_features
|
7,139,559 | 7,140,309 | How to implement QSizeGrip in a Qt frameless window? | How can I implement QSizeGrip with a Qt frameless window?
What would the code be like?
| You just have to add a QSizeGrip in a corner of your window inside a layout to make it stay in that corner.
QDialog *dialog = new QDialog(0, Qt::FramelessWindowHint);
QVBoxLayout *layout = new QVBoxLayout(dialog);
// To remove any space between the borders and the QSizeGrip...
layout->setContentsMargins(QMargins... |
7,139,622 | 7,139,748 | reading an integer from a string | I am reading a date from the db as a string. I want to break it down into integers so I can pass it to my Date constructor, so I used the following:
int y,m,d;
sscanf(test,"%d-%d-%d",&y,&m,&d);
cout<<"date is: "<<y<<"-"<<m<<"-"<<d<<"\n";
Date cdr;
cdr=Date(d,m,y);
setDate(cdr);
cout<<"cdr is "<<cdr.getDay();//... | Looking at the Date class posted in the comments above the error is here
class Date
{
...
Date(const Date& dd){}
Date& operator=(const Date&){}
...
};
Delete both of those methods and the code might work.
|
7,139,825 | 7,139,909 | Colormap library for C++ which converts a given value into red, green and blue values | I'm looking for a colormap library which converts a given value into red, green and blue values. Similar to the colormap feature of matlab [1]. Preferrably in C++.
[1] http://www.mathworks.com/help/techdoc/ref/colormap.html
| In think this is way too simple for a library personally i've implemented it my self their is the example in C (you can look up wikipedia for the math explanation):
/**
* Computes the color gradiant
* color: the output vector
* x: the gradiant (beetween 0 and 360)
* min and max: variation of t... |
7,139,878 | 7,140,028 | How to make " #using <System.DLL>" work in Qt? | How can I check if a process with a given name ("PowerPNT") is running?
After further web research, I've concluded that there is no Qt function which is able to do it :(, so I had to use a Win32 function, "GetProcessesByName" as described below.
#using <System.dll>
#include <windows.h>
int main()
{
...
if ( Sys... | This is C++/CLI which runs under .NET. You need plain C++ for your Qt project, presumably.
|
7,140,042 | 7,140,057 | C++ functor as a function pointer | I have a Functor which I need to send to a function which receives a function pointer as a parameter (such as CreateThread).
Can I convert it to a static method address somehow? And if not, how can I do it?
| No, you can't convert a class-type object to a function pointer.
However, you can write a non-member wrapper function that calls the member function on the right instance. Many APIs, including CreateThread, allow you to provide a pointer that it will give back to you when it calls your callback (for CreateThread, this... |
7,140,044 | 7,140,129 | What does it mean by implementing a DOM | I came across this phrase "implementing a DOM" and want to ask what does that mean exactly?
I think DOM is implemented by C++ in most browser. and DOM API is exposed to users through Javascript? So what does it mean to implement the DOM using PHP/Java or even Javascript such as jsdom did.
A more specific question is w... |
I think DOM is implemented by C++ in most browser. and DOM API is exposed to users through Javascript?
Maybe. I'm sure that Internet Explorer uses MSXML for manipulating the DOM. As it's a set of COM components, it is available for use in many different languages. It's likely that this implementation is written in... |
7,140,130 | 7,140,148 | Ambiguous call (conversion from char* to lambda vs std::string) | According to my compiler gcc-4.6 the call to func in the example below is ambigous.
void func(const std::string &str) {
}
void func(std::function<std::string()> f) {
}
void test() {
func("Hello");
}
Is the compiler correct in saying this? If I remove the first overload this code won't compile as it will fail to ... | You could also add a third overload to explicitly capture the string literal case:
void func(char const* cstr) {
return func(std::string(cstr));
}
|
7,140,294 | 7,140,372 | C++ Function templates with templatized arguments | I am trying to write a function which can take any of the standard containers(list, stack, vector etc) as it's arguments. I also wish to know the type that is within the container. Here is what I have tried.
#include<iostream>
#include<list>
#include<vector>
template<class data_type, template<class> class container_... | Your code won't work, because as soon as someone swaps out the allocator or something like that, then you're done for. You should take any T and use ::value_type, if in C++03, or type deduction in C++0x.
Also, .name() isn't defined to return anything useful, at all. In any situation. An implementation could return "har... |
7,140,336 | 7,140,440 | deadlock problem with threads in GTK | In my GUI, I have a list store treeview in my main window. When the user double clicks a row, a dialog pops up. The problem is that the data I populate in the dialog box takes a while to process, so what I've done is started a thread (using boost threads) to do the dialog box calculations.
In main:
.......
g_signal_con... | I think this is beause GTK_IS_COMBO_BOX probably calls gdk_threads_enter()
I don't think this is the case. These macros are generally pretty simple and I wouldn't expect it to take a lock. In fact, as far as I can tell the whole idea of gdk_threads_enter is that the library itself shouldn't call this, only code that ... |
7,140,793 | 7,140,961 | how to convert pugi:char_t* to string? |
Possible Duplicate:
How to convert pugi::char_t* to string
how can I convert pugi:char_t* type to wchar_t string?
I want to compare the result of child_value() to some utf8 string and without that convertion I cant do that.
for (pugi::xml_node_iterator it = words.begin(); it != words.end(); ++it)
{
wcha... | Here's an idea. The crude version involves modifying the library, which may break stuff in the future, but let's begin with that:
We already have these two functions:
std::string as_utf8(const wchar_t* str);
std::wstring as_wide(const char* str);
We also know that pugi::char_t is either char or wchar_t. So all we need... |
7,140,943 | 7,140,974 | How to serialize numeric data into char* | I have a need to serialize int, double, long, and float
into a character buffer and this is the way I currently do it
int value = 42;
char* data = new char[64];
std::sprintf(data, "%d", value);
// check
printf( "%s\n", data );
First I am not sure if this is the best way to do it but my immediate problem is determinin... | In C++ you can use a string stream and stop worrying about the size of the buffer:
#include <sstream>
...
std::ostringstream os;
int value=42;
os<<42; // you use string streams as regular streams (cout, etc.)
std::string data = os.str(); // now data contains "42"
(If you want you can get a const char * from an std::... |
7,140,958 | 7,143,961 | Object initialization and object factories in C++ | I'm quite new to c++ development and design and so I apologize in advance in my question is vague or poorly structured. I have several distinct and unrelated hierarchies in my code and I would like to use a generic factory as described and implemented by Alexandrescu to instantiate objects from these hierarchies .
... | You are hurtling down the Over-Engineering highway... head first.
Factories are seldom required, and no two Factories are alike (as you noticed).
It is useless to try and provide a base class for all your Factories, because this base class will have no clear semantic. What does it build ? Birds ? Cars ? They are unrela... |
7,140,994 | 7,184,022 | overlaping QGraphicsItem-s hover events | I have more QGraphicsItems on top of each other. How can I make hover event available for all items? Only the last added item (the one on the top) accepts hover events.
Thanks
| You could simulate those events, you "just" have to:
reimplement mouseMoveEvent in a QGraphicsView or QGraphicsScene derived class,
use QGraphicsView::items(QPointF) get the item list below the mouse
create and send events, with QGraphicsScene::sendEvent whenever an item is added or removed from the list for all items... |
7,141,220 | 7,141,340 | C++0x unique_ptr misunderstanding? | In N2812 is an example in the Introduction where a unique_ptr is given as a value parameter
void push_back2(
std::list<std::unique_ptr<int>>& l, std::unique_ptr<int> a)
{
l.push_back(a); // oops: moves from the lvalue 'a', silently!
l.push_back(a); // oops: 'a' no longer has its original value
}
The paper discus... | Your knowledge and assumptions about the behavior are correct.
The paper's example is confusing as it is conflating two languages: C++ with concepts and C++ without concepts. In the paper's pretend language, the list push_back which requires CopyConstructible is SFINAE'd away, leaving only the overload requiring Move... |
7,141,260 | 7,159,944 | Compare std::wstring and std::string | How can I compare a wstring, such as L"Hello", to a string? If I need to have the same type, how can I convert them into the same type?
| Since you asked, here's my standard conversion functions from string to wide string, implemented using C++ std::string and std::wstring classes.
First off, make sure to start your program with set_locale:
#include <clocale>
int main()
{
std::setlocale(LC_CTYPE, ""); // before any string operations
}
Now for the fu... |
7,141,382 | 7,141,399 | Packet timing problem | I have a client that every 8 seconds will send a packet to a server. If the server detects the packets are sent too fast it will disconnect the client. In the client I call Sleep(8000); before sending the packet. On the server side I use GetTickCount(); to calculate the time between the packets. I expected this to work... | The problem is actually an age old one; TickCount varies, even between multiple CPUs in the same computer:
http://social.msdn.microsoft.com/Forums/en-US/netfxbcl/thread/22c68353-1dbb-4718-a8d2-0679fdc0c298/
My suggestion is set your Sleep to higher then 8000, say 9500, and keep the same mechanic for tickCount, therefor... |
7,141,417 | 7,167,382 | how can I compare utf8 string such as persian words in c++? | I want to compare strings in Persian (utf8). I know I must use some thing like L"گل" and it must be saved in wchar_t * or wstring. the question is when I compare by the function compare() strings I dont get the right result.
| If the strings that you want to compare are in a specific, definite encoding already, then don't use wchar_t and don't use L"" literals -- those are not for Unicode, but for implementation-defined, opaque encodings only.
If your strings are in UTF-8, use a string of chars. If you want to convert them to raw Unicode cod... |
7,141,427 | 7,141,632 | Making computations on pairs of sub events in two large files | I have large data in two files each with about two million (different) entries. The structure of the file is such that there is an event number, and for each event, there are some subevents. Each of these subevents have some characteristics. For example, the general structure of the files is such:
Index Event Sub... | In your loop you have to say continue to skip a round, rather than your break which aborts the entire loop.
Design-wise, your algorithm is extremely inefficient, as you can convince yourself by doing a basic complexity analysis. Indexing your data suitably would almost certainly be necessary.
This is exactly what datab... |
7,141,649 | 7,141,684 | Mac OS X drawing program | I want to write a ray tracer for a Mac. I don't want to learn Objective-C, is it possible to mix C++ and Objective-C? Is there some simple example somewhere of a program that does that and draws on the screen?
| SDL work on OS X and should work seamlessly with C++ code.
http://www.libsdl.org/
|
7,141,776 | 7,142,504 | C++ std::unordered_map | I am am using std::unordered_map and I would like to use it to store pointers to an object that I dynamically create with new.
I can create the objects fine and the insert method succeeds; however when I attempt to resolve a specific object from the map using the index it appears that all of the items in the list are m... | If I had to guess from the output you're getting, by any chance is the ID field of Session marked static? If so, this would manifest itself with exactly the behavior you're seeing here. In particular, if the field is static, then every time you create and update the ID of a new session, you'd be overwriting the ID fi... |
7,141,947 | 7,142,042 | C++ Weird istringstream behaviour | I apologise for being a C++ novice. I am trying to learn by translating some code from Java.
In this code, the strings that are read in represent letter frequencies in % in a language.
The test string we are dealing with is a10b10c10d10e10f50, as the test code shows.
In the loop below, the first 3 values (0.1, 0,1, 0.1... | You're not calling substr() correctly; try frequencies[fset].substr(i + 1, 2).
(The reason for the strange value is that it parses 10e10 as 100 billion.)
|
7,141,975 | 7,142,054 | static int array in a class problem | The following 3 code blocks are the main.cpp, static_class_array.cpp, and static_class_array.h respectively. I'm getting the following error:
static_class_array.cpp||In constructor 'static_array_class::static_array_class()':|
static_class_array.cpp|5|error: cannot convert '<brace-enclosed initializer list>' to 'int' in... | I think that what you want in the implementation file is:
static_array_class::static_array_class()
{
}
static_array_class::~static_array_class(){}
int static_array_class::array[3] = {0,1,2};
Explanation of error message
"cannot convert 'brace-enclosed initializer list' to 'int' in
assignment"
... |
7,142,302 | 7,142,428 | Detecting when destructor running due to exception being thrown? | What is a good way in C++ to detect in a destructor that it is being run during unwind of the stack due to an exception being thrown as opposed to a normal exit of scope triggering the destructor? I'd like to know so that I can create a class that has some cleanup code that is always run on normal exit but skipped whe... | std::uncaught_exception() (defined in <exception>) will tell you in your destructor if it was called because of an exception:
class A
{
public:
~A()
{
if (std::uncaught_exception()) {
// Called because of an exception
} else {
// No exception
}
}
};
|
7,142,394 | 7,142,419 | Creating new types in C++ | Using typedef in C++ creates an alias for a type.
So:
typedef double Length;
typedef double Mass;
creates two aliases which can be intermixed. In other words we can pass a value of type Mass to a function that expects a value of type Length.
Is there a lightweight way of creating new types? I would like them to be do... | BOOST_STRONG_TYPEDEF seems to be designed exactly for what you're looking for. I believe it does it's magic by creating a class and overloading the operators to make it behave like a builtin type, but I've not looked at it's implementation.
|
7,142,425 | 7,142,477 | I can't link static library with cmake | I try to link X11, giblib as static library with cmake.
So I append this code in CMakeLists.txt
set(BUILD_SHARED_LIBS FALSE)
set(CMAKE_EXE_LINKER_FLAGS '-static')
target_link_libraries(Printmade2 Imlib2)
target_link_libraries(Printmade2 /usr/lib/i386-linux-gnu/libX11.a)
target_link_libraries(Printmade2 /usr/lib/libgib... | It looks like you're missing the libxcb static libraries. http://xcb.freedesktop.org/
|
7,142,451 | 7,222,686 | Fast Graphics library which can support Animated GIFs | I am using ImageMagick with animated gifs but it is very slow. Taking twenty seconds for a single animation. Is there an alternate C/C++ graphics library which is fast? A good result may be those libraries that can handle huge images. But do any of those support animated GIFs?
These are the features I am needing:
Spli... | giflib [to parse the GIF format and save to] and C++ (for the image processing). This seems the best solution for me. Also using ImageMagick's Magick++ library could improve performance a bit.
|
7,142,517 | 7,143,130 | C++ and Lua: automatically register functions | When I was working with Lua in C#, I would add attributes to the methods I wanted to register with Lua, something like this:
// place tile marker
[LuaExport("settilemarker")]
public void SetTileMarker(int x, int y)
{
TileEditor.X = x;
TileEditor.Y = y;
}
Then, I would use reflection at runtime to find all thes... | C and C++ do not have reflection. Therefore, any tool you use will require at least some manual work. You're going to have to type something for every function you want to export, or you're going to have to put the prototypes into a special location or something.
There is a list of Lua binding utilities available. Some... |
7,142,532 | 7,142,585 | C++: Iterating through all of an object's members? | Suppose I have an object with many members:
class Example {
AnotherClass member1;
AnotherClass member2;
YetAnotherClass member3;
...
};
Is there a short/concise way to do something like:
foreach(member m: myExample)
m.sharedMethod();
Instead of accessing each one individually?
I think I could put ... | C++ does not support class introspection, so you cannot iterate over all of the members in a class like that - not without having a (manually written) function that iterates over all members for you anyway.
You could, in principle, add a template member like so:
template<typename Functor>
void doAllMembers(Functor &f) ... |
7,142,673 | 7,142,745 | What do people in the computer graphics industry use for ray tracing? | I took a computer graphics course (graduate level) this past year. We spent the semester building a ray tracer and adding features to it. We built everything from scratch in C++, presumably for the purpose of gaining a better understanding of the underlying data structures and algorithms. Here's my question: If I were ... | Although I'm sure there are a number of specialized commercial products, I think overall the most widely used package is the open-source POVRay. POVRay is powerful, easy to use, scriptable and extensible, and it can do an amazing range of things out of the box. Check out their site for an enormous gallery of ray-traced... |
7,142,874 | 7,151,629 | Serializing simple data structures in C++: evaluating a 1d versus 2d representation | I am trying to decide on a simple yet efficient serialization approach for some largish data structures and am hoping to find some feedback regarding the simple tests I have just written to help me make the decision.
The data structure in question comprises several 2-dimensional vectors of floats:
vector<<vector float>... | There is some room for improvement.
Timers are more consistent with less granularity. Don't add up times of iterations, take the time of the full operation and do any division by number of iterations afterward. This also keeps code dealing with time at the higher levels of concern, where it makes the most sense. Low... |
7,142,883 | 7,142,903 | How to pass reference-to-function into another function | I have been reading about function pointers and about using them as parameters for other functions.
My question is how would you pass a function by reference without using pointers? I have been trying to find the answer on the Internet but I haven't found a good answer.
I know that you can pass variables by reference l... | #include <iostream>
using namespace std;
void doCall( void (&f)(int) )
{
f( 42 );
}
void foo( int x )
{
cout << "The answer might be " << x << "." << endl;
}
int main()
{
doCall( foo );
}
|
7,142,983 | 7,143,230 | Well-documented, Open Source and Fast C/C++ image manipulation library. Like 'resize', rotate, change color, crop | Looking for a bunch of optimized image processing utility functions. Like: Resize with Cubic Interpolation, Rotate, Crop, Change a Color to a different Color. Much like what the GIMP has. But without the license and bloat of The GIMP.
Must be Free and Open Source, preferably not GPL, unless it is best
Must have compre... | Your question looks very subjective. Still look at the Boost Generic Image Library, it is open source.
|
7,143,120 | 7,143,186 | Convert string to variable name or variable type | Is it possible to convert strings into variables(and vise versa) by doing something like:
makeVariable("int", "count");
or
string fruit;
cin >> fruit; // user inputs "apple"
makeVariable(fruit, "a green round object");
and then be able to just access it by doing something like:
cout << apple; //a green round obje... | No, this is not possible. This sort of functionality is common in scripting languages like Ruby and Python, but C++ works very differently from those. In C++ we try to do as much of the program's work as we can at compile time. Sometimes we can do things at runtime, and even then good C++ programmers will find a way to... |
7,143,194 | 7,143,501 | C++: STL linked list - representing a Polynomial | I'm working on a problem which requires me to use the STL linked list class to represent a polynomials. I've made a good start on getting the class definition, however I'm a little confused as to where to go next (novice programmer - please excuse my potential ignorance).
class Polynomial
{
public:
Polynomi... | Others have explained list<pair<double, int> > (and I like shelleybutterfly's suggestion to derive Polynomial from the list, except that I'd make it protected, not public, so that outside code is not too free to mess with the contents of the list).
But the add function is a little tricky, because adding two polynomials... |
7,143,276 | 7,143,615 | How to create custom boost::posix_time to_string formatters? | Currently I have to use stuff like
ptime t = from_time_t(last_write_time(p));
std::string Created = boost::posix_time::to_iso_extended_string(t) ;
or:
ptime t = from_time_t(last_write_time(p));
std::ostringstream formatter;
formatter.imbue(std::locale(std::cout.getloc(), new boost::posix_time::time_facet("%a, %d %b %Y... | I always get flamed for using sprintf but anything wrong with this?
char buffer[...];
sprintf(buffer, "%s, %d %s %04d %02d:%02d:%02d GMT", t ...);
std::string Create(buffer);
I don't know the details of the ptime type, so I don't know how big you would have to make the buffer to be safe, or what you would put for the ... |
7,143,445 | 7,143,946 | TCP memcpy buffer returns rubbish data using C++ | I'm doing something similar to Stack Overflow question Handling partial return from recv() TCP in C.
The data receive is bigger than the buffer initialised (for example, 1000 bytes). Therefore a temporary buffer of a bigger size (for example, 10000 bytes) is used. The problem is that the multiple data received is rubbi... | Suppose you are expecting 7000 bytes over the tcp connection. In this case it is very likely that your messages will be split into tcp packets with an actual payload size of let's say 1400 bytes (so 5 messages).
In this case it is perfectly possible consecutive recv calls with a target buffer of 1000 bytes will behave ... |
7,143,528 | 7,161,255 | CyanogenMod compile error on OpenSuse | I'm trying to compile CM7.1 on my OpenSuse 11.4 64-bit. I think i've all the required packages in place, except for gcc-multilib and g++-multilib (couldnt find those for SuSe)
So, when i compile, i get some strange glibc errors -
*** glibc detected *** make: free(): invalid next size (fast): 0x0000000007a00340 ***
===... | Nevermind, got it. Was a problem with make 3.82 - reverted to 3.81, and it works now.
Described here - http://groups.google.com/group/android-porting/browse_thread/thread/7666e7f8271e1260
|
7,143,538 | 7,146,410 | What does _dopr mean | I have a gdb be crashed dump having crashed at dopr
What does this do ?
I have not defined this function and not using calling anywhere. Is is libc function ?
[Switching to thread 1 (Thread 5339)]#0 0x00000000005f0937 in _dopr ()
(gdb) bt
#0 0x00000000005f0937 in _dopr ()
#1 0x00000000000003ff in ?? ()
#2 0x000000... | As mentioned in the comments _dopr isn't your problem. What you are looking at is stack corruption, and again, in the comments, a buffer overflow is the most likely problem.
Assuming you are compiling your application with gcc, add the option:
-fstack-protector-all
to your compile and link options. This stick a coup... |
7,143,716 | 7,143,753 | how to create scripting languages | I'd really like to know what knowledge do I have to pursue in order to create scripting languages from the ground up, probably using C++, maybe python, for those are the languages I know.
I've searched through SO similar questions, but nothing comes close of what I'm asking. I intend to understand language processing, ... | "From the ground up" is a quite relative term, especially if you consider Python as the implementation language. I think what you are looking for is the implementation of a domain specific language (DSL). Good starting points might be this book or this one. DSLs are a wide topic, so if you provide more details, we migh... |
7,143,812 | 7,143,897 | Why does allocator in c++ provide specialization for type void | I notice that the allocator in c++ provides specialization for type void. Is there any special purpose to do this? It doesn't make sense to allocate memory for void type, right?
| This old Standard Librarian column by Matt Austern has a fairly thorough discussion of allocators in general, including this tidbit:
What do we do about void? Sometimes a container has to refer to void
pointers, and the rebind mechanism almost gives us what we need, but
not quite. It doesn't work, because we would... |
7,143,976 | 7,151,276 | Collections of objects that are aware of each other | This is kind of a broad question, but for my own understanding I decided I would throw it out there.
Can anyone recommend designs, or maybe even generally accepted design patterns for situations where one would want various objects that are aware of each other?
To use a people/community simulation as an analogy, what w... | What you're looking for is a relatively simple association.
class Person {
struct Relationship {
// whatever
};
std::map<Person*, Relationship> relationships;
public:
Person() {}
void Meet(Person* other) {
// think about it
relationships[other] = ...;
}
~Person() {
... |
7,144,149 | 7,144,192 | CPtrArray without MFC (to STL or Boost) | I'm trying to leave MFC, how can I replace CPtrArray ?
maybe I can typedef it to something alike vector<void *>
What is better way to save full functional of this class ?
thank you.
| No need to write it yourself, you can use boost::ptr_array instead. It uses an underlying std::vector<void*> to store the pointers.
|
7,144,217 | 7,144,247 | Question on using this pointer | I tried copying a pointer to another by using a method inside the class and the this pointer as follows. I am giving the entire test code so that it is clear what is going on.
class test {
private:
int x;
public:
void setx(int x);
int getx(void);
void copy(test *temp);
};
void test::setx(int x) {
... | You cannot overwrite this. The this pointer is a constant, so you're not allowed to change it. And what would that mean anyway? You can't change the object that you're in. You can change the values within that object, but not the object itself.
You need to copy other objects by value (by what is stored in the object), ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.