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 |
|---|---|---|---|---|
1,815,172 | 1,815,214 | Is it possible to see definition of Q_SIGNALS, Q_SLOT, SLOT(), SIGNAL() macros? (Qt) | Is it possible to see definition of Q_SIGNALS, Q_SLOT, SLOT(), SIGNAL() macros in Qt framework?
P.S. Google gave me nothing in this question.
| Form qobjectdefs.h, for a non-debug compilation:
#define Q_SLOTS
#define Q_SIGNALS protected
#define SLOT(a) "1"#a
#define SIGNAL(a) "2"#a
The Q_SLOTS and Q_SIGNALS declarations are only treated specially by the moc run, in the final compilation they reduce to simple method declarations. SIGNAL() and SLOT() cr... |
1,815,202 | 1,815,209 | C++ bindings to jGoodies? | Thus far the best C++ UI libraries I've run into are Qt, GTK, and wxWidgets; Are there existing libraries similar to jGoodies or 'better'. I am interested in mature (yet simple) technologies.
| QT is about as good as it gets AFAIK.
Binding a Java toolkit to C++ is a rather convoluted idea since in C++ you usually have a direct interface to the OS widgets. going full circle through Java is guaranteed to have uglier results.
|
1,815,297 | 1,815,336 | How do I convert an image into a buffer so that I can send it over using socket programming? C++ |
How do I convert an image into a buffer so that I can send it over using socket programming? I'm using C++ socket programming. I am also using QT for my Gui.
Also, after sending it over through the socket, how do I put that image back together so it can become a file again?
If someone could put up some sample code th... | Assuming that you want to send an image as a file,
here is pseudocode to send it through a TCP connection.
Client A
Set up a connection
Open a file in binary mode
Loop:
read/load N bytes in a buffer
send(buffer)
Close file
Close connection
Client B
Listen and accept a connection
Create a new file... |
1,815,431 | 1,815,440 | error C4430: missing type specifier / error C2143: syntax error : missing ';' before '*' | I am getting both errors on the same line. Bridge *first in the Lan class. What am i missing?
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
using namespace std;
class Lan{
Bridge *first;
Bridge *second;
Host hostList[10];
int id;
};
class Bridge{
Lan lanList[5];
};
class Host{
... | Declare Bridge before Lan
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
using namespace std;
class Bridge;
class Lan{
Bridge *first;
Bridge *second;
Host hostList[10];
int id;
};
class Bridge{
Lan lanList[5];
};
|
1,815,486 | 1,815,511 | C# & C++: "Attempted to read or write protected memory" Error | The following code compile without errors. Basically, the C#2005 Console application calls VC++2005 class library which in turn calls native VC++6 code. I get the following error when I run the C#2005 application:
"Unhandled Exception: System.AccessViolationException: Attempted to read or write protected memory. This i... | The main problem from my point of view is you are storing an iterator to a vector in your stdStringContainer class. Remember that whenever vector resizes all the existing iterators are invalidated. So whenever you do insert operation into the vector it may be possible that it resizes and your existing iterator becomes ... |
1,815,490 | 1,815,575 | How to get emacs tempo mode working with abbrevs for C/C++? | I've been experimenting with emacs tempo mode and it seems likely to save me lots of typing (always a good thing), but I haven't gotten it to work exactly the way I want it. On the wiki, there is an example for elisp similar to what I want to do which works as expected. Here is the complete .emacs that I tested it on... | The last argument to your define-abbrev should be 'tempo-template-c-include . Also, I'm not sure you can have a dash in there, i.e. it might have to be cinclude instead of c-include:
(define-abbrev c-mode-abbrev-table "cinclude" "" 'tempo-template-c-include)
|
1,815,513 | 1,815,926 | Problem with a volumetric fog in OpenGL | Good day.
I am trying to make a volumetric fog in OpenGL using glFogCoordfEXT.
Why does a fog affect to all object of my scene, even if they're not in fog's volume? And these objects become evenly gray as a fog itself. Here is a pic
alt text http://img248.imageshack.us/img248/9281/fogp.jpg
Code:
void CFog::init()
... | You seem to not be clear on how GL_fog_coord_EXT works.
You're saying that an object is "outside the fog volume" but OpenGL does not have any notion of a fog volume. At any point, either Fog is completely off, or it's on, in which case the fog equation will be applied with a fog coefficient that depends both on the fog... |
1,815,542 | 1,821,283 | How to let omnicppcomplete automatically close empty argument lists? | Is it possible to let Vim's omnicppcomplete automatically close argument lists for functions or methods that do not take any arguments?
For example, assuming v is an STL vector, when auto completing v.clear(), we end up with:
v.clear(
It would be nice if the closing parenthesis would be automatically added. Is this po... | It looks like it should be possible: I'm not sure whether I have the latest version of the omnicppcomplete script, but in my autoload/omni/cpp/complete.vim, there is a function called s:ExtendTagItemToPopupItem. In this function, there is:
" Formating information for the preview window
if index(['f', 'p'], tagItem.kin... |
1,815,613 | 1,815,633 | What next generation low level language is the best bet when migrating a code base? | Let's say you have a company running a lot of C/C++, and you want to start planning migration to new technologies so you don't end up like COBOL companies 15 years ago.
For now, C/C++ runs more than fine and there is plenty dev on the market for it.
But you want to start thinking about it now, because given the huge ru... | D and Go will probably just become as popular as Python and Ruby are today. They each fill a niche, and even though D was supposed to be a full-fledged replacement of C++, it probably will never acquire enough mass to push C++ away. Not to mention that they both aren't stable/mature enough, and it's unknown whether you... |
1,815,643 | 1,815,694 | How to properly return reference to class member? | class Foo {
protected:
QPoint& bar() const;
private:
QPoint m_bar;
};
QPoint& Foo::bar() const {
return m_bar;
}
I got this error:
error: invalid initialization of reference of type ‘QPoint&’ from expression of type ‘const QPoint’
However it works if I change it to this:
QPoint& Foo::bar() const ... | In a non-const member function of class Foo the this pointer is of the type Foo* const - that is, the pointer is const, but not the instance it points to. In a const member function, however, the this pointer is of the type const Foo* const. This means that the object it points to is constant, too.
Therefore, in your ... |
1,815,688 | 1,954,144 | How to Use CCache with CMake? | I would like to do the following: If CCache is present in PATH, use "ccache g++" for compilation, else use g++. I tried writing a small my-cmake script containing
CC="ccache gcc" CXX="ccache g++" cmake $*
but it does not seem to work (running make still does not use ccache; I checked this using CMAKE_VERBOSE_MAKE... | I personally have /usr/lib/ccache in my $PATH. This directory contains loads of symlinks for every possible name the compiler could be called from (like gcc and gcc-4.3), all pointing to ccache.
And I didn't even create the symlinks. That directory comes pre-filled when I install ccache on Debian.
|
1,815,705 | 1,815,784 | I am new to threads, What does this compile error mean? | Using C++.
pthread_t threads[STORAGE]; // 0-99
...
void run()
Error>>> int status = pthread_create(&threads[0], NULL, updateMessages, (void *) NULL);
if (status != 0)
{
printf("pthread_create returned error code %d\n", status);
exit(-1);
}
...
void ClientHandler::updateMessages(void *)
{
string reqUp... | A pointer to a member function is different from a global function with the same signature since the member function needs an additional object on which it operates. Therefore pointers to these two types of functions are not compatible.
In this case this means that you cannot pass a member function pointer to pthread_c... |
1,815,903 | 1,815,922 | Const correctness in C++ operator overloading returns | I'm a little confused as to why I've been told to return const foo from a binary operator in c++ instead of just foo.
I've been reading Bruce Eckel's "Thinking in C++", and in the chapter on operator overloading, he says that "by making the return value [of an over-loading binary operator] const, you state that only a ... | When you say ++x, you're saying "add 1 to x, store the result back into x, and tell me what it was". This is the preincrement operator. But, in ++(a+b), how are you supposed to "store the result back into a+b"?
Certainly you could store the result back into the temporary which is presently holding the result of a+b, ... |
1,815,976 | 1,816,757 | Download an Image file from web server using VC++ 9.0 | I want to code a VC++ 9 based console application which downloads an image from a webserver.
I have code which used to run in VC++ 6, but its giving lot of compilation errors in VC++ 9.0.
I need code which compiles in VC++ 9.0 using MS Visual Studio 2008.
Also I need only win32 code and not MFC.
| To download something from the Web you could use libcurl library. It doesn't use MFC.
|
1,816,023 | 1,816,072 | Reading/Writing Magnetic Striped ID Cards in Linux | How would I accomplish this? Is there a specific brand of card reader/writer that works easily with linux and windows (linux being more important as I need to deploy these to cheap kiosks).
| Googling "magnetic card reader writer linux" will give you lots of hits. Also search for "stripe snoop" - it's open-source software looks like it reads well, but doesn't write yet.
It's been my experience with similar devices that if you find one at a price that works for you, then even if the manufacturer doesn't supp... |
1,816,052 | 1,816,095 | big integers with fixed length | I am looking for a library for big integers but with fixed width (128 or 256 would be enough). The reason is I don't want any allocation on the heap.
I tried to make them myself but implementing multiplication, division and modulo an efficient way seems to be quite a pain.
Does this already exists somewhere ?
Thanks
| Take a look at the GMP library: www.gmplib.org
Quoting from the function categories:
Low-level positive-integer,
hard-to-use, very low overhead
functions are found in the mpn
category. No memory management is
performed; the caller must ensure
enough space is available for the
results. (...)
That seems to... |
1,816,319 | 1,816,382 | Reading directly from an std::istream into an std::string | Is there anyway to read a known number of bytes, directly into an std::string, without creating a temporary buffer to do so?
eg currently I can do it by
boost::uint16_t len;
is.read((char*)&len, 2);
char *tmpStr = new char[len];
is.read(tmpStr, len);
std::string str(tmpStr, len);
delete[] tmpStr;
| std::string has a resize function you could use, or a constructor that'll do the same:
boost::uint16_t len;
is.read((char*)&len, 2);
std::string str(len, '\0');
is.read(&str[0], len);
This is untested, and I don't know if strings are mandated to have contiguous storage.
|
1,816,402 | 1,816,428 | How can I do an HTTP redirect in C++ | I'm making an HTTP server in c++, I notice that the way apache works is if you request a directory without adding a forward slash at the end, firefox still somehow knows that it's a directory you are requesting (which seems impossible for firefox to do, which is why I'm assuming apache is doing a redirect).
Is that a... | Determine if the resource represents a directory, if so reply with a:
HTTP/1.X 301 Moved Permanently
Location: URI-including-trailing-slash
Using 301 allows user agents to cache the redirect.
|
1,816,431 | 1,824,731 | QT Webkit & OpenGL Rendering Context | Would it be possible to create a window with a webpage using a webkit component using QT4, then embed an OpenGL context into the middle in the same way a java applet or a flash applet may appear normally?
| Sure, you can embed any QWidget into a web page shown through a QWebView, including a QGLWidget. This would be a starting point in the docs: http://doc.trolltech.com/4.5/qwebpage.html#setPluginFactory .
|
1,816,451 | 1,816,470 | Are there any CURL alternatives for C++? | I hate CURL it is too bulky with too many dependencies when all I need to do is quickly open a URL. I don't even need to retrieve the contents of the web page, I just need to make the GET HTTP request to the server.
What's the most minimal way I can do this and don't say CURL !@#$
| There are lots of choices! Try libwww -- but be warned, most people strongly prefer libcurl. It's much easier to use.
|
1,816,498 | 1,816,500 | Creating custom message types in win32? | Is there a way to define and send custom message types in Win32, to be caught by your Main message handler? For example, my main message handler captures messages such as WM_PAINT, WM_RESIZE, WM_LBUTTONDOWN etc. Can I create my own WM_DOSOMETHING? If so, how would I send this message?
Ah, I actually just discovered thi... | Yes. Just declare a constant in the WM_USER range e.g.
#define WM_RETICULATE_SPLINES (WM_USER + 0x0001)
You can also register a message by name using the RegisterWindowMessage API.
You can then send these messages using SendMessage, PostMessage or any of their variants.
|
1,816,547 | 1,816,618 | Initialization: T x(value) vs. T x = value when value is of type T | T x(value) is usually the better choice because it will directly initialize x with value, whereas T x = value might create a temporary depending on the type of value.
In the special case where value is of type T though, my guess is that the expression T x = value will always result in exactly one copy constructor call.... | From the standard, copy-initialization for class types where the cv-unqualified type of the source type is the same as, or a derived class of the destination, has exactly the same behaviour as direct-initialization. The description of these two cases introduce a single paragraph describing the required behaviour which ... |
1,816,552 | 1,816,715 | Where does C++ standard define the value range of float types? | As far as I know floating point values are of the form n * 2^e, with
float range being n = -(2^23-1) - (2^23-1), and e = -126 - 127,
double range being n = -(2^52-1) - (2^52-1), and e = -1022 - 1023
I was looking through the C++ standard, but failed to find the place where the standard specifies this, or mandates the... | Just like integer numberic limits, the limits for float, double and long double are imported from the C standard. The minimum value for constants FLT_MAX, DBL_MAX and LDBL_MAX is 1E+37. For their *_MIN variants the maximum value is 1E-37.
|
1,816,628 | 1,816,694 | printing ip addresses using gdb | I am debugging a networking code and want to print ip addresses which are declared as int32.
when i print it using gdb print command, i get some values which is not much meaningful.
How can i possibly print them in meaningful format?
| Just use inet_ntoa(3) as so:
(gdb) p (char*)inet_ntoa(0x01234567) # Replace with your IP address
$1 = 0xa000b660 "103.69.35.1"
|
1,816,790 | 1,875,992 | Sun C++ Compilers and Boost | I am currently developing on OpenSolaris 2009-06. The Boost::MPL Documentation seems to suggest that sun compilers are not supported (the document was last updated in 2004 ). Boost's top level documentation seems to suggest that the sun compilers 5.10 onwards are supported -- I guess this is a general level of support ... | I guess since an exact answer has not been provided I must post one myself.
opensolaris(2009.06) and boost-1.4.1 seem to work well. The ./bjam picks the right switches and boost::mpl seems to work well with the sun compiler present. So, as far as I can tell the mpl documentation on compiler support is quite outdated.
|
1,816,851 | 1,817,009 | HLSL DirectX9: Is there a getTime() function or similar? | I'm currently working on a project using C++ and DirectX9 and I'm looking into creating a light source which varies in colour as time goes on.
I know C++ has a timeGetTime() function, but was wondering if anyone knows of a function in HLSL that will allow me to do this?
Regards.
Mike.
| Use a shader constant in HLSL (see this introduction). Here is example HLSL code that uses timeInSeconds to modify the texture coordinate:
// HLSL
float4x4 view_proj_matrix;
float4x4 texture_matrix0;
// My time in seconds, passed in by CPU program
float timeInSeconds;
struct VS_OUTPUT
{
float4 Pos : POSI... |
1,816,904 | 1,816,937 | segmentation fault at end of the program | I've got a bit problem. My program throws segmentation fault when returning zero in main.
The main function looks like this:
int main(int argc, char* argv[]){
ifstream fs("test.dat", ios::binary);
cSendStream sendstr(&fs,20);
char *zomg=sendstr.data();
//zomg[20]=0;
sendstr.read(20);
cout<<"B... | zomg[20]=0 is writing one past the end of the allocated array, but it is difficult to guess why the segfault is occurring. My guess is that your clever compiler is using alloca for the allocation and you are scribbling on the return address.
It might be fun to look at the assembly (usually -S) to see what's happening.
|
1,816,960 | 1,816,968 | setCurrentDrive? c++ win32 | How can I set the current drive in c++? I was unable to find anything on the MSDN site
| The string you use to set the directory can be prefixed by the drive letter -- i.e., "c:\program files".
Directories are set relative to your programs current working directory. If you start your program from 'X' drive you will not be able to move outside of 'X' using relative conventions/directory addressing. You nee... |
1,817,048 | 1,817,127 | Qt, how to set text edit scroll bar to the bottom? C++ | I have the text edit box as a chat window, but I was wondering if there was a way to set the scroll bar to be at the bottom to show the most updated message.
I am currently using Qt3 and C++.
chat_box->.... I tried looking and was only able to find "ScrollBarMode" but it only lets me turn it on or off or auto... which ... | scotchi's answer would be correct if it was Qt4. Qt3 solution would be something like:
QScrollBar *v = chat_box->verticalScrollBar();
v->setValue(v->maxValue());
I didn't test this code since I don't have Qt3 anymore. Check if it works.
|
1,817,266 | 1,817,273 | Is it better/faster to have class variables or local function variables? | Ok I know the title doesn't fully explain this question. So I'm writing a program that performs a large number of calculations and I'm trying to optimize it so that it won't run quite so slow. I have a function that is a member of a class that gets called around 5 million times. This is the function:
void PointCamera::... | By limiting the scope of your variables, you are giving more opportunity to the compiler optimiser to rearrange your code and make it run faster. For example, it might keep the values of those variables entirely within CPU registers, which may be an order of magnitude faster than memory access. Also, if those variables... |
1,817,334 | 1,817,355 | Library redefines NULL | I'm working with a library that redefines NULL. It causes some problems with other parts of my program. I'm not sure what I can do about it. Any idea? My program's in C++, the library's in C.
#ifdef NULL
#undef NULL
#endif
/**
* NULL define.
*/
#define NULL ((void *) 0)
Oh, and it produces these errors:
Generic.... | Can you rebuild the library without that define? That's what I'd try first. NULL is a pretty standard macro, and should be assumed to be defined everywhere.
Right now, your problem is that C++ doesn't allow automatic casts from void * to other pointer types like C does.
From C++ Reference:
In C++, NULL expands either ... |
1,817,445 | 1,817,450 | C++: static member functions and variables- redefinition of static variable? | I was trying to incorporate the Singleton design pattern into my code, but I started getting a weird error:
main.obj : error LNK2005: "private: static class gameState * gameState::state" (?state@gameState@@0PAV1@A) already defined in gameState.obj
If you're not familiar with the singleton pattern, it is basically used... | You need to put the definition of the static gameState* into exactly one source file, i.e. this line:
gameState* gameState::state = new gameState();
If you put it in a header which is included by multiple source files, each has a definition of gameState::state which leads to errors at link-time.
For the follow-up prob... |
1,817,508 | 1,817,526 | Is there a way to prevent construction during non-compound operations? | I have a vector class that has addition, multiplication, subtraction, division, etc operators. I'm trying to optimize my program (which does a lot of vector operations) and I'm realizing that about 50% of the time spent is in constructing and destructing vectors. I understand that this is because every time I call a no... |
I understand that this is because
every time I call a non-compound
mathematical operator for a vector, a
new vector is constructed. Is there a
way to prevent this without using
compound operators or expanding vector
operations?
Well, the nature of adding two things together to produce a third thing requir... |
1,817,599 | 1,817,611 | c++: Private constructor means no definition of that classes objects inside headers? | Yet another question, go me!...
Anyway, I have 2 classes with private constructors and static functions to return an instance of that class.
Everything was fine, I have a main.cpp file where I managed to get hold of my gameState object pointer, by doing:
gameState *state = gameState::Instance();
But now I seem to have... | It looks like you need to add a forward declaration of the opposite class to each class's header file. For example:
class actionHandler;
class gameState
{
private:
actionHandler *handler;
...
};
and:
class gameState;
class actionHandler
{
private:
gameState *state;
...
};
|
1,817,691 | 1,817,775 | How to use unordered_set in STL? | I am in need of a hash_map class in C++(STL). Primary operation is to put pair in the set and then check if it exists or not.
I am unable to find a sample code which does it to know if what I am declaration correctly or not.
#include <iostream>
#include <hash_map>
using namespace std;
using namespace __gnu_cxx;
typed... | Your problem is that hash<T> is only specialized for certain types. It can't magically make a hash function for any old type. You need to make your own hash function.
|
1,817,733 | 1,818,543 | Sound Monitoring in C++/Python | I'm looking for an API (or some information as to where to look/start) that will ultimately allow me to monitor sound being played by the computer.
My end goal (well, certain to eventually be a stepping-stone) is an oscilloscope.
Where should I begin to look (aside from Google, which has yielded unsatisfactory results... | As @cobbal noted, on Mac OS X you would need to use PortAudio in some way to get the audio as it plays. The only other way to do it would be to use an audio player that has a plugin API, then write your code as a plugin for that one player. But a CoreAudio solution should make it possible for you to monitor all sound... |
1,817,807 | 1,817,811 | Does the hash<char*> function in STL give 1-1 mapping between char* and size_t? | I have a pair
I know the value of the pair.first cannot be more than 1000.
I also know that the pair.second , the string, is always 1 word. Never more than 1 word.
So, to construct the Hash value for the pair I am doing the following:
pair<int,string> p;
hash<char*> H;
hash_vale = H(p.second)*1000 + p.first;
I think t... | By definition, a hash can't be one-to-one due to the pigeonhole principle. I.E., there are 2^32 possible hash values, but far more possible strings. So there must be two strings with the same hash value.
Second of all, you are almost certainly causing overflow by multiplying your hash value by 1000, since a hash should... |
1,817,814 | 1,819,037 | c++: Object's variable cannot be evaluated, but variable from reference to the same object can? | Ok, this is veeery weird... I think. What I mean with the title is:
inside the act() function from an actionHandler object I have:
state->getHumanPieces();
Which gives me an address violation of some sort, apparently 'this' does not have a 'state' variable initialized... It so happens this actionHandler class has a st... | Looks like a case of static initialization order fiasco described here. Your both static objects constructors are depending upon each other in a circular fashion which is very odd.
|
1,818,025 | 1,818,104 | Reading characters outside ASCII | A friend of mine showed me a situation where reading characters produced unexpected behaviour. Reading the character '¤' caused his program to crash. I was able to conclude that '¤' is 164 decimal so it's over the ASCII range.
We noticed the behaviour on '¤' but any character >127 seems to show the problem. The questio... | Your system is using UTF-8 character encoding (as it should) so the character '¤' causes your program to read the sequence of bytes C2 A4. Since a char is one byte, it reads them one at a time. Look into the wchar_t and the corresponding wcin and wcout streams to read multibyte characters, although I don't know which e... |
1,818,106 | 1,819,588 | Should we add unsubclass code during dialog destruction? | What will happen when we subclass a windows dialog and dialog is closed?
Scenario is that I am subclassing a dialog and application can launch many instances of that dialog.
Is it necessary to add unsubclassing code to all the dialogs in thier destruction logic.
I think when dialogs get closed there is no need to unsub... | If you're using instance subclassing (SetWindowLongPtr), then since when the window gets torn down it doesn't matter which WndProc it's using--it's about to vanish anyway.
If you're using global subclassing (SetClassLongPtr) then it would probably be a good idea to remove the subclass once the last subclassed window is... |
1,818,134 | 1,818,165 | Hashing function for four unsigned integers (C++) | I'm writing a program right now which produces four unsigned 32-bit integers as output from a certain function. I'm wanting to hash these four integers, so I can compare the output of this function to future outputs.
I'm having trouble writing a decent hashing function though. When I originally wrote this code, I threw... | Why don't you store the four integers in a suitable data structure and compare them all? The benefit of hashing them in this case appears dubious to me, unless storage is a problem.
If storage is the issue, you can use one of the hash functions analyzed here.
|
1,818,186 | 1,818,203 | Can't quite get Project Euler problem #2 figured out | I'm trying to learn the basics of C++ by going through some Project Euler problems. I've made it to...#2.
Each new term in the Fibonacci
sequence is generated by adding the
previous two terms. By starting with 1
and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
Find the sum of all the even-valu... | You're using y as both the loop variable, and the second term in the sequence.
What you mean to do is:
int x = 0;
int y = 1;
int z;
int sum = 0;
do {
z = x + y;
x = y;
y = z;
if (y % 2 == 0) sum += y;
} while (y <= 4000000);
Noting that you should probably initialize sum as well.
|
1,818,325 | 1,818,332 | How to stop visual c++ stepping into certain files | Is there some way to filter what files Visual Studio 2005 (C++) steps into?
For example, when stepping into
SomeFn( a.c_str(), b.c_str(), etc );
I hate how it steps into the standard template library files for c_str() - instead I just want to go into SomeFn().
If there was some way to filter out any source files didn... | This article describes how to solve it for VC6, VC7 and VC8.
|
1,818,353 | 1,818,418 | Can every if-else construct be replaced by an equivalent conditional expression? | (I don't have a serious need for this answer, I am just inquisitive.)
Can every if-else construct be replaced by an equivalent conditional expression using the conditional operator ?:?
|
Does every if-else constructs can be replaced by an equivalent conditional expression using conditional operator?
No, you've asked this backwards. The "bodies" of if/else contain statements, and it is not possible to turn every statement into an expression, such as try, while, break statements, as well as declaratio... |
1,818,596 | 1,818,621 | Linux & C++: Easy way to exchange objects between two processes | I would like to know what is the easiest way (amongst various alternatives) to exchange objects (or some data) between two linux-based systems.
It appears socket-programming could be a choice, but I have not done it earlier so I am not sure if it is the best way. Could anyone point me to a reference please?
TIA,
Sviiya... | You could have a look at Boost IPC, as well as Google's Protocol Buffers. Or just generally, read this SO post concerning platform independent IPC, it's not exactly what you want, but should give you some good pointers.
|
1,818,641 | 1,818,657 | Why don't win32 API functions have overloads and instead use Ex as suffix? | The win32 API has for example two methods StrFormatByteSize and StrFormatByteSizeEx.
Even though both the methods symantically do the same thing and the Ex counter part only offers a new parameter to slightly change the behavior then couldn't they have two overloads of the same function?
Is it a limitation of c/c++ or ... | The Win32 API is a C (not C++) API. The C language doesn't support overloaded functions.
Complete aside: The Win32 API uses __stdcall-decorated functions, which include the number of bytes of parameters as part of the function name. __stdcall is not part of the C language, but Windows linkers have to know about it.
Mi... |
1,818,666 | 1,818,722 | What's the cost of "as" compared to QueryInterface in COM or dynamic_cast in C++? | I'm still trying to map my deep and old knowledge from C/C++ to my somewhat more shallow .Net knowledge. Today the time has come to "as" (and implicitly "is" and cast) in C#.
My mental model of "as" is that it's a QueryInterface or dynamic_cast (a dynamic_cast with pointer argument, not reference, that is) for C#. My q... |
Yes, the comparison is fair, especially when dealing with pointers. Each of the three either succeeds and returns a non-null pointer of the target type, or returns null.
You can actually use the as operator when working with COM objects in .NET, making it equivalent to QueryInterface with a small amount of overhead fo... |
1,818,821 | 1,819,376 | search for multiple indecies with Boost Multi-Index | how do I limit the search in a boost::multi_index by the result of a previous search?
As an example: suppose I have a rectangle class with an internal value like this:
class MyRect
{
public:
int width;
int height;
double value;
}
and I need a data structure of such obj... | I don't think you can do an inplace limitation.
Store the resulting iterators of the matching widths query in another container and use that container to find the matching heights with remove_if. Then use max_element to find the largest.
If you store the elements as pointers, you could use the same MIC to store the re... |
1,818,846 | 1,818,901 | Add source code to elf file | I want to add my C++ source code to the corresponding elf binary file and I'm looking for the best way to do this. (I'm using several versions of my code and not every version should be committed into svn).
Can I just append the source code without destroying the elf file using bash's >> operator?
Or is objcopy --add-s... | If you're using gcc you could use the -M flag to get a file with a list of all included files. It's written to the file specified with -o, like this:
gcc -M -c my_file.c -o list_of_included_files.txt
|
1,818,861 | 1,818,876 | Memory leak/Memory allocation in C++ | I have the following function in C++
void func1()
{
char *p = "Test for memory leak";
}
When func1() is called where is the memory for the variable allocated? Whether in the stack or the heap? Should delete p; be called explicitly?
| No, the memory is allocated only for the pointer p on the stack. This memory is automatically reclaimed when p goes out of scope. p is just pointing to a string which is stored some where in the read-only section of your program. Ideally it should be defined as const char *p. If you try to delete it, it will be undefin... |
1,818,919 | 1,818,958 | copy to cout with hex flag set | having something like this:
void print_signs()
{
const char* chars[] = {"abcdefghijklmnopqrstuvwxyz0123456789"};
std::copy(chars,chars + 1,std::ostream_iterator<const char*>(cout));
cout << hex; //trying to change the way output works for next line
std::copy(chars,chars + 1,std::ostream_iterator<const char*>(cout));
}
... | void print_signs()
{
const std::string chars("abcdefghijklmnopqrstuvwxyz0123456789");
std::cout << std::hex;
std::copy(chars.begin(), chars.end(), std::ostream_iterator<int>(std::cout));
}
And If you wan't to preserve the exact typing of the original:
void print_signs()
{
const char* chars[] = {"abcdef... |
1,819,024 | 1,819,035 | C++ 2D dynamic array crash | Hi I'm having some problem with 2D dynamic array.
int main()
{
double **M;
int M_dimension;
int i;
M_dimension = 10;
M = new double *[M_dimension];
for (i=0;i<M_dimension;i++)
{
M[i] = new double[M_dimension];
}
M[0][0] = 1.0;
...
}
Program works but I'd like to initialize 2D array... | You are passing M by value, instead of by reference. initialize2D needs to change the value of the pointer-to-pointer M such that it points to the memory allocated
Try changing your function signature to this instead:
void initialize2D(double **&M,int M_dimension)
Or
void initialize2D(double ***M,int M_dimension) {
... |
1,819,114 | 1,968,819 | When can typeid return different type_info instances for same type? | Andrei Alexandrescu writes in Modern C++ Design:
The objects returned by typeid have
static storage, so you don't have to
worry about lifetime issues.
Andrei continues:
The standard does not guarantee that
each invocation of, say, typeid(int)
returns a reference to the same
type_info object.
Even though t... |
Are there times when &typeid(T) != &typeid(T)?
I'm mainly interested in compilers for Windows, but any information for Linux and other platforms is also appreciated.
Yes. Under windows DLL can't have unresolved symbols, thus. If you have:
foo.h
struct foo { virtual ~foo() {} };
dll.cpp
#include "foo.h"
...
foo f;
co... |
1,819,189 | 1,819,236 | What range of values can integer types store in C++? | Can unsigned long int hold a ten digits number (1,000,000,000 - 9,999,999,999) on a 32-bit computer?
Additionally, what are the ranges of unsigned long int , long int, unsigned int, short int, short unsigned int, and int?
| The minimum ranges you can rely on are:
short int and int: -32,767 to 32,767
unsigned short int and unsigned int: 0 to 65,535
long int: -2,147,483,647 to 2,147,483,647
unsigned long int: 0 to 4,294,967,295
This means that no, long int cannot be relied upon to store any 10-digit number. However, a larger type, long l... |
1,819,282 | 1,866,723 | How to draw Windows 7 taskbar like Shaded Buttons | Windows 7 taskbar buttons are drawn on a shaded background. The color shade somehow reacts on where the mouse is over the button.
I'd like to use such buttons in my application. How can i do that ?
| The effect is called "Color Hot-track". It does not seem that there is a dedicated API for that. There are some notes in a developer blog about it:
I found some source code from Rudi Grobler though doing a similar thing:
Make your WPF buttons color hot-track!
|
1,819,387 | 1,819,399 | Handling large integer on C/C++ using Visual C++ 2008 | How do I do to handles some big positive integers (like 9,999,999,999) on Visual C++ 2008 on a 32-bit PC.
Please give an example on declaring, printf, scanf of these big positive integers.
Please consider using 9,999,999,999 in your example.
| unsigned long long foo;
scanf("%llu", &foo);
printf("%llu", foo);
|
1,819,562 | 1,819,847 | Plain C callback function pointer as part of iPhone delegate protocol? | Trying to integrate plain C/C++ code into iPhone project as an external static library. So far so good, but now I'm stuck at a point, where I need to register library callbacks. The library should notify my iPhone application, when something happens. Seems like a good place to define a Delegate.
...but the library is e... | You need to use C++/C interfaces for the callbacks which then internally delegate the call to your Objective-C code. Where the callback registrations allow you to pass in user-data of sufficient size, you can conveniently pass something that identifies your context like in this answer.
Callbacks that don't get passed a... |
1,819,564 | 1,819,596 | g++ produces big binaries despite small project | Probably this is a common question. In fact I think I asked it years ago... but I can't remember the answer.
The problem is: I have a project that is composed of 6 source files. All of them no more than 200 lines of code. It uses many STL containers, stdlib.h and iostream. Now the executable is around 800kb in size....... | If you give g++ dynamic library names, and don't pass the -static flag, it should link dynamically.
To reduce size, you could of course strip the binary, and pass the -Os (optimize for size) optimization flag to g++.
|
1,819,603 | 1,819,620 | How can I set up a map with string as key and ostream as value? | I am trying to use the map container in C++ in the following way: The Key is a string and the value is an object of type ofstream. My code looks as follows:
#include <string>
#include <iostream>
#include <map>
#include <fstream>
using namespace std;
int main()
{
// typedef map<string, int> mapType2;
// map<string... | Streams do not like being copied. The simplest solution is using a pointer (or better, a smart pointer) to a stream in the map:
typedef map<string, ofstream*> mapType;
|
1,819,680 | 1,819,756 | Usage of boost lambdas | I am new to boost and trying to write some simple programs to understand it. Here in the following piece of code I am trying to fill an array with random numbers. Here is my code:
using namespace boost::lambda;
srand(time(NULL));
boost::array<int,100> a;
std::for_each(a.begin(), a.end(), _1=rand());
Bu... | Seems like you need to use delayed function call
std::for_each(a.begin(), a.end(), boost::lambda::_1= boost::lambda::bind(rand) );
Here is another interesting situation: Delaying constants and variables
|
1,819,791 | 1,824,402 | C/C++ library for .wav file encoding | I need a library for MS VC6 which encodes sampled data which is in the form of a float array, to an audio file format preferably wav
Also is there a library that can encode the samples into pcm form and play it directly through the sound card without saving a wav file first??
| As noted, the WAV file format is very simple. To just play the samples, use the waveOut functions; they're documented.
To convert from a float to a signed 16-bit PCM sample, just convert the sample into the 16 bit range. For example, assuming a sample in the range -1.0 to +1.0 multiply by 32767.0 and convert to an in... |
1,819,871 | 1,819,889 | Simple C++ Instant messenger | I want to make a very simple c++ instant messenger for lan networks and internet (direct IP connect). I know little about sockets. I searched the internet, but nothing really helped. I would someone to suggest a howto/tutorial/guide. I just want to send and receive messages (in a console window, I'll create the gui lat... | Checkout Boost.Asio. It's portable, and it's also got an example that implements a simple chat.
|
1,819,982 | 1,820,107 | What can cause "corrupted double-linked list" error? | I am having problems with a fairly complex code. I wasn't able to produce a short snippet that reproduces the error, so I'll try to explain the problem in words.
The code crashes randomly with the error
*** glibc detected *** gravtree: corrupted double-linked list: 0x000000001aa0fc50 ***
Debugging showed that it comes... | Try running your program under Valgrind. It may point you to an earlier cause, whereas gdb is only breaking in where damage has already occurred.
|
1,820,069 | 1,820,092 | Public operator new, private operator delete: getting C2248 "can not access private member" when using new | A class has overloaded operators new and delete. new is public, delete is private.
When constructing an instance of this class, I get the following error:
pFoo = new Foo(bar)
example.cpp(1): error C2248: 'Foo:operator delete': cannot access private member declared in class 'Foo'
But there's no call to delete here, so ... | When you do new Foo() then two things happen: First operator new is invoked to allocate memory, then a constructor for Foo is called. If that constructor throws, since you cannot access the memory already allocated, the C++ runtime will take care of it by passing it to the appropriate operator delete. That's why you al... |
1,820,174 | 1,820,207 | Forcing C++ compilers to check for exception handling | I was wondering if there is some compiler parameter, preferably in gcc (g++) which treats the lack of try/catch blocks as errors. This is the standard behavior in java and I was alway fond of it.
| Since checked exceptions in Java rely on the throw signature, you can read why you will not want to use throw function signatures in C++ in this question on SO.
|
1,820,394 | 1,820,483 | C++ character replace | What is the best way to replace characters in a string?
Specifically:
"This,Is A|Test" ----> "This_Is_A_Test"
I want to replace all commas, spaces, and "|" with underscores.
(I have access to Boost.)
| As the other answers indicated, you can use the various replace methods. However, these approaches have the downside of scanning the string multiple times (one time for each character). I would recommend rolling your own replace method, if you care about speed:
void beautify(std::string &s) {
int i;
for (i = ... |
1,820,825 | 1,820,888 | Global hotkey with WIN32 API? | I've been able to set local hotkeys like this
RegisterHotKey(hwndDlg, 100, MOD_ALT | MOD_CONTROL, 'S');
How can I set the hotkey to be global? I want it to be there even when my window is hidden.
| I solved it myself but thanks for your reply
here's what was wrong...
ShowWindow(hwndDlg, SW_HIDE);
RegisterHotKey(hwndDlg, 100, MOD_ALT | MOD_CONTROL, 'S');
if you register the hotkey first then hide the window... it ignores the hotkey for some reason... oh well.. it's working now :)
|
1,821,081 | 1,821,222 | Sorting a listview (Win32/C++) | I'm trying to sort a listview when the user clicks on the column header.
I am catching the LVN_COLUMNCLICK notification like so:
case LVN_COLUMNCLICK:
{
NMLISTVIEW* pListView = (NMLISTVIEW*)lParam;
BOOL test = ListView_SortItems ( m_hDuplicateObjectsList, ListViewCompareProc, pListView->iSubItem );
... | Are you using the LVS_OWNERDATA style on your control?
There are a number of features incompatible with that style, including sorting:
http://msdn.microsoft.com/en-us/library/bb774735%28VS.85%29.aspx
|
1,821,153 | 1,843,062 | Segfault on C++ Plugin Library with Duplicate Symbols | I have a cross platform C++ application that is broken into several shared libraries and loads additional functionality from plugin shared libraries. The plugin libraries are supposed to be self contained and function by themselves, without knowledge of or dependency on the calling application.
One of the plugins co... | I think I've found the solution, the linker flag -Bsymbolic. Essentially this flag adds a flag in the shared library to tell the runtime linker to try and resolve symbol names within itself first. The engine was able to run with the plugin just fine in all cases (monolithic exe, exe w/ shared libs, plugin w/ and w/o ... |
1,821,540 | 1,828,324 | Does anyone know of a VB(A/6) example using GetLocaleInfoEx? | I thought I dug most of what I need out of the header files, but I keep crashing out.
Here is the declare I tried using, but I don't think it's just an issue of the declare. I think I'm actually using it wrong.
Private Declare Function GetLocaleInfoEx Lib "kernel32" ( _
ByVal lpLocaleName As Long, _
ByVal LCType As Lon... | EDIT: I couldn't test this because I don't have Vista here at home, but Oorang says it works (in the comments).
Private Declare Function GetLocaleInfoEx _
Lib "kernel32" ( _
ByVal lpLocaleName As Long, _
ByVal LCType As Long, _
ByVal lpLCData As Long, _
ByVal cchData As Long _
) As Long
Const LOCAL... |
1,821,703 | 1,821,723 | Help me understand std::erase | In the book 'C++ In A Nutshell', there is the following example code
std::vector<int> data
...
std::erase(std::remove(data.begin(), data.end(), 42),
data.end());
I thought that 'erase' was a member function, so shouldn't that be 'data.erase' rather than 'std::erase'?
Is there some way the c++ compiler can tell what ... | erase is a member function. The sample provided is incorrect.
|
1,821,799 | 1,821,816 | What useful functionality do you get out of overriding the 'new' operator? | What new kind of functionalities (for debugging or not) do you find helpful by overriding the new operator?
| The main reason I've had to overload new has been for performance. One example is allocating a large number of small objects, which is often fairly slow with a general purpose allocator, but can often be improved a lot with a custom allocator.
|
1,821,822 | 1,824,354 | #import command line equivalent | Using Visual Studio with Microsoft's C++ compiler, we have several source files which use the Microsoft-specific '#import' directive to import a type library. For instance:
#import my_type_lib.tlb
I'd like to remove the #import from the source code, and replace it with a command line step to be executed via GNU Make.... | As far as I know, there are no separate tools to generate code from the type lib.
You could do #import once, and then stash away the generated files and include them as regular source files. But then changes to the type library would need a new supervised build to regenerate the files.
Which parts of the generated info... |
1,821,858 | 1,822,030 | Iterating over pair elements in a container of pairs (C++) | If I have a container (vector, list, etc) where each element is a std::pair, is there an easy way to iterate over each element of each pair?
i.e.
std::vector<std::pair<int,int> > a;
a.push_back(std::pair(1,3));
a.push_back(std::pair(2,3));
a.push_back(std::pair(4,2));
a.push_back(std::pair(5,2));
a.push_back(std::pair... | To flatten your container of pairs into a second container you could also simply write your own inserter:
template<class C>
struct Inserter {
std::back_insert_iterator<C> in;
Inserter(C& c) : in(c) {}
void operator()(const std::pair<typename C::value_type, typename C::value_type>& p)
{
*in++ = p... |
1,821,988 | 1,822,005 | Yield from C# to C++, dealing with containers | Actually, I have a design question here. Its very simple but the point is:
I have one C++ class that has a STL vector declared as a private member. But the clients of that class need to iterate over this vector.
In C# we have a very handy statement, the Yield, that in cases like that, you write a function returning an... | There's no syntactic sugar in C++ analogous to yield in C#. If you want to create a class, instances of which should be iterable in the same way stock STL collections are, then you have to implement an iterator for your class, expose it as ::iterator on your type, and provide begin() and end() member functions.
|
1,822,083 | 1,822,102 | Accessing Linux diagnostic information from JavaScript | Is there a way can I access machine diagnostic information within the Linux OS in realtime? Such diagnostic info as CPU utilization, memory utilization, etc using JavaScript to display on a web page?
If there is no direct access from JavaScript, is there any other method where JS code can call functions in shared libr... | JavaScript is in general not allowed to access system information - among other things this results from portability and security considerations.
If you really need that for some reason you either find some browser-specific solutions (don't know if there are any) or you require the user to install a custom plugin you d... |
1,822,114 | 1,822,183 | C++ map insertion and lookup performance and storage overhead | I would like to store a mapping of an integer key to a float value in-memory.
I have roughly 130 million keys (and, accordingly, 130 million values).
My focus is on lookup performance -- I have to do many, many millions of lookups.
The C++ STL library has a map class for associative arrays of this sort. I have severa... | Given what you've said, I'd think very hard about using an std::vector<pair<int, float> >, and using std::lower_bound, std::upper_bound, and/or std::equal_range to look up values.
While the exact overhead of std::map can (and does) vary, there's little or no room for question that it will normally consume extra memory ... |
1,822,143 | 1,822,198 | Null Object Pattern, Recursive Class, and Forward Declarations | I'm interested in doing something like the following to adhere to a Null Object design pattern and to avoid prolific NULL tests:
class Node;
Node* NullNode;
class Node {
public:
Node(Node *l=NullNode, Node *r=NullNode) : left(l), right(r) {};
private:
Node *left, *right;
};
NullNode = new Node();
Of course, as w... | Use extern:
extern Node* NullNode;
...
Node* NullNode = new Node();
Better yet, make it a static member:
class Node {
public:
static Node* Null;
Node(Node *l=Null, Node *r=Null) : left(l), right(r) {};
private:
Node *left, *right;
};
Node* Node::Null = new Node();
That said, in both existing code, and amendmen... |
1,822,156 | 1,822,264 | How do I select the client only framework in a Managed Visual C++ project in VS 2008 Sp1? | The title said it all.
| Unfortunately, this isn't possible, even with VS 2008 sp1. You set the target framework under the "Common Properties"->"Framework and References" in the project property pages. In 2008sp1, the only choices are:
.NET Framework 2.0
.NET Framework 3.0
.NET Framework 3.5
|
1,822,199 | 2,256,100 | gdb 7.0, signal SIGCONT doesn't break from a pause() call | I'd built a version of gdb 7.0 for myself after being pointed to a new feature, and happened to have that in my path still.
Attempting to step through some new code, I'd added a pause() call, expecting to be able to get out like so:
(gdb) b 5048
Breakpoint 1 at 0x2b1811b25052: file testca.C, line 5048.
(gdb) signal SI... | The pause() function does not return unless a signal handler is called (see the specification and the man page).
To make it return after your program receives SIGCONT, you must install an handler for SIGCONT. Try and see using the following example:
#include <signal.h>
#include <stdio.h>
#include <string.h>
#include <u... |
1,822,223 | 1,822,230 | How to find what's new in VC++ v10? | Googling nor binging "VC++ What's new C++0x" gives me nothing that tells me what is new.Is there an official page at msdn or something similiar that contains the information for VC++ 10? I've seen such for C#,there must be one for what I'd enjoy to read.
If not, please list the new features available in Visual Studio 2... | The Visual C++ Team Blog has frequent articles about what's new for VC++ in Studio 2010. It's not an exhaustive list, but does detail many of the new additions.
There's also an MS site which lists some of whats new.
|
1,822,260 | 1,822,274 | Help programmatically add text to an existing PDF | I need to write a program that displays a PDF which a third-party supplies. I need to insert text data in to the form before displaying it to the user. I do have the option to convert the PDF in to another format, but it has to look exactly like the original PDF. C++ is the preferred language of choice, but other la... | What about PoDoFo:
The PoDoFo library is a free, portable
C++ library which includes classes to
parse PDF files and modify their
contents into memory. The changes can
be written back to disk easily. The
parser can also be used to extract
information from a PDF file (for
example the parser could be used i... |
1,822,429 | 1,822,507 | A recurring const-connundrum | I often find myself having to define two versions of a function in order to have one that is const and one which is non-const (often a getter, but not always). The two vary only by the fact that the input and output of one is const, while the input and output of the other is non-const. The guts of the function - the ... | I don't believe it's the deficiency of const-correctness per se, but rather the lack of convenient ability to generalize a method over cv-qualifiers (in the same way we can generalize over types via templates). Hypothetically, imagine if you could write something like:
template<cvqual CV>
inline CV ITEMIDLIST* GetNextI... |
1,822,667 | 1,822,738 | How can I share HWND between 32 and 64 bit applications in Win x64? | MSDN tells me that handles to windows (HWND) can be shared between 32- and 64-bit applications, in Interprocess Communication (MSDN). However, in Win32 a HWND is 32 bits, whereas in 64 bit Windows it is 64 bits. So how can the handles be shared?
I guess the same question applies to handles to named objects such as mu... | Doesn't the fact that they can be shared imply that only the lower 32 bits are used in Win64 processes? Windows handles are indexes not pointers, at least as far as I can tell, so unless MS wanted to allow more than 2^32 window/file/mutex/etc. handles there's no reason to use the high 32 bits of a void* on Win64.
|
1,822,876 | 1,823,032 | C++ swap problem in inheritance scenario | I want to add swap functionality to two existing C++ classes. One class inherits from the other. I want each classes' instances to only be swappable with instances of the same class. To make it semi-concrete, say I have classes Foo and Bar. Bar inherits from Foo. I define Foo::swap(Foo&) and Bar::swap(Bar&). Bar:... | (Somewhat hacky solution)
Add a protected virtual method, isBaseFoo(), make it return true in Foo, and false in Bar, the the swap method for Foo could check it's argument has isBaseFoo()==true.
Evil, and detects the problem only at run-time, but I can't think of anything better, although Charles Bailey's answer might b... |
1,822,887 | 1,823,024 | What is the best way to eliminate MS Visual C++ Linker warning : "warning LNK4221"? | I have a CPP source file that uses #if / #endif to compile out completely in certain builds. However, this generates the following warning.
warning LNK4221: no public symbols found; archive member will be inaccessible
I was thinking about creating a macro to generate a dummy variable or function that wouldn't actuall... | OK, the fix I am going to use is Pavel's suggestion with a minor tweak. The reason I’m using this fix is it’s an easy macro to drop in and it will work in bulk-builds / unity-builds as well as normal builds:
Shared Header:
// The following macro "NoEmptyFile()" can be put into a file
// in order suppress the MS Visua... |
1,822,914 | 1,822,999 | Load XML into C++ MSXML from byte array | I'm receiving XML over a network socket. I need to take that XML and load it into the DOM to perform further operations. MSXML requires input strings that are in either UCS-2 or UTF-16 and completely ignores the XML header with the encoding type when loading from a string. It allows the loading of XML fragments, so thi... | Simplest way is pass the load function a safe array. e.g.
const char* xml = "<root/>";
SAFEARRAYBOUND rgsabound[1];
rgsabound[0].lLbound = 0;
rgsabound[0].cElements = strlen(xml);
SAFEARRAY* psa = SafeArrayCreate(VT_UI1, 1, rgsabound);
memcpy(psa->pvData, xml, strlen(xml));
VARIANT v;
VariantInit(&v);
V_VT(&v) = VT_... |
1,823,059 | 1,823,086 | Declaring arrays similar to C style (C++) | In C a programmer can declare an array like so:
unsigned char Fonts[2][8] {
[1] = {0, 31, 0, 31, 0, 31, 0, 31}
};
And element [0] is likely random bits. Is there a similar way in C++?
| You can do this:
unsigned char Fonts[2][8] = {
{0},
{0, 31, 0, 31, 0, 31, 0, 31}
};
|
1,823,073 | 14,837,584 | stringstream operator>> fails as function, but works as instance? | I'm writing simple code that will extract a bunch of name, int pairs from a file. I'm modifying existing code that just uses:
string chrom;
unsigned int size;
while ( cin >> chrom >> size ) {
// save values
}
But I want to use another (similar) input file that has the same first two columns, but are followed by o... | Three groups of member functions and one group of global functions overload this "extraction operator" (>>), see http://www.cplusplus.com/reference/istream/istream/operator%3E%3E/.
stringstream(line); --created a temporary object
stringstream ss(line);-- a normal object.
when "chrom" is int, operator >> is overloade... |
1,823,370 | 1,823,401 | C++ overloading * for polynomial multiplication | So I have been developing a polynomial class where a user inputs: 1x^0 + 2x^1 + 3x^2... and 1,2,3 (the coefficients) are stored in an int array
My overloaded + and - functions work, however, * doesnt work. No matter the input, it always shows -842150450
when is should be (5x^0 + x^1) * (-3x^0 + x^1) = -15x^0 + 2x^1 +... | You don't appear to initialise the temp.coefficient[i+j] to zero in your operator * ().
temp.coefficient = new int [count];
std::memset (temp.coefficient, 0, count * sizeof(int));
|
1,823,431 | 1,823,475 | which is a better language (C++ or Python) for complex problem solving exercises (ex. Graphs)? | I am trying to work on some problems and algorithms. I know C++ but a friend told me that it would be better if done with Python.As it would be much faster to develop and less time is spent in programming details which does not actually earn anything solution wise.
EDIT 2: I plan to use python-graph lib from Google-cod... | I think you're looking for Python, because you can:
Focus on the algorithms themselves and not have to worry about other detail like memory management.
Do more with less code
The syntax is almost like working with pseudo code.
There is great built in language support for lists, tuples, list comprehensions, etc...
B... |
1,823,605 | 1,839,640 | Boost: what could be the reasons for a crash in boost::slot<>::~slot? | I am getting such a crash:
#0 0x90b05955 in __gnu_debug::_Safe_iterator_base::_M_detach
#1 0x90b059ce in __gnu_debug::_Safe_iterator_base::_M_attach
#2 0x90b05afa in __gnu_debug::_Safe_sequence_base::_M_detach_all
#3 0x000bc54f in __gnu_debug::_Safe_sequence_base::~_Safe_sequence_base at safe_base.h:170
#4 0x000aa... | I found the problem. When I enable these preprocessor definitions (my Xcode does that by default in Debug configuration), it crashes:
-D _GLIBCXX_DEBUG=1
-D _GLIBCXX_DEBUG_PEDANTIC=1
I guess Boost (bjam) compiled without those and that causes such problems because the STL structures (like vector) look different in bin... |
1,823,628 | 1,823,770 | EnumChildWindows or FindWindowEx? | I have option to use any one of the API EnumChildWindows or FindWindowEx.
Any suggestions which api is better performance oriented?
Is FindWindowEx internally uses EnumChildWindows to get handle to particular window?
| This really depends a lot on your scenario.
The FindWindowEx function is used to search for windows having a particular class and optionally a particular piece of text in the window. The EnumChildWindows function is simply there to enumerate child windows.
I think performance should be your last concern here. The... |
1,823,643 | 2,024,669 | Boost: what exactly is not threadsafe in Boost.Signals? | I read at multiple places that Boost.Signals is not threadsafe but I haven't found much more details about it. This simple quote doesn't say really that much. Most applications nowadays have threads - even if they try to be single threaded, some of their libraries may use threads (for example libsdl).
I guess the imple... | I don't think it's too clear either, and one of the library reviewers said here:
I also don't liked the fact that only three times the word 'thread' was named.
Boost.signals2 wants to be a 'thread safe signals' library. Therefore some more
details and especially more examples concerning on that area should be given t... |
1,823,666 | 1,823,674 | Program stop to running when calls a process | I am trying to create a program that calls another process using CreateProcess. After some problems, I change my program to just open a known program:
if( !CreateProcess( (LPWSTR)"C:\\Program Files\\Opera\\Opera.exe", // No module name (use command line)
NULL, ,
// Command line
... | This line is wrong:
(LPWSTR)"C:\\Program Files\\Opera\\Opera.exe"
LPWSTR is a typedef for wchar_t*. So you're casting a plain string (array of chars, which will decay to a const char*) to a wchar_t*. The end result is likely not even null-terminated!
Either use CreateProcessA and drop the cast, or use a wide string:
... |
1,823,721 | 1,823,749 | How to catch the null pointer exception? | try {
int* p = 0;
*p = 1;
} catch (...) {
cout << "null pointer." << endl;
}
I tried to catch the exception like this but it doesn't work,any help?
| There's no such thing as "null pointer exception" in C++. The only exceptions you can catch, is the exceptions explicitly thrown by throw expressions (plus, as Pavel noted, some standard C++ exceptions thrown intrinsically by standard operator new, dynamic_cast etc). There are no other exceptions in C++. Dereferencing ... |
1,823,883 | 1,823,914 | Updating text in a C Win32 API STATIC control drawn with WS_EX_TRANSPARENT | I have window with some STATIC labels and BUTTONs on it.
I make all the LABELS transparent background so I can make the background RED say.
In the CALLBACK i process the WM_CTLCOLORSTATIC message, determine the ID of the control with GetDlgCtrlID() and then:
SetBkMode((HDC)wParam, TRANSPARENT); // Make STATIC control B... | Use InvalidateRect on the rectangle occupied by the control.
RECT rect;
GetClientRect(hctrl, &rect);
InvalidateRect(hctrl, &rect, TRUE);
MapWindowPoints(hctrl, hwnd, (POINT *) &rect, 2);
RedrawWindow(hwnd, &rect, NULL, RDW_ERASE | RDW_INVALIDATE);
|
1,823,927 | 1,824,226 | Simulated time in a game loop using c++ | I am building a 3d game from scratch in C++ using OpenGL and SDL on linux as a hobby and to learn more about this area of programming.
Wondering about the best way to simulate time while the game is running. Obviously I have a loop that looks something like:
void main_loop()
{
while(!quit)
{
handle_eve... | I've mentioned this before in other game related threads. As always, follow the suggestions by Glenn Fiedler in his Game Physics series
What you want to do is to use a constant timestep which you get by accumulating time deltas. If you want 33 updates per second, then your constant timestep should be 1/33. You could al... |
1,824,087 | 1,824,193 | How do I factor code to ease testability? | I am learning about Unit Testing and want to know how to write testable code. But, I'm not sure how to write testable code without making it complex. I'll take famous Car and Engine problem to describe the problem.
class Car
{
private:
Engine m_engine;
public:
Car();
// Rest of the car
}
I came up with follo... | If you only have one Engine type, why are you trying to make it a new object? If you don't plan on swapping engines, don't create another abstraction layer. Just make the engine part of the car.
You might be decomposing to reduce complexity, rather than to reuse components. Good call. In which case, I'd say that 3 is y... |
1,824,118 | 1,824,135 | What may cause losing object at the other end of a pointer in c++? | EDIT: I have found the error: I did not initialize an array with a size. question can be closed.
I have a class V, and another class N. An object of N will have an array of pointers to objects of class V (say V **vList). So, N has a function like
V **getList();
Now in some function of other classes or simply a drive... | Q1 is right. For the second part, V *oneV = vList[i] would be the correct syntax. In your syntax you are dereferencing one more time (treating an object of type V as a pointer to such an object) which obviously is crashing your code.
EDIT:
Since you are using the correct syntax, the reason of segfaults would depend on ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.