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,586,074 | 7,594,581 | COM addin for MS Office doesn't load in a limited user account | I've created a toolbar for Word. It's a COM addin and is written in C++. It works when Word is started by an Administrator account in XP. But when Word is started from a limited account it's not even loaded. I placed this code in DllMain:
/////////////////////////////////////////////////////////////////////////////
// ... | It turned out that my addin was registering itself in HKCU instead of HKLM (this was in the .rgs file). So only the user doing the install would have it registered. That's why Word wouldn't load it for other user accounts.
|
7,586,088 | 7,586,169 | Boost condition_variable destruction assert | My question is: is there something specific I need to do (like call notify_all?) in the destructor of a thread that encapsulates a boost::condition_variable. The following code generates this assert when the Test destructor is called:
cond_var:
/usr/include/boost/thread/pthread/condition_variable_fwd.hpp:38:
boost... | You need to join the two threads you've created before you exit. Add a global boolean variable called say, 'stop', initialized to false, and have t1 and t2 check that it's false every iteration:
bool stop = false;
void runPut () {
while( !stop ) {
t.getI();
}
}
void runGet () {
while( !stop ) {
... |
7,586,354 | 7,586,405 | C++ insert numbers until certain symbol | I tried to write a code that asked me to input numbers one by one and when a certain char was inserted ( in this case 'x' ) it would stop the loop. But when I insert that char it starts spamming me with "Insert Number" . I think that the fault is that I'm trying to insert a char in an int array, but I can't think a way... | You should write a loop as:
while(cin >> numbers[index])
index++;
It will read all the integers, untill you enter some invalid input, be it 'x' or any other character. Now if you want to skip all invalid inputs and continue reading integers (which might be after invalid inputs), and want to consider only 'x' to ex... |
7,586,535 | 7,586,900 | Looking for Polygon Geometry library with specific capabilities | I am doing a survey of polygon/geometric algorithm libraries implemented in Objective C, C or C++ (in that order of preference). I have very specific needs, so I figured I'd ask the community to see if anyone knows of one that meets some or all of them since I'd prefer to use one library/API for all my needs. This is w... | In C++ it exists some libraries to work with the polygon geometry but I don't know one that fully corresponds to your needs.
A very useful library that I know in C++ is CGAL. It covers some of your needs, but not all.
|
7,586,674 | 7,586,906 | quick-sorts iterator requirements | tl;dr: Is it is possible to implement quicksort on a doubly linked list efficiently? My understanding before thinking about it was, no, its not.
The other day I had an opportunity to consider the iterator requirements for the basic sorting algorithms. The basic O(N²) ones are fairly straightforward.
Bubble sort - 2 ... | tl;dr: Yes
As you say, the problem is to find the pivot element, which is the element in the middle, finding this with random access takes O(1), finding it with bidirectional iterators takes O(n) (n/2 operations, to be precise). However, in each step you have to create to sub containers, the left and the right containi... |
7,586,723 | 7,586,757 | Verify web service is available | I have a C++ program that will be retrieving a url which specifies a wsdl. My program is simply middleware and doesn't perform any wsdl related requests; it will literally read the data and pass it on to whomever will use the url.
That being said, within Linux, can I test to see if the webservice is available within m... | use curl, ping the url, and check the response code. Look here for a bunch of libcurl examples
|
7,586,817 | 7,587,033 | moving pointer between vectors in vector causes vector iterators incompatible | I have std::vector of cells. Each cell has other std::vector to store some pointers to entities. Now I want to move pointer from one cell to another based on calculation new cell index.
But I am getting vector iterators incompatible. I know that is caused by push_back invalid the iterator, but I do not know why, becaus... | The line that erases from entitiesInCurrentCell has a bug. Correct it by writing
entityIter = entitiesInCurrentCell.erase(entityIter);
When erasing from a container, the next iterator is returned by the erase function, so you do not need to increment the iterator.
|
7,586,845 | 7,587,384 | Using OpenGL shaders to plot 4D points in 2D in C++ |
Possible Duplicate:
Visualising 4D objects in OpenGL
I have a set of 4 dimensional data points (lets call the dimensions X,Y,A, and B) that I'd like to plot in 6 different 2d plots (plot XxY, XxA, XxB, YxA, etc...).
In a previous question I asked about the proper way to store and plot this data. The solution was to... | Since shaders can work with 4 dimensional vectors and 4x4 matrix, we can be smart and use only one vertex shader to do the trick. This shader will take three inputs:
the point data (a 4 floating vector),
a selection 4x4 matrix,
a projection 4x4 matrix.
All the magic is done by the selection matrix, which will map you... |
7,586,848 | 7,586,946 | Placement new breaks consts and references? | Following the discussion on my answer to this question, apparently:
the following code is allowed
struct Foo {
int x;
};
Foo f;
Foo & f_ref = f;
(&f) -> ~Foo ();
new (&f) Foo ();
int x = f_ref .x;
but the following code is not allowed
struct Foo {
const int & x; // difference is const reference
... | I believe the motivation is to permit the compiler to cache the values of const objects (note that's const objects, not merely referands of pointers-to-const and reference-to-const), and the addresses of referands of references, across calls to unknown code.
In your second example, the compiler can "see" firstly that t... |
7,587,066 | 7,587,145 | How to iterate over unicode characters in C++? | I know that to get a unicode character in C++ I can do:
std::wstring str = L"\u4FF0";
However, what if I want to get all the characters in the range 4FF0 to 5FF0? Is it possible to dynamically build a unicode character? What I have in mind is something like this pseudo-code:
for (int i = 20464; i < 24560; i++ { // Fro... | The wchar_t type held within a wstring is an integer type, so you can use it directly:
for (wchar_t c = 0x4ff0; c <= 0x5ff0; ++c) {
std::wstring str(1, c);
// do something with str
}
Be careful trying to do this with characters above 0xffff, since depending on the platform (e.g. Windows) they will not fit in... |
7,587,067 | 7,587,151 | Do I need to overload methods accepting const lvalue reference for rvalue references explicitly? | currently I’m playing around with rvalue reference (C++11, g++ with gnu++x0) and I want to implement move semantics in my classes, because it just feels „right“.
Do I need to overload each function which normally would accept const lvalue reference to benefit from the rvalue references?
Let’s say this is my example cla... | Write one function. Take it in by value, then move it.
void Person::set_name(std::string name)
{
this->name_ = std::move(name);
}
Let the std::string decide how to copy itself.
|
7,587,071 | 7,587,795 | Is this method of inter-thread-communication safe? | I have 3 objects(inherited from QObject) that each contain a separate std::list. Each object gets created in the main gui thread (with no parent) and then is pushed to it's own thread (using Qt's QObject::moveToThread()).
Each thread is hooked up to a gui and messages are sent between the different threads with data. ... | It's hard to say exactly whether it's thread-safe or not without all the implementation details as there are a lot of things that can go wrong when using threads.
Obj 1 : Consumer of data. It pop's the front off of its list(if data is present) to use. It also has a SLOT available so that other threads can push data to... |
7,587,154 | 7,587,202 | What is this error message about implicitly deleted virtual destructors? | I've just updated GCC from (I think) 4.5.6 to 4.6.1, under Windows, MinGW. Suddenly my NonInstantiable base class (from which you inherit with public virtual to prevent instantiation) refuses to work with the following and similar error messages:
#ifndef Frigo_Lang_NonInstantiable
#define Frigo_Lang_NonInstantiable
na... | Parent destructors always need to be callable from a child class (because this happens automatically) and so parent class destructors can't be private.
Just make your NonInstantiable's destructor protected.
Also note that a child class could circumvent the parent as written by explicitly (accidentally?) calling into it... |
7,587,595 | 7,587,701 | Read binary data from std::cin | What is the easiest way to read binary (non-formated) data from std::cin into either a string or a stringstream?
| std::cin is not opened with ios_binary. If you must use cin, then you need to reopen it, which isn't part of the standard.
Some ideas here: https://comp.unix.programmer.narkive.com/jeVj1j3I/how-can-i-reopen-std-cin-and-std-cout-in-binary-mode
Once it's binary, you can use cin.read() to read bytes. If you know that in... |
7,587,782 | 7,587,829 | Why is std::cout not printing the correct value for my int8_t number? | I have something like:
int8_t value;
value = -27;
std::cout << value << std::endl;
When I run my program I get a wrong random value of <E5> outputted to the screen, but when I run the program in gdb and use p value it prints out -27, which is the correct value. Does anyone have any ideas?
| Because int8_t is the same as signed char, and char is not treated as a number by the stream. Cast into e.g. int16_t
std::cout << static_cast<int16_t>(value) << std::endl;
and you'll get the correct result.
|
7,587,983 | 7,588,030 | Passing NULL for array parameter in C/C++ | void DoSomeThing(CHAR parm[])
{
}
int main()
{
DoSomeThing(NULL);
}
Is the passing NULL for array parameter allowed in C/C++?
| What you cannot do is pass an array by value. The signature of the function
void f( char array[] );
is transformed into:
void f( char *array );
and you can always pass NULL as argument to a function taking a pointer.
You can however pass an array by reference in C++, and in that case you will not be able to pass a N... |
7,588,485 | 7,588,592 | Is it considered good practice to change the protection level of a method? | In other words if I have a class
class A
{
public:
A() { .. }
virtual void somemethod() { .. }
};
is it ok to write
class B : public A
{
public:
B() { .. }
protected:
virtual void somemethod() { .. }
};
or are there some drawbacks with this approach?
| I would say this defeats the purpose of polymorphism, because when you write a function that accepts a polymorphic type, the derived type should work equally well with it:
void fun(A* a){
a->somemethod();
}
...
A* a = new B();
fun(a); // Shouldn't this work?!
// According to Liskov Principle, you are doing i... |
7,589,170 | 7,589,275 | Boost - Formatting sub second precision time with a time stamp | I need to get a nicely formatted timestamp (slightly modified ISO 8601) with millisecond precision.
And example date would look like this: 2011-09-28 13:11:15.237-08:00
The formatting should be able to be overwridden as well.
I've been playing around with boost::posix_time::microsec_clock::local_time() and boost::posix... | Have a look at the boost::local_time::local_date_time class. You can specify a time zone and use the local microsecond clock to initialize it like
boost::local_time::local_date_time my_ldt(boost::local_time::local_microsec_clock::local_time(new boost::local_time::posix_time_zone("EST-5EDT,M4.1.0,M10.5.0")));
You shou... |
7,589,341 | 7,589,400 | Is SQLite right for my game? | I have been looking into different database libraries for my online card game (PostgreSQL, Oracle, etc) and, while SOCI + pg or Oracle are much more powerful, they also are tricky to compile, integrate, and do a whole lot more than what I need to do.
Quite simply these are my requirements:
Store the username, hash, win... | With that many clients SQLite is a perfect fit. However, I would recommend you wrap up this functionality in a simple and not database specific interface, and implement it for SQLite. Once you will get millions of clients along with concurrency/performance issues, you can simply throw in another implementation that use... |
7,589,511 | 7,589,625 | How to mix OpenCV 1.0 and OpenCV 2.0 | I want to do a polar transform. But in OpenCV 2.0 there doesn't appear to be a C++ version of the cvLogPolar function. How do I use it with cv::Mat?
Error:
'cvLogPolar' : cannot convert parameter 1 from 'cv::Mat' to 'const CvArr *'
Here is my code:
VideoCapture cap(1);
try {
if(!cap.isOpened()) {
throw "Cou... | Try something like
Mat frame;
cap >> frame;
Mat dst(frame.size(), frame.type());
CvMat cvframe = frame;
CvMat cvdst = dst;
cvLogPolar(&cvframe, &cvdst, Point(frame.size().width/2, frame.size().height/2),
1.0f, CV_INTER_LINEAR|CV_WARP_INVERSE_MAP);
imshow("Preview", dst);
I've created new Mat to store results of c... |
7,589,672 | 7,589,751 | Boost.Regex vs C++11 Regex | Could someone explain the differences between the two? Which would be better to learn right now? How would knowledge transfer from one to the other and vice-versa?
| The boost regex library made it into C++0x so I'm guessing it will slowly be removed from boost. However, using boost is nice because you can still use it with compilers without C++0x support. So it's really up to you.
|
7,589,809 | 7,589,864 | Why can't we have automatically deduced return types? | Recently I was working a friend who wanted to make C++ more Haskell-y, and we wanted a function that's basically like this:
auto sum(auto a, auto b) {
return a + b;
}
Apparently I can't use auto as a parameter type, so I changed it to this:
template<class A, class B>
auto sum(A a, B b) {
return a + b;
}
But t... | Well - time passed since the original question was asked and the answer now is that you can!
Yes, it is true that the question is tagged C++11 - with which you still cannot do what the OP is asking for. But it's worthwhile to show what is doable with C++14 and later.
Since C++14 this is valid:
template<class A, class B... |
7,589,974 | 7,590,050 | OpenGL: glGenBuffer vs glGenBuffersARB | What is the difference between the functions glGenBuffers()/glBufferData()/etc, and the functions with ARB appended to the function name glGenBuffersARB()/glBufferDataARB()/etc. I tried searching around but no one ever points out the difference, merely they just use one or the other.
Also, is it common for either fu... | glGenBuffers() is a core OpenGL function in OpenGL 1.5 and later; glGenBuffersARB() was an extension implementing the same functionality in earlier versions.
Unless you're developing for an ancient system, there's no longer any reason to use the ARB extension.
|
7,590,047 | 7,590,089 | C++ Class: Passing a parameter | I'm just learning classes so I'm trying something basic. I have a class called Month as shown below. For my first test, I want to supply a number from 1 through 12 and output the name of the month ie. 1 = Jan.
class Month
{
public:
Month (char firstLetter, char secondLetter, char thirdLetter); // constructor
... | What you probably want to do is something like this:
int num;
cout << "give me a number between 1 and 12 and I'll tell you the month name: ";
cin >> num;
Month myMonth(num);
myMonth.outputMonthLetters();
Note that myMonth isn't declared until it's needed, and the constructor taking the month number is called after you... |
7,590,065 | 7,590,177 | Updating a file with <fstream> library (overwriting just a specific section) | I want to ask if there is any way to update say a text file with a content of "ooooo" to
"ooXXo" using the fstream library. I know there is a way with cstdio but I don't want to use that one because of unsupported exception handling... Also, I don't want to read the file to memory, update the section I want and then w... | #include <fstream>
int main (){
std::fstream pFile("example.txt");
pFile << "This is an apple.";
pFile.seekp(9);
pFile << "sam";
pFile.close();
return 0;
}
fstream by default opens the file for both reading and writing. There's a second argument with a default value in the constructor which controls that ... |
7,590,184 | 7,590,363 | Bringing convenience of Java code assistant from Eclipse to Visual Studio 2010 for native C++ projects | Eclipse has many features which saves a developer much time, for example:
1) Override/Implement Methods...
2) TODO lists...
3) Fast access to documentation... (There might be also something else)
Is there any plugin for VS 2010 which brings approximately the same functionality to native C++ projects?
| VisualAssist X provides refactoring, navigation and code assistance. When you're moving from Eclipse to VisualStudio, it drastically reduces the feeling that you're working with stone knives and bearskins.
|
7,590,298 | 7,590,418 | UDP NAT hole punching example | I try search in google and here but i still cant find simple C\C++ example udp hole punching algorithm. Please help if you know where i can find it. Thanks!
| You can browse this open source code for it:
http://www.codeproject.com/KB/IP/stunner.aspx
You should googled 'STUN'
|
7,590,370 | 7,604,137 | boost property tree, iterators to an element for inserting? | I've searched a lot through the boost manual, and the internet, as I believe it is quite a standard feature?
Well I'm looking into "merging" property trees. - I noticed the function insert, and I hope I can merge trees with this?
Below is the line which I am trying to get working:
base.insert(base.get_child("BRANCH"), ... | You can get an iterator to an element using the begin() method:
base.get_child("BRANCH").begin();
In order to insert every element in t on that position, you should use:
base.insert(base.get_child("BRANCH").begin(), t.begin(), t.end());
If t contains one parent node or you only want to insert the first node, you ca... |
7,590,604 | 7,591,080 | prevent command line from opening on _popen | I'm opening a process in C++ like so
FILE* pipe = _popen(ss.str().c_str(), "r");
This create a cmd window which goes to the forefront of the desktop. I want to prevent the cmd window from opening, and if I can't, a way to keep it minimized.
Tried solutions:
HWND hWnd = GetConsoleWindow();
ShowWindow(hWnd, SW_HIDE);
... | Instead of using _popen, use CreateProcess and the CREATE_NO_WINDOW flag.
|
7,590,610 | 7,590,723 | Very basic question about argument with signature void *data | This is very likely an extremely basic question - sorry about that.
I have written an interface in C++ which is powered by a C engine. One of the C-engine functions has the following signature:
static int f(double t, double *y, double *ydot, void *data)
The *data thingy is to pass user data to an ODE solver. Now, in C... | void *data
means a pointer to any address. It is a non-typesafe way of passing data of arbitrary type. It is a common pattern in C to implement what would be done with a function object in C++. The data parameter is probably not actually used by your ODE solver, but by a callback that you are providing. You and t... |
7,590,675 | 7,590,767 | How to properly dereference multidimensional arrays without []-operator | So, I've figured out how to dereference a multidimensional array like this:
#include <tchar.h>
#include <iostream>
wchar_t g_pppwcSymbol[2][3][4];
int main(int argc, TCHAR **argv)
{
(* (*( (*(g_pppwcSymbol+1) )+2 )+3 ) ) = L'K';
std::wcout<<g_pppwcSymbol[1][2][3];
std::wcin.get();
return 0;
}
... | The compiler actually transforms the [] operator into just those mathematical calculations, so you are going about this the hard way... But it's an interesting exercise so I'll play along.
g_pppwcSymbol[2][3][4] is actually a 2 elements large array of 3 elements large array of 4 elements large. Thus,
g_pppwcSymbol +... |
7,590,924 | 7,590,973 | How do I initialize a struct in a Class constructor list? | I want to initialize a struct within a default class initializer list. For example, if I have a class like like this:
class Foo
{
private:
int x;
int y;
int z;
somestruct p;
public:
Foo(): x(1), y(2), z(3)
{
// other stuff
}
};
So, I can clearly initialize primitive types this way -... | In the code below, m_strct is a member of MyClass, and is initialized by the default constructor.
struct MyStruct
{
MyStruct(int i): // Constructor
myData(i)
{ }
int myData;
};
class MyClass
{
public:
MyClass() : // default constructor
m_strct(0)
{ }
private:
MyStruct m_s... |
7,591,014 | 7,591,059 | Not sure about my interpretation of function declaration in C++? | It seems to be stupid question but I have never seen something like this!
int operator() (const std::string& s1, const std::string& s2) const
to me operator is a const member function that return an intger and no variable argument!
but need two const variables s1 and s2?!?! I can't get the point of this!
class str_di... | The operator() part says that objects of type str_dist_ can be "called", as though it were a function. The (const std::string& s1, const std::string& s2) tells us what the argument actually are.
For example, say we have an object str_dist_ obj;, and two std::string objects, str1 and str2. Then we can write something li... |
7,591,264 | 7,591,424 | Is there a difference between calling a member function from a leaf class in or out of the destructor body? | I have a specific case which is hard to isolate in a code snippet here but I can explain it...
I have a class A : public B and A has a member pointer of some type foo * f. In the virtual destructor for A, I have something like:
A::~A() { shutdown(); }
where, shutdown is nonvirtual and looks something like:
void A::shu... | Either shutdown is a pure virtual function somewhere up the inheritance tree, or it calls another member function which is pure virtual somewhere up the inheritance tree. Either directly or indirectly, but that's what happens.
Check the execution path to see where the call is made and get rid of it.
|
7,591,270 | 7,591,313 | Looking for windows equivalent of the unix script command | The unix command "script" allows a user to run programs/commands, and when ctrl-d is pressed, the output is written to a file. A timestamp of the session is also written in this file. Is there is a equivalent command in Windows/Visual Studio?
| is Cygwin an option? The script command can be found in the util-linux package.
|
7,591,280 | 7,591,297 | Is the correct type required for the delete operator in C++? | void * intptr = new int;
delete (int *) intptr;
Is the (int *) type cast required?
| Yes.
The type must match that which was new'd. The only time it doesn't have to match is deletion of a derived type through a base pointer, where the base type has a virtual destructor.
|
7,591,609 | 7,592,374 | Rendering with glDrawRangeElements() not working properly | This is a followup to my previous question. All of my questions were answered in my last thread but this is a new error that I am having. When rendering in intermediate mode, everything looks great.
In fact:
http://i.imgur.com/OFV6i.png
Now, I am rendering with the glDrawRangeElements() and look what happens:
http://i.... | Managed to get it to work. Very thankful that someone on another forum labeled his question accurately where a third vertex was being drawn at the origin.
http://www.gamedev.net/topic/583558-gldrawelements-is-drawing-all-of-my-vertices-with-one-vertex-at-the-origin-solved/page_gopid_4867052#entry4867052
Seems I needed ... |
7,591,617 | 7,591,655 | Why this code does not compile using MS compiler? | This code does compile using the GNU gcc compiler while doesn't if using the Visual Studio 2008 one.
the error sas: "error C2143: syntax error: missing ';' before '*'
Arbol::Nodo* is a pointer to the class inside Arbol that works ok if compiling using codeblocks + gnu gcc compiler.
template <class T>
Arbol<T>::Nodo<T>*... | Add typename:
template <class T>
typename Arbol<T>::Nodo<T>* Arbol<T>::Alta(Nodo<T>* &nodo,const T d) /////this line is highlited
{
return nodo;
}
You need to mark qualified names that are types explicitly within a template.
|
7,591,706 | 7,591,786 | I'm in trouble with creating new object in C++ | I'm new to C++ and I'm having a trouble with it.
I've tried to create new object without (*), so Animal a1; but it didn't work.
So now I'm using Animal* a1;, and it works, but the problem is that it says it has to be initialised.
I made a default constructor, so doesn't it mean that it initialises automatically or shou... | When you declare
Animal* a1;
a1 doesn't point to anything: it's an uninitialised variable, which has an undefined value. Calling a method on it has undefined behaviour. If you have a default constructor, you can create a default-constructed local Animal like so:
Animal a1;
This Animal will exist till the end of the s... |
7,591,711 | 7,592,345 | Is it more efficient to have a map of maps, or a very large map? | I am storing some objects in map (hashed by strings), but the objects are categoriseable by another string.
I could therefore make a map of these categories, and for each category keep another map of the objects in that category.
I will always know the category whenever I make an insertion or a get request from this da... | Doing the arithmetic, if you have n elements lookup time would be O(log(n)). If you split the map into m1 maps containing maps of size m2, then you need O(log(m1)) to lookup in the first map, then O(log(m2)) to do a lookup on the second map. But since
log(m1) + log(m2) = log(m1*m2) = log(n)
You aren't buying much ... |
7,591,771 | 7,592,016 | How can I convert 0x70, 0x61, 0x73 ... etc to Pas ... etc in C++? | I am using MSVC++ 2010 Express, and I would love to know how to convert
BYTE Key[] = {0x50,0x61,0x73,0x73,0x77,0x6F,0x72,0x64};
to "Password" I am having a lot of trouble doing this. :( I will use this knowledge to take things such as...
BYTE Key[] { 0xC2, 0xB3, 0x72, 0x3C, 0xC6, 0xAE, 0xD9, 0xB5, 0x34, 0x3C, 0x53, 0... | All you are lacking is a null terminator, so after doing this:
char Key_str[(sizeof Key)+1];
memcpy(Key_str,key,sizeof Key);
Key_str[sizeof Key] = '\0';
Key_str will be usable as a regular char * style string.
|
7,591,942 | 7,592,079 | C++ compiler from VS2005 | If I would like to use the compiler that comes with Visual Studio 2005 but without IDE which Platform/Windows SDK should I install to get it? Windows SDK 2008?
| According to this MSDN blog article:
Updated Windows SDK Visual C++ Cross Compilers
The compilers in the new Windows Server 2008 and .NET Framework 3.5 SDK match (are exactly the same as) the compilers shipped with Visual Studio 2008. In the Windows Vista RTM SDK or the Windows Vista Update SDK, the compilers match... |
7,591,967 | 7,592,881 | C++ OpenSSL HMACSHA1 works but not how I want it to | This HMACSHA1 code below works for converting "Password" and "Message" to AFF791FA574D564C83F6456CC198CBD316949DC9 as evidence by http://buchananweb.co.uk/security01.aspx.
My question is, Is it possible to have:
BYTE HMAC[] = {0x50,0x61,0x73,0x73,0x77,0x6F,0x72,0x64};
BYTE data2[] = {0x4D,0x65,0x73,0x73,0x61,0x67,0x6... | The issue is the relation ship between arrays, strings, and the null char.
When you declare "Password", the compiler logically treats the string literal as a nine byte array, {0x50,0x61,0x73,0x73,0x77,0x6F,0x72,0x64, 0x00}. When you call strlen, it will count the number of bytes until it encounters the first 0x00. st... |
7,591,968 | 7,591,988 | counting number of occurrences of an object in a list | I am trying to find the number of occurrences of an object in a list:
class Complex{
double re, im;
public:
Complex (double r, double i):re(r), im(i){}
Complex (){re = im = 0;}
friend bool operator == (Complex, Complex);
};
bool operator == (Complex a, Complex b){
return a.re == b.re and a.im == b... | It seems Iterator does not have overloaded operator+(int), try:
class Complex{
double re, im;
public:
Complex (double r, double i):re(r), im(i){}
Complex (){re = im = 0;}
friend bool operator == (Complex, Complex);
};
bool operator == (Complex a, Complex b){
return a.re == b.re and a.im == b.im;
}... |
7,591,977 | 7,605,220 | MySQL Connector C linking problem on VS2010 | I am beginning on MySQL, and I encountered the error message while compiling the code:
error LNK2001: unresolved external symbol _mysql_init@4
I have searched the web, and did everything that seems to be the problem.
#include <my_global.h>
#include <mysql.h>
#define NULL 0
int main() {
MYSQL * sql = mysql_init(NULL);... | After a careful investigation, I found that the problem raised from the x64 settings.
x64 compilation option should be turned on when compiling an x64 project.
In this case, platform should be switched from win32 to x64,
and in project->properties->linker->advanced->target machine: x86 should be set to x64.
|
7,592,129 | 7,592,147 | Program is generating same random numbers on each run? | I just finished coding a Minesweeper type game, and everything's good except for that each time I run the application, it generates the same number (I ran it 3 different times, saved the output to 3 text files and used the diff command in Linux, it didn't find any differences). It's seeded by time(NULL) so it should ch... |
It's seeded by time(NULL)
If it is, I can't see it. In fact, a search for it in your code returns nothing. The default behaviour, if you don't explicitly seed, is the same as if you had seeded it with the value 1.
You need to explicitly state something like:
srand (time (NULL));
at the start of main somewhere (and m... |
7,592,145 | 7,592,191 | Conventional c++ program header file structure? | I know the mechanics of how header files work in c++ but i'm just starting to write bigger opengl programs with lots of classes and i was wondering if there is a "standard" or conventional way of organizing larger programs around header files or if it is just personal preference for the most part?
|
1. Divide your project into Modules.
2. Make a directory for each module.
3. Under each directory for a module create 2 sub directories inc/ and src/
where you will place your header and source files resp.
4. Create a global directory and place your header and cpp files in that directory which
would be used commonly ... |
7,592,207 | 7,592,219 | ostream equivalent of %.2f or %.2lf | double d = 1/2.;
printf("%.2lf\n", d);
This prints out 0.50. This is what I want to replicate using ostream manipulators. However, none of the obvious iomanip manipulators let me set the minimum required decimal places (if I understood correctly, setprecision sets the maximum width). Is there a pure iostream or boos... | Use setprecision in combination with fixed.
According to section 22.4.2.2.2 of the standard, precision specifications on iostreams have exactly the same effect as they do for printf. And fixed gives the exact same behavior as printf's %f.
|
7,592,367 | 7,592,392 | C++ Access violation? | Why am I getting an access violation reading location 0xC0000005 here if the same code works like a charm when I coding in linux?
if(nodo->izq!=NULL) //nodo is a class or struct and "sig" is a pointer of the same kind
VaciarAux(nodo->izq);
Is there any way of getting this done without that unhandled exception?
ass... | Most likely because nodo itself is an invalid pointer. The -> dereferencing would then cause a problem.
You need to check the things that could possibly affect that value (buffer overflows causing corruption, having set to NULL for some reason).
Note that:
if (nodo->izq != NULL)
does not check if the nodo variable is ... |
7,592,630 | 7,592,741 | Is pass-by-value a reasonable default in C++11? | In traditional C++, passing by value into functions and methods is slow for large objects, and is generally frowned upon. Instead, C++ programmers tend to pass references around, which is faster, but which introduces all sorts of complicated questions around ownership and especially around memory management (in the eve... | It's a reasonable default if you need to make a copy inside the body. This is what Dave Abrahams is advocating:
Guideline: Don’t copy your function arguments. Instead, pass them by value and let the compiler do the copying.
In code this means don't do this:
void foo(T const& t)
{
auto copy = t;
// ...
}
but ... |
7,592,820 | 7,592,912 | Stack versus Integer | I've created a program to solve Cryptarithmetics for a class on Data Structures. The professor recommended that we utilize a stack consisting of linked nodes to keep track of which letters we replaced with which numbers, but I realized an integer could do the same trick. Instead of a stack {A, 1, B, 2, C, 3, D, 4} I co... | From the looks of things the way you are doing things here is quite inefficiant.
As a general rule try to have the least amount of for loops possible since each one will slow down your implementation greatly.
for instance if we strip all other code away, your program looks like
while(thing) {
for(z < 26) {
}
for... |
7,592,822 | 7,593,718 | What are the advantages of pwrite and pread over fwrite and fread? | Hey please don't mind if I am asking trivial question, but, please can somebody help me with this..
| It's useful when you do a lot of random read/write operations. There is even an option for SQLite3 that replaces seek() + read() and seek()+ write() with pread()/pwrite().
The advantage: seek()+ read() and seek() + write() both are the pairs of system calls while pread() and pwrite() are single system calls. It's usu... |
7,592,848 | 7,605,465 | Why is no serial data available on my Arduino? | I've run the simple serial program on my Arduino Uno, which just echos whatever you type to it. This works perfectly when run in the Arduino Sketch IDE (v22).
int incomingByte = 0; // for incoming serial data
void setup() {
Serial.begin(115200); // opens serial port, sets data rate
}
void loop() {
// send... | Found the answer to my own question:
It turns out the HardwareSerial.h library relies on interrupts. This is something that is automagically taken care of for you when building with the Arduino IDE. If you aren't using the Arduino IDE (like me), then you must remember to enable interrupts on your own.
Just #include <av... |
7,593,072 | 7,593,278 | How to overload operator +() for a class | The following is a class that contains a operator+ method. I understand the feetInches::operator+(const feetInches &other) const part of it but in the method definition, why is there an extra feetInches and what does it represent here?
class feetInches {
public:
feetInches(int inFeet = 0, int inInch... | Declaring a function const means you can't modify the this object (unless of course you try to modify mutable fields, but that's a different story). Therefore, to return something which is the sum of two feetInches, you must create a new feetInches object and return that.
// return type scope resolution ... |
7,593,086 | 7,593,152 | Why use non-member begin and end functions in C++11? | Every standard container has a begin and end method for returning iterators for that container. However, C++11 has apparently introduced free functions called std::begin and std::end which call the begin and end member functions. So, instead of writing
auto i = v.begin();
auto e = v.end();
you'd write
auto i = std::be... | How do you call .begin() and .end() on a C-array ?
Free-functions allow for more generic programming because they can be added afterwards, on a data-structure you cannot alter.
|
7,593,165 | 7,593,468 | Object of abstract class type "Animal" is not allowed: (C++) | I'm trying to store things into vector but there're few problems.
These are my code.
Animal.cpp
#include "Animal.h"
#include "Cattle.h"
#include "Sheep.h"
#include <iostream>
#include <string>
using namespace std;
Animal::Animal(int newid, double newweight, int yy, int mm, int dd, double newaccDose, char newsex)
{
... | virtual double calcDose()
This says "It is possible to calcDose() for everything which is an Animal, and different Animals may do it differently..."
= 0;
"... but there is no 'generic' way to do it for Animals; each one must specify its own method".
You may not construct an unspecified sort of Animal because, by defini... |
7,593,279 | 7,593,628 | Linking problem when derived class calls a template function in base class | I have a class Base in base.h, which has a template function
class Base {
template <typename T> void test(T a);
}
this template is supposed to read in int or double type, and I have class Derived, which is derived from class Base
I tried to call function test in class Derived, but I have the linker error.
In the end... | C++ templates must be defined (given a complete function body) in the same translation unit (.CPP file plus all included header files) where they are used. In your header file, all you have done is declared (given the name and signature of) the function. The result is that when you include base.h, all the compiler sees... |
7,593,479 | 7,595,222 | is there some c++ library / source similar to boost program_options but for *keyboard shortcut auto-gen help* ? | So, I have some c++ source with key bindings like:
switch( keypressed )
{
case 'c':
cam_handle->Yaw(min_angle );
break;
case 'd':
cam_handle->Yaw( -min_angle );
break;
case 's':
cam_handle->Pitch(min_angle );
break;
case 'x':
cam_handle->Pitch( -min_angle );
break;
case 'z':
cam_handle->Roll( min_an... | In my opinion these are two different pairs of shoes. If you like to create and ship documentation about your application I think it might not be the best to make it accessible via a --help option. It might be okay for small programs, but boost::program_options is certainly not the best way to deal with this.
If you wa... |
7,593,710 | 7,593,954 | How to write a `<<` operator for boost::tuple? | In the sample code below, it shows that boost::tuple can be created implicitly from the first template argument.
Because of that I am not able to write a << operator as it becomes ambiguous.
Also I don't understand why ostringstream& << float is also ambiguous. This does not have any implicit construction. Why does th... | The problem is not with the tuple, but with your operator. This works fine :
ostream& operator<<(ostream& os_, Mytuple tuple_)
{
os_ << tuple_.get<0>(); // Error because int is implicitly converted into Mytuple. WHYY?
os_ << tuple_.get<1>(); // No Clue Why this is ambiguous.
//os_ << tuple_.get<2>();... |
7,593,900 | 7,599,122 | How to get information about key container through certificate public key in CryptoAPI? | In C# I can do this by using
public static CspKeyContainerInfo GetKeyConatinerInformation(X509Certificate2 certificate)
{
if (certificate == null)
throw new ArgumentNullException("certificate");
ICspAsymmetricAlgorithm key = certificate.PublicKey.Key as ICspAsymmetricAlgorithm;
if (key == null)
... | Here is a program written by Mounir IDRASSI. This will provide you with the information you are looking for.
Also look for the related answer here.
|
7,594,273 | 7,594,304 | How to validate user input a number and the number greater than 0 | I'm trying to validate user input that user must enter number and it must be greater than 0, the validation of only numbers I got it working; however, I can't seem to incorporate the validation of greater than 0
float income;
cout << "How much did you earn last year: ";
//validating imput for income
while(!(ci... | Just add the condition to the while, and handle it in the loop:
while ( !(cin >> income) || income < 0.0 ) {
if ( !cin )
// Clean up input stream...
else
// Must be negative number...
}
|
7,594,508 | 7,594,577 | Modulo operator with negative values | Why do such operations:
std::cout << (-7 % 3) << std::endl;
std::cout << (7 % -3) << std::endl;
give different results?
-1
1
| From ISO14882:2011(e) 5.6-4:
The binary / operator yields the quotient, and the binary % operator
yields the remainder from the division of the first expression by the
second. If the second operand of / or % is zero the behavior is
undefined. For integral operands the / operator yields the algebraic quotient wit... |
7,594,808 | 7,594,934 | What use cases necessitate #define without a token-string? | I have encountered the #define pre-processor directive before while learning C, and then also encountered it in some code I read. But apart from using it to definite substitutions for constants and to define macros, I've not really understook the special case where it is used without a "body" or token-string.
Take for ... | This is used in two cases. The first and most frequent involves
conditional compilation:
#ifndef XYZ
#define XYZ
// ...
#endif
You've surely used this yourself for include guards, but it can also be
used for things like system dependencies:
#ifdef WIN32
// Windows specific code here...
#endif
(In this case, WIN32... |
7,595,243 | 7,595,321 | Specialize template for any vector<any_arithmetic_data_type> | I have got a template method with two specialized versions for type bool and vector<string>.
Base version:
template <class T>
const T InternGetValue(const std::string& pfad) const
{
...
}
Specialized versions:
template <>
const bool InternGetValue(const std::string& pfad) const
{
...
}
template <>
const std... | I think std::enable_if and std::is_integral together can solve this problem:
template<typename T>
std::vector<typename std::enable_if<std::is_integral<T>::value, T>::type>
f(const std::string& d);
If std:: doesn't have them, then use boost:: if you can. It has them.
|
7,595,284 | 7,595,450 | Is it worth to insert `const`-correctness | I'm currently confronted with a C++ project written by some senior programmers consisting of about 400 files and 200 classes.
The code is well elaborated, works fine and stable.
While I'm adding some features, for me it is just ordinary practice to take care about const-correctness.
But if I start to declare my new m... |
Should I invest the amount of time to introduce const-correctness into this code?
If you feel that you can get it all done in a reasonable time, sure. const-correctness is a good thing, so if you can adjust the codebase to employ it properly then that can never be bad.
It all comes down to how much time you have avai... |
7,595,350 | 7,595,571 | C++: Logical Comparison as conditional statement? | Ran across some code that used this, which led me to wonder.
if(condition) foo = bar();
condition && (foo = bar());
Are these two segments of code equal to a compiler? If not, in what ways would they differ?
| Unless && is overloaded for the combination of types of condition and foo they will have identical behavior - the latter will work this way:
bool result;
if( !condition ) {
result = false;
} else {
foo = bar();
result = foo != 0;
}
and result gets ignored
that's usual short-circuiting - if the first com... |
7,595,396 | 7,595,423 | permutation computing in c++ | I want to write a program that gets an integer n and prints all the permutations of 1,2,...,n.
I know there is a recursive way to do this and I know the overhead of function calls.
Is there any way to do this without recursion??
| Yes, you can do it iteratively with std::next_permutation from <algorithm> as a while condition, or depending on how you set up the loop this may be one of the occasions where do...while is more appropriate.
|
7,595,407 | 7,595,470 | String operators C++ | I was wondering if you can compare two strings using ==. I have a function which takes in a const value &item and since its a value type there is no way I can determine what type the value is, hence if the value type is a string, == may not work.
Hence the question, what would be the best way to tackle this problem? I... | In C++ operator == for std::string compares the content of the strings.
|
7,595,541 | 7,595,609 | const qualification conversion | From (4.4/1 ) It reads
An rvalue of type “pointer to cv1 T” can be converted to an rvalue of
type “pointer to cv2 T” if “cv2 T” is more cv-qualified than “cv1 T.”
I don't know where the standard defines 'more cv-qualifield' type but as I understood a declarator with const is more cv-qualified than than a non-const... | Table 6 in 3.9.3/4 gives the partial ordering of cv-qualifiers and 3.9.3/4 also gives the definition of more cv-qualified.
no cv-qualifier < const
no cv-qualifier < volatile
no cv-qualifier < const volatile
const < const volatile
volatile < const volatile
|
7,595,869 | 7,595,899 | Exceptions handling guidelines for C++ | I understand benefits of using exceptions handling in C++ and I'm aware that it may be tricky. One of rule says, that every function may throw. Ok, but there are situations, where we want to make sure, that function does not throw. I'm looking for any well-known practices or guidelines for handling such situations. Exa... | I think you need to understand RAII as a starting point.
Once you're using RAII correctly, you'll find that most of the case where you thought you needed to manually finalize objects have magically disappeared: And, so in a lot of cases, that means you can dispense with the try/catch/finalize approach entirely.
As oth... |
7,595,914 | 7,595,959 | how can I mix objective-c objects (i.e UITextView) with pure c++ UI like DooleJump leadboard | How can I mix objective-c objects (i.e UITextView) with pure c++ UI like DooleJump leadboard, which is scrollable and the text in it is from system`font. Can somebody help me ..thanks...
| I can't see the relation between DooleJump leadboard being scrollable and using system fonts, and the use of C++.
Anyway, to answer the question, if you need to mix Objective-C and C++, use Objective-C++ (and rename all your files from ".m" to ".mm")
|
7,595,950 | 7,596,037 | Can I create a pthread inside a pthread, which is already created by the main? | Will I run into an error if I create a pthread_create inside a pthread, which is created by the main function. If, I can then what all things I should take care of???
Important....:I am doing a socket programming, where I have opened 5 threads each on separate ports which are listening on ports, when ever I receive a m... | pthread_create creates a new thread. Independently of where it is
called. And creating a new thread for a connection when listening on a
port is pretty much standard procedure.
|
7,595,982 | 7,624,952 | COLLADA: Inverse bind pose in the wrong space? | I'm working on writing my own COLLADA importer. I've gotten pretty far, loading meshes and materials and such. But I've hit a snag on animation, specifically: joint rotations.
The formula I'm using for skinning my meshes is straight-forward:
weighted;
for (i = 0; i < joint_influences; i++)
{
weighted +=
jo... | I started by comparing my values to the ones I read from Assimp (an open source model loader). Stepping through the code I looked at where they built their bind matrices and their inverse bind matrices.
Eventually I ended up in SceneAnimator::GetBoneMatrices, which contains the following:
// Bone matrices transform fro... |
7,596,012 | 7,596,027 | Clean way to cancel object creation | I'm wondering how to stop/cancel the creation of an object, risen by new(). Maybe if some preconditions fail and the object isn't needed.
Check before new?
Check within constructor, returning null or something special, don't know how to handle ...
Check after new was successful and object is alive. Call a member funct... | None of the above.
If the object cannot be constructed because of unmet conditions, the constructor should throw an exception with the throw statement.
|
7,596,183 | 7,596,700 | Is RVO (Return Value Optimization) applicable for all objects? | Is RVO (Return Value Optimization) guaranteed or applicable for all objects and situations in C++ compilers (specially GCC)?
If answer is "no", what are the conditions of this optimization for a class/object? How can I force or encourage the compiler to do a RVO on a specific returned value?
| Return Value Optimization can always be applied, what cannot be universally applied is Named Return Value Optimization. Basically, for the optimization to take place, the compiler must know what object is going to be returned at the place where the object is constructed.
In the case of RVO (where a temporary is returne... |
7,596,406 | 7,596,439 | stdio.h not standard in C++? | I know most compilers allow both:
#include <stdio.h>
and
#include <cstdio>
But someone argued that <stdio.h> is not actually C++ standard. Is that true?
| stdio.h is standard, but deprecated. Always prefer cstdio in C++.
[n3290: C.3.1/1]: For compatibility with the Standard C library, the
C++ standard library provides the 18 C headers (D.5), but their use is
deprecated in C++.
[n3290: D.5/3]: [ Example: The header <cstdlib> assuredly
provides its declarations and ... |
7,596,612 | 7,614,252 | Benchmarking (python vs. c++ using BLAS) and (numpy) | I would like to write a program that makes extensive use of BLAS and LAPACK linear algebra functionalities. Since performance is an issue I did some benchmarking and would like know, if the approach I took is legitimate.
I have, so to speak, three contestants and want to test their performance with a simple matrix-matr... | I've run your benchmark. There is no difference between C++ and numpy on my machine:
Do you think my approach is fair, or are there some unnecessary overheads I can avoid?
It seems fair due to there is no difference in results.
Would you expect that the result would show such a huge discrepancy between the c++ and ... |
7,596,633 | 7,596,758 | Merging programs of different languages | I have three programs (one in C++ + WinAPI, another one in C# .NET and the last one in Java) with different functions. I am about to choose one and implement functions of the other two. Is it possible to somehow merge them? I need to have them in one GUI, under one process (at least visually). IPC isn't a problem.
Than... | I think the best/easiest thing you could do is make the GUI only in C#, in windows clients you could use Windows Forms or WPF, in web based you can use ASP.NET WebForms or ASP.NET MVC.
in all these cases except MVC (Razor) you have really good tools for designing and customizing the GUI within Visual Studio.
Your C++ c... |
7,596,757 | 7,597,141 | passing boost python enum as parameter | I defined
enum_<mytype>("mytype")
.value("one",1)
.value("two",2)
;
in my BOOST_PYTHON_MODULE.
when I expose a class with a function taking a parameter of type mytype (essentially, an int), like:
void myfunc(mytype m) {
...
}
I get the following compiler warning:
dereferencing pointer 'p.2311' (or whateve... | It's hard to say exactly without seeing the warning, but it's most likely caused by some macros from Python headers. To be safe, compile the code that uses Python (and Boost.Python) with -fno-strict-aliasing.
|
7,596,993 | 7,597,043 | returning boost list from exposed class | I exposed a c++ class to python, one of its methods is something like:
boost::python::list getList() {
boost::python::list l
...
return l;
}
it works perfectly, and I dont get any compiler warning.. since I heard that working with containers is a mess with c++/python, I was just wondering if what I did is ... | Yes, this is the correct way of returning a list in Boost.Python. The "mess" is handled by boost::python::list.
|
7,597,062 | 7,597,168 | Qprocess messes my linux command up (i think). how to fix? | I need to force my c++ QT4 application to read results from a linux command. I am trying to use Qprocess but as soon as my command gets complicated it get messed somehow (just guessing) and does not work.
Here i try to make for yu a small example:
QProcess process;
command = "ls -l | grep a | sort";
qDebug() << "Execut... | QProcess does not support shell commands. The pipe symbols is thus not interpreted by a shell, but instead directly passed to ls. ls interprets it as file name, and complains because apparantly there is no file named |.
You need to setup pipes manually by redirecting input and output streams of QProcess objects. Rea... |
7,597,260 | 7,597,469 | How to get the tail of a std::string? | How to retrieve the tail of a std::string?
If wishes could come true, it would work like that:
string tailString = sourceString.right(6);
But this seems to be too easy, and doesn't work...
Any nice solution available?
Optional question: How to do it with the Boost string algorithm library?
ADDED:
The method should be ... | There is one caveat to be aware of: if substr is called with a position past the end of the array (superior to the size), then an out_of_range exception is thrown.
Therefore:
std::string tail(std::string const& source, size_t const length) {
if (length >= source.size()) { return source; }
return source.substr(sourc... |
7,597,356 | 7,597,538 | Error in creating temp files on mac os | Om mac OS 10.6.7, I am creating some files in the temp directory. After a while I start getting failure in open syscall and error returned is 24 which means disk full. I checked the disk space and still 80GB is available. Are there any restrictions or special quota on temporary directory? I used following flags to open... | Error 24 is EMFILE meaning too many open files.
|
7,597,410 | 7,630,130 | How to build parse tree? | Have found C++ BNF and there next lines
selection-statement:
if ( condition ) statement
if ( condition ) statement else statement
Now trying to write parser. Need to build parse tree. On input i have BNF and source file. But i'm stucked in how i can point my parser what if condition evaluated to true, then it ... | Conditional statements have a simple recursive structure. The corresponding recursive descent parser has a similarly simple recursive structure. Abstractly, the interior conditionals are parsed as follows:
<cond> -> if <expression> then <statement> [else <statement>]
cond :
a = parse expression
b = parse statement... |
7,597,449 | 15,806,597 | getline() reads an extra line | ifstream file("file.txt");
if(file.fail())
{
cout<<"Could not open the file";
exit(1);
}
else
{
while(file)
{
file.getline(line[l],80);
cout<<line[l++]<<"\n";
}
}
I am using a two dimensional character array to keep the text (more than one line) read from a file t... | This will solve your problem:
ifstream file("file.txt");
if(!file.good())
{
cout<<"Could not open the file";
exit(1);
}
else
{
while(file)
{
file.getline(line[l],80);
if(!file.eof())
cout<<line[l++]<<"\n";
}
}
Its more robust
|
7,597,474 | 7,597,661 | Mixing template specialisation and enable_if in a function template with only a templated return type | I have the following code that fails to compile on VC2010:
#include <type_traits>
using namespace std;
template <class C>
typename enable_if<true, C>::type
foo()
{ return C(); }
template <>
bool
foo()
{ return true; } // error C2785: 'enable_if<true,_Type>::type foo(void)'
// and 'bool foo(void)' h... | A function template specialization is (thankfully!) not required to return the same type as the non-specialized template, so this is not the issue here.
In fact, enable_if has nothing to do with your error, your code is simply missing the template arguments list in the specialization:
template <>
bool foo<bool>()
{ ret... |
7,597,516 | 7,597,614 | How can I stop my Windows console application triggers beeps when displaying binary data | I wrote a windows console application that receives binary data from a third party provider.
For Debug and logging purposes, I display the binary data on the output (the console).
Unfortunately when the character 7 is displayed it triggers a beep.
Here is a code that can trigger it:
int main(int argc, char** argv)
{... | You could unplug the beeper in your computer.
If that is not an option:
If you have a method debug(String s) that outputs the string s, you could replace character 7 by something else to avoid the beep.
Another way would be to output the text in hexadecimal form.
|
7,597,634 | 7,598,042 | Name spaces in c++ and c | Not that I would ever write the code like the following in my professional work, the following code is legal and compiles without warnings in c++ and c:
#include <stdlib.h>
typedef struct foo { int foo; } foo;
foo * alloc_foo () {
return (struct foo*) malloc(sizeof(foo));
}
struct foo * alloc_struct_foo () {
... |
foo * foo; is perfectly legal, so why isn't int foo (foo*); legal?
Because there already is a type named foo in the same declaration context as your function. You cannot have a type and a function of the same name in the same scope.
How does this work at all in C++?
Because you are allowed to hide names in nested s... |
7,598,067 | 7,599,148 | How to create a Windows-style textbox in a C++ Win32 application | I tried this:
#include <windows.h>
#pragma comment(linker,"/manifestdependency:\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='x86' publicKeyToken='6595b64144ccf1df' language='*'\"")
LRESULT CALLBACK WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam);
int APIE... | Instead of using CreateWindow, use CreateWindowEx and specify WS_EX_CLIENTEDGE as the first parameter.
You can compare the styles of your created edit control with a stock one (for example, when you show 'Properties' on a file in the explorer) with the Spy++ tool that comes along Visual Studio.
|
7,598,126 | 7,598,712 | Detecting arrow keys input in C++ using curses on a unix platform is not working after calling a system command | I have an application in which the user inputs data and needs to be able to move around the screen using the arrow keys. now I've used the curses library but I am having a problem detecting the arrows after calling a system command which is
system("more filename);
I've been able to detect them before calling this com... | Try the advice here: http://tldp.org/HOWTO/NCURSES-Programming-HOWTO/misc.html#TEMPLEAVE
Some times you may want to get back to cooked mode (normal line buffering mode) temporarily. In such a case you will first need to save the tty modes with a call to def_prog_mode() and then call endwin() to end the curses mode. Th... |
7,598,152 | 7,598,179 | Changing value of constant object with pointer | There is such code:
#include <iostream>
int main(){
const int a = 2;
int* ptr = (int*)&a;
*ptr = 3;
std::cout << &a << " " << ptr << " " << a << " " << *ptr << std::endl;
return 0;
}
Result:
0xbf88d51c 0xbf88d51c 2 3
Why these two values differ? What does it here happen?
| int* ptr = (int*)&a;
This is dangerous (this itself doesn't invoke UB, though). But this,
*ptr = 3;
This invokes undefined behavior (UB), because you're attempting to modify the const object pointing to by ptr. UB means anything could happen. Note that a is truly a const object.
§7.1.5.1/4 (C++03) says,
Except that ... |
7,598,443 | 7,599,560 | Can you change a std::list while iterating through it? | In the following functions, it it entirely possible for the IObserver's Process() function to try to remove itself from the notify list, using the this pointer's DeleteObserver().
This causes hell with the iterators (not surprisingly!), is there a way round this? Or should I be taking a closer look at my design?
void c... | Edit:
Some people in comments corrected me, so I will change this answer. But don't upvote, as it's the commenters' solution, not mine.
(*iter++)->Process();
|
7,598,476 | 7,600,261 | MSXML loadXML won't load elements with namespace prefixes... Why? | Hiho,
i guess, it's a pretty stupid question, but i had to switch to C/C++ recently and haven't done this in years.
And right now I'm stuck on the following:
Given XML Element as a simple String:
<myns:factor>1000</myns:factor>
I have to parse the string, add the resulting Element to a surrounding MSXML2 DOM object wi... | The Problem
The string
<myns:factor>1000</myns:factor>
is not well-formed XML (with regard to namespaces). That's why XML parsers generally won't load it.
It's not well-formed because it uses the namespace prefix "myns", which has not been declared.
The Solution
If you changed the XML to something like this, it would ... |
7,598,484 | 7,600,465 | How to get the array of RGB values for each pixel of the client area of a window | Is there a way to receive the colour values for each pixel in the client area of a window, with gdi?
| As noted in comment by @JerryCoffin. Here's a simple example
hDC = GetDC(hwnd);
hBitmap = CreateCompatibleBitmap(hDC, width, height);
hMemDC = CreateCompatibleDC(hDC);
hOld = SelectObject(hMemDC, hBitmap);
BitBlt(hMemDC, 0, 0, width, height, hDC, x, y, SRCCOPY);
// Clean up
DeleteDC(hMemDC);
ReleaseDC(hwnd, hDC);
You... |
7,598,514 | 7,598,605 | "Symbol 'map' could not be resolved" in namespace | Hello!
I am currently developing an game engine. Even though I only just started, I have already run into a problem.
I have this code:
#ifndef INSTANS_H_
#define INSTANS_H_
#include <map>
#include "Core/Version.h"
#include "Core/Window.h"
#include "Core/Component.h"
#include "Core/Game.h"
namespace Instans
{
class... | The third parameter to map is a comparison function type, not a third contained data type. Chances are that's what's causing your problem.
I can't quite tell what you're trying to do but if you're trying to map an int/string composite key to a Component you could use:
std::map<std::pair<int, std::string>, Component*>
|
7,598,758 | 7,598,811 | c++ const symbols inflating linked file | In C++ is legal to put a const in the header file, usually the C way would be to put the extern declaration in the header and the definition in just one compilation unit, but in C++, the former technique leads to an increased binary since the symbols are not removed while linking (tested with gnu ld and visual studio).... | There are two real choices you have. You can define a constant with external linkage, or not. With internal linkage, you'll only a copy in each translation unit that actually uses the constant, assuming optimization is turned on.
Internal linkage:
// a.h
const double AI_LIKE_COOKIES = 5.0;
External linkage:
// a.h
e... |
7,598,800 | 7,598,884 | How to loop through a map and assign the value to an array in C++? | I have a map<id,age>,; how to get the age of each <id,age> pair, and assign the age to a C-style array in C++?
what is the efficient way to do it? I mean how to fill the C-style array in the same order as map?
| If you decide to stick with the fixed array approach
//Assuming both id and age are integers
map<int,int> myMap; // Your id and age map
map<int,int>::iterator it;
int myList[100];
int i = 0;
for(it = myMap.begin(); (i < 100 && it != myMap.end()); it++)
{
myList[i++] = (*it).second;
}
A MUCH better approach is to use... |
7,598,923 | 7,809,560 | Gtk::Widget on_enter_notify when mouse is down? | I'm trying to have a list of Gtk::Widgets that when clicked on I need to highlight the widget, but when the user holds the button down, and drags to another widget, the first one will 'unhighlight' and the new one will highlight on enter_notify.
I've tried using the on_enter_notify_event, and on_button_press_event in m... | Okay, apparently when a widget gets activated or clicked, the GdkDevice 'grab()'s the widget and only sends events to THAT widget. So I've taken the device from the event, and called 'ungrab()' on it so it allows the other cells to receive events. Then on my other cells I check the event->state in the on_enter_notify_e... |
7,598,963 | 7,599,098 | Float to Char Array to std::string | I'm having a bit of a problem with this piece of code:
string StringServices::ToStringf(float value)
{
char buffer[10];
sprintf (buffer, "%f", value);
return (string) buffer; // signal SIGABRT
}
Its been working previously and continues to work for other calls, but I currently get a SIGABRT on the retu... | You probably overflowed your buffer because you're not using snprintf. You have this tagged C++ so do it that way:
std::string buffer = boost::lexical_cast<std::string>(value);
Or without boost use a string stream:
std::ostringstream os;
os << value;
// os.str() has the string representation now.
|
7,599,407 | 7,599,814 | How would you make an iterator as a key of hash_map? | How would you make an iterator as a key of hash_map?
How would you define it under gcc, Microsoft c++?
E.g.
vector<string>::iterator i;
hash_map<vector<string>::iterator, int> h;
or
list<string>::iterator i;
hash_map<list<string>::iterator, int> h;
THis gives an error as iterators are not predefined a... | If you know what you're doing (e.g. if the iterators are taken from a non-modifiable container), you can try to exploit the fact that &*it should be unique for each element:
typedef std::string my_container;
typedef my_container::const_iterator my_iterator;
struct IteratorHasher
{
std::size_t operator()(const my_ite... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.