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 |
|---|---|---|---|---|
4,338,318 | 4,338,606 | How to extract derived classes from the base-class container? | After storing objects of different types in the same container using common parent class I need to extract them back.
[Tests/test0.c++]:
int main()
{
element wrapper;
wrapper.name = "div";
wrapper.attributes["id"] = "wrapper";
cargo<string> text("Learn from yesterday, live for today, hope for tomorrow... |
This question is probably more about the design than implementation.
Although Boost.Variant and Boost.Any will work, they will be only a workaround. The real problem may be that variable part of responsibility of classes, derived from node class, is not encapsulated.
You could try to use composition instead. One host ... |
4,338,374 | 4,338,406 | C++ count the number of digits of a double | i want to do what the title says like this:
int number1;
cin>>number1;
num1len=log10(number1)+1;
cout<<"num of digits is "<<num1len<<"\n";
but when the number of digits is 11 and more the answer is always 7(6+1)
Does anyone knows why or what im i doing wrong?
| What is 'wrong' is the maximum value which can be stored in a (signed) int :
#include <iostream>
#include <numeric>
int main()
{
std::cout << std::numeric_limits<int>::max() << std::endl;
}
Gives me :
2147483647
|
4,338,409 | 4,338,477 | Using NULL as a terminator in arrays? | I like "reinventing the wheel" for learning purposes, so I'm working on a container class for strings. Will using the NULL character as an array terminator (i.e., the last value in the array will be NULL) cause interference with the null-terminated strings?
I think it would only be an issue if an empty string is added... | "" is the empty string in C and C++, not NULL. Note that "" has exactly one element (instead of zero), meaning it is equivalent to {'\0'} as an array of char.
char const *notastring = NULL;
char const *emptystring = "";
emptystring[0] == '\0'; // true
notastring[0] == '\0'; // crashes
|
4,338,411 | 4,338,823 | OpenCV - is there anything like delete text? | I need such thing because it seems to me that when I do
cvRectangle( CVframe, UL, LR, CV_RGB(0,256,53), CV_FILLED);
string cvtext;
cvtext += timeStr;
cvPutText(CVframe, cvtext.c_str(), cvPoint(0,(h/2+10)), &font , CV_RGB(0,0,0));
each time 24 times per second cvRectangle does not overlay old text...
| There's no built-in cvDeleteText or anything like that, and probably for good reason. Whenever you put text on an image, it overwrites the pixels in that image, just as if you had set their values to CV_RGB(0,0,0) individually. If you wanted to undo that operation, you'd need to store whatever had been there beforehand... |
4,338,857 | 4,339,049 | Difference between PathAppend and PathCombine in Win32 API | I want to understand what's the difference between those functions, and which of them should I use for work with paths?
For example: I want "C:\Temp" + "..\Folder" = "C:\Folder"
Thanks
| You have to use PathCombine for this.
Concatenates two strings that
represent properly formed paths into
one path; also concatenates any
relative path elements.
PathAppend specifically rules out relative path qualifiers, per the MSN docs:
The path supplied in pszPath cannot
begin with "..\" or ".\" to prod... |
4,338,966 | 4,339,421 | C++ : How can I know the size of Base class SubObject? | .
Here I was discussing Empty Base Optimization, and MSalters made this interesting comment:
No class can ever have
sizeof(Class)==0, empty or not. But
we're talking specifically over the
size of an empty base class subobject.
It doesn't need its own vtable, nor a
vtable pointer. Assume the common
layout o... | Good answers.
By the way, MS VC++ and G++ compilers can dump class layouts for you to study.
With VC++ just run cl.exe /c /d1reportAllClassLayout <source>.cpp
This uses class and vtable layout dump code I wrote in 1990 to test proper layout objects, vtables, vbtables, etc.
To better understand how C++ compilers lay out... |
4,339,067 | 4,339,120 | const char* in my class has junk character(s) after it's returned from function | Class:
class myclass {
public:
myclass(void);
const char* server;
private:
char pidchar[6];
int pidnum;
};
The function
myclass parseINI(const char* file)
{
myclass iniOptions;
CSimpleIniA ini;
ini.SetUnicode();
ini.LoadFile(file);
const char* server = ini.GetValue("", "serve... | The const char* returned by GetValue() probably belonged to the ini object. When you exited the parseIni() function, ini went out of scope and was destroyed, which could mean your pointer is no longer valid.
Try using a std::string for the server member type instead of const char*.
|
4,339,128 | 4,339,372 | boost::program_options: how to get the application name? | Using Boost Program Options, how do you get the string equivalent of argv[0]?
| I don't think this is possible. This may be because the program name could also legally be used as an option name.
The command line parser code explicitly skips the relevant argv member:
template<class charT>
basic_command_line_parser<charT>::
basic_command_line_parser(int argc, charT* argv[])
: detail::cmdline(
... |
4,339,210 | 4,339,384 | std::cout << stringstream.str()->c_str() prints nothing | in a function, that gets unsigned char && unsigned char length,
void pcap_callback(u_char *args, const struct pcap_pkthdr* pkthdr, const u_char* packet)
{
std::vector<unsigned char> vec(packet, packet+pkthdr->len); // optimized from foo.
std::stringstream scp;
for (int i=0;i<pkthdr->len;i++) {
scp<... | For a quick test, throw in a check for scp.str().size() == strlen(scp.str().c_str()) to see if there are embedded '\0' characters in the string, which is what I suspect is happening.
|
4,339,265 | 4,339,416 | Writing Magic Packet in C++ | I want to send magic packet to wake up a specific PC(specific MAC address) connected to an mbed through LAN . I have found the following code in code project.
My MAC Address : 00-C0-9F-BD-E4-3A (sample).....how can i declare this and fill this in the array.* I have little knowledge in Programming. so please ignore any... | I'm afraid to you are not providing enough of the code to give an unambiguous answer (a link might help), but I think that you don't have to fill in magicP[] yourself - this is what the code is doing for you. It appears that you have to provide your hexadecimal MAC address as input in the macAddr variable, as a string ... |
4,339,394 | 4,339,452 | How to get around rounding issues in floating point arithmetic in C++? | Im running into some issues with floating point arithmetic not being accurate. I'm trying to calculate a score based on a weighted formula where every input variable weighs about as much as 20 times the next significant one. The inputs however are real numbers, so I ended up using a double to store the result. The code... |
you are not outputting the entire value, use cout << setprecision(number_of_digits) << score1 << endl;
how many valid digits do you need in your score computation?
|
4,339,520 | 4,339,739 | How to read an array from XML-RPC | xmlrpc_c::clientSimple myClient;
xmlrpc_c::value Result
...
myClient.call(serverUrl, "getattr", "s", &result, pName);
If the result is an array, how do I read it?
| found it....
typdef std::vector<xmlrpc_c::value> carray;
...
function(...){
carray c = xmlrpc_c::value_array(result).cvalue();
cout << xmlrpc_c::value_int(c[0]);
}
...
|
4,339,523 | 4,339,731 | Should I switch to C++ I/O streams? | I've never been much to use C++ I/O streams and have always opted for what I know.
i.e. the printf functions.
I know there are some benefits to using I/O streams, but I'm looking for some tips
from the stackoverflow community to help me (or convince me) to switch. Because I still
prefer printf and I think the printf ... | I'm not a big user of streams myself, so I'll only list what I think about them. This is really subjective, I'll understand if my answer is voted for deletion.
I like : homogeneity
I may have a enum, a class or anything else, making my user defined type printable is always done by providing the same operator<< next t... |
4,339,564 | 4,339,773 | Should I use header-only classes or lib files? | I am creating an external library for general use. What Im asking is should I put every class in just .hpp files like boost does or should I compile it into a lib file and keep the two file per class rule. As far as I can see .hpp is used for speed, so you don't have to add a .lib for every class or a massive one for t... | This really depends on if you have cross-platform or templated code. You may not have an awful lot of choice about making the majority in header files if you need a lot of preprocessing to generate it. Otherwise, you should pre-compile as much as possible, as a general rule.
|
4,339,589 | 4,339,608 | Foreach implementation in C++, a Poor man's approach | There are happy people working with boost and Qt. In my current "embedded" project I have to use home-made container classes. OK, enough complaining.
I've tried to implement an easy and self-contained foreach like that:
#define ForEachString(S,C) TString S;\
for ( int i=0; i<C.GetSize() && (!!(&(S=C[i]))); ++i ... | Perhaps you could parameterise on the type T:
#define ForEach(T,S,C) T S;\
for ( int i=0; i<C.GetSize() && (!!(&(S=C[i]))); ++i )
TStringList tables;
ForEach( TString, table, tables )
{
//do sth. with tab.
}
|
4,339,960 | 4,339,977 | How do I convert wchar_t* to std::string? | I changed my class to use std::string (based on the answer I got here but a function I have returns wchar_t *. How do I convert it to std::string?
I tried this:
std::string test = args.OptionArg();
but it says error C2440: 'initializing' : cannot convert from 'wchar_t *' to 'std::basic_string<_Elem,_Traits,_Ax>'
| You could just use wstring and keep everything in Unicode
|
4,340,121 | 4,341,202 | Are there standard patterns for implementing a class to dynamically load images? | I've been tasked with creating an application that works with thousands of images, far too many to load into RAM all at once. I guess it's somewhat analogous to a photo viewer like Picassa, in that at any given moment the application needs the pixel data from only a handful of the total cataloged images. The applicatio... | If the larger images are really large, such that do not fit onto screen, then it may be reasonable to split them into smaller pieces.
If you have usually to display the images reduced (zoomed out) then you can ease your work by creating and storing the reduced versions of larger images. The whole cascade of reduced im... |
4,340,241 | 4,340,330 | SDL Surface Pixel Format Conversion | I want to convert an SDL_Surface, which was loaded by IMG_Load() to an other pixel format (rgba8) for an OpenGL Texture. How can I do that?
I've read about SDL_ConvertSurface() in the documentation, but I can't figure out, how to put it together.
| Give "How To Load an OpenGL Texture from an SDL_Surface" a shot:
GLuint texture; // This is a handle to our texture object
SDL_Surface *surface; // This surface will tell us the details of the image
GLenum texture_format;
GLint nOfColors;
if( (surface = SDL_LoadBMP("image.bmp")) )
{
// Check that the i... |
4,340,271 | 4,343,491 | Is C++ value of this guaranteed? | Consider I have a class Foo (that does not have its & operator overloaded) is the address obtained from the & operator of this class guaranteed to have the same value as its this pointer?
In the code below is equalPointer guaranteed to return true?
Are there any cases where it could return false (e.g. when considering ... | The issue is one of memory layout. The standard doesn't guarantee much about memory layout, in particular it doesn't guarantee that no offset exists between a derived and a base class...
For example:
class Foo: public boost::noncopyable
{
public:
virtual ~Foo();
};
Because boost::noncopyable doesn't have a virtual m... |
4,340,332 | 4,340,449 | pthread-win32 extension sem_post_multiple | I am currently building a thin C++ wrapper around pthreads for in-house use. Windows as well as QNX are targeted and fortunately the pthreads-win32 ports seems to work very well, while QNX is conformant to POSIX for our practical purposes.
Now, while implementing semaphores, I hit the function
sem_post_multiple(sem_t*... | In any case semaphores are an optional extension in POSIX. E.g OS X doesn't seem to implement them fully. So if you are concerned with portability, you'd have to provide wrappers of the functionalities you need, anyhow.
Your approach to emulate an atomic increment by iterated sem_post has certainly downsides.
I... |
4,340,415 | 4,340,500 | QComboBox - set selected item based on the item's data | What would be the best way of selecting an item in a QT combo box out of a predefined list of enum based unique values.
In the past I have become accustomed to .NET's style of selection where the item can be selected by setting the selected property to the item's value you wish to select:
cboExample.SelectedValue = 2;
... | You lookup the value of the data with findData() and then use setCurrentIndex()
QComboBox* combo = new QComboBox;
combo->addItem("100",100.0); // 2nd parameter can be any Qt type
combo->addItem .....
float value=100.0;
int index = combo->findData(value);
if ( index != -1 ) { // -1 for not found
combo->setCurrent... |
4,340,469 | 4,340,725 | quicksort bug not found | after working a whole day on this, i cannot find what is wrong with my code, i cannot find where my error is. can someone please help me figure out what i did wrong?
void a_quick(int array[], int i, int j){
//Array Quick Sort
if ((j - i) < 2){
return;
}
int top = j;
int bot = i;
int p_lo... | this code works fine for me
void a_quick(int array[], int i, int j){
//Array Quick Sort
int top = j;
int bot = i;
int p_location = (j + i) / 2;
int pivot = array[p_location];
do {
while (array[i] < pivot)i++;
while (array[j] > pivot)j--;
if (i <= j){
swap... |
4,340,506 | 4,340,952 | Cache Optimization of C++ Code | This might seem kind of open-ended, but I'm having trouble with optimizing a piece of C++ code for multiple processors and the cache.
More important than multiple processors is the cache: I am iterating over 2 nested loops
for(int i=0; i<n; i++){
//do a little something here with a single array
for(int j=0; j<whoaA... | One possibility for cache-use improvement is to modify your pattern of access to array and otherArray. When you read array[i][j] your machine will, of course, move a 'line' of memory into cache. When you read otherArray[i][j] your machine will, of course, move a 'line' of memory into cache. It is possible that to r... |
4,340,779 | 4,340,989 | Closing Window and Thread Generates Invalid Window Handle Error - C++ | My console application spawns a new (invisible) window in its own thread. Prior to exiting the application, it attempts to clean up, and the last call to GetMessage in the window's message pump fails. GetLastError returns 1400, "Invalid window handle."
This is how the clean up proceeds in the application thread:
if (... | You are passing an invalid window handle to GetMessage, which is why it's failing and reporting that a window handle is invalid.
You'll see the same error if you run this code with a made-up window handle:
MSG msg = {0};
BOOL b = ::GetMessage(&msg, (HWND)(0x123000), 0, 0);
if (b == -1)
{
DWORD dwErr = ::GetLastErr... |
4,340,792 | 4,340,840 | How can I make an instant-dependant static variabe in a class method? | I have a function in a class the more or less works like so:
class Player {
private:
Object* minions[16]
public:
void Summon(Object* obj);
};
Player::Summon(Object* obj) {
static int i = 0;
if (i == 16)
return;
minions[i] = obj;
i++;
}
The problem arise when trying to use more than one... | Change Object* minions[16]; to a std::vector<Object*> minions;. That way you can just use minions.size() to know how many there are, or minions.push_back(obj); to add one without worrying about array index stuff.
|
4,340,987 | 4,341,380 | Resolving 'LNK2019 unresolved external symbol' on DirectDrawCreate | I've been attempting to get DirectDraw to function on a CE5.0 framework for the last week and I'm running into some very odd issues.
ddrval = DirectDrawCreate(NULL, &lpDD, NULL);
When I have this function in my code, I get "error LNK2019: unresolved external symbol _DirectDrawCreate referenced in function "bool __cdec... | You should link your program with ddraw.lib. This is the import lib for direct draw on windows mobile.
|
4,341,041 | 4,341,087 | Creating pointer using #define | Is it possible to create pointer using #define?
Something like this:
#define *HEY
I'll use it for something like this:
#define *HEY 2
...
int *s=HEY;
| No, asterisks aren't allowed in #define macro names.
Your example variable declaration wouldn't work anyway, because it doesn't contain the text *HEY, it only contains HEY, which doesn't match the defined macro name.
What's that code intended to do? Make a pointer that points to the number 2?
|
4,341,045 | 4,341,064 | separate digits of a long number in c++ | I have for example the long number 12345678901 and I want to get separately each digit to use it. I tried really hard but I didn't make it so far? Any ideas?
but I have a problem in all of them
when I try those with a number of 11 digits and more (that what I want) my program stops working
I'm running my program in vis... | This will give you digits in variable b.
long a = 12345678901;
while(a > 0) {
long b = a % 10;
a /= 10;
}
|
4,341,198 | 4,341,255 | Forward Declaration of Class, Function | When forward declarations of functions work in a source file (.cpp), why would the same doesn't work for classes ?
Thanks.
// main.cpp
void forwardDeclaredFunction() ; // This is correct
class One ; // Why this would be wrong
int One:: statVar = 10 ;
void
One :: anyAccess() {
std::cout << "\n statVar:\t " << s... | Forward declaration can work for classes too:
class Foo;
class Bar {
public:
Foo *myFoo; // This has to be a pointer, thanks for catching this!
};
class Foo {
public:
int value;
};
The above code shows a forward declaration of the Foo class, using a variable of type Foo* in another class (Bar), then the ac... |
4,341,254 | 4,341,293 | Distinguishing between string formats | Having an untyped pointer pointing to some buffer which can hold either ANSI or Unicode string, how do I tell whether the current string it holds is multibyte or not?
| Unless the string itself contains information about its format (e.g. a header or a byte order mark) then there is no foolproof way to detect if a string is ANSI or Unicode. The Windows API includes a function called IsTextUnicode() that basically guesses if a string is ANSI or Unicode, but then you run into this proble... |
4,341,303 | 4,341,321 | Get the WNDPROC for windows handle | Exist any Windows api function to retrieve the WNDPROC for a Windows Handle?
Thanks in advance.
| Use GetWindowLongPtr(hwnd, GWLP_WNDPROC).
Caution: GetWindowLongPtr is actually #defined to GetWindowLong for 32-bit systems, so in order to import it in Delphi you might need to use GetWindowLong instead. As well, GetWindowLongPtr itself is #defined to either GetWindowLongPtrA or GetWindowLongPtrW (for non-unicode and... |
4,341,372 | 4,342,090 | AcceptEx returns 1022 (WSAEINVAL)... What did I do wrong? | I am trying to code a small test-server for completion ports.
But when I try to call AcceptEx... it always returns WSAEINVAL as the winsock error code...
I don´t really get what was my mistake
http://codepad.org/NEXG3Ssh <- code on codepad
and
StartWinsock();
cout << "Winsock initiated\n";
//Get the number of process... | Te problem in your code is this:
while(true)
{
memset(&over, 0, sizeof(over));
if(AcceptEx(AcceptorSock, newSock, lpOutputBuf, outBufLen - ((sizeof(sockaddr_in) + 16) * 2), sizeof(sockaddr_in)+16, sizeof(sockaddr_in)+16, &dwBytes, &over) == FALSE)
{
int x = WSAGetLastError();
if( x != WSA_IO_PENDING)
... |
4,341,523 | 4,341,534 | When assigning in C++, does the object we assigned over get destructed? | Does the following code fragment leak? If not, where do the two objects which are constructed in foobar() get destructed?
class B
{
int* mpI;
public:
B() { mpI = new int; }
~B() { delete mpI; }
};
void foobar()
{
B b;
b = B(); // causes construction
b = B(); // causes construction
}
| The default copy assignment operator does a member-wise copy.
So in your case:
{
B b; // default construction.
b = B(); // temporary is default-contructed, allocating again
// copy-assignment copies b.mpI = temp.mpI
// b's original pointer is lost, memory is leaked.
// temp... |
4,341,570 | 4,341,919 | Why does a C/C++ compiler need know the size of an array at compile time? | I know C standards preceding C99 (as well as C++) says that the size of an array on stack must be known at compile time. But why is that? The array on stack is allocated at run-time. So why does the size matter in compile time? Hope someone explain to me what a compiler will do with size at compile time. Thanks.
The ... | To understand why variably-sized arrays are more complicated to implement, you need to know a little about how automatic storage duration ("local") variables are usually implemented.
Local variables tend to be stored on the runtime stack. The stack is basically a large array of memory, which is sequentially allocated ... |
4,341,649 | 4,343,288 | how to put a derived control ("MyCEdit") onto a dialog or property page? | This should be obvious, but I can't find anywhere that spells it out.
I want to derive a MyCEdit from CEdit so I can override the OnChar handler and do useful things with keyboard input to an edit box. Each edit box I have fills the client area on a MyCPropertyPage (derived from CPropertyPage), and several such pages m... | HI if i understand you need you can add simple edit to your page, then add control variable and write MyCEdit in class name field. And dont forget to set parent notify option in resource editor on your MCPropertyPage.
|
4,341,870 | 4,341,925 | About Memory Management When mentioning C++ | When someone mention the memory management the c++ is capable of doing, how can i see this thing? is this done in theory like guessing?
i took a logical design intro course and it covered the systems of numbers and boolean algebra and combinational logic,will this help?
so say in Visual Studio , is there some kind of ... | C++ has a variety of memory areas:
space used for global and static variables, which is pre-allocated by the compiler
"stack" memory that's used for preserving caller context during function calls, passing some function arguments (others may fit in CPU registers), and local variables
"heap" memory that's allocated usi... |
4,342,047 | 4,342,938 | Compiling a Qt application for Mac OS X on Linux | I'm developing a Qt application and I need to support Linux, Windows and Mac OS X. The only problem however is that I do not own a Mac. Is it possible to compile my application for Mac OS X on Linux and package it in a .dmg file?
I'm also worried with the fact that my application depends on OpenSSL, can I compile OpenS... | How do you want to support Mac if you can't even test if your software works?
Cross-compilation for OS X: I doubt there is any solution out there (I'd love to learn about it if it is), you'd need the whole SDK and toolchain for that.
For the .dmg file creation part, there is another question here:
How to build a dmg M... |
4,342,068 | 4,342,129 | C++: Infinite loop with a simple menu selection | The script I am working on is over a page long, so I am going to link it (one simple file):
http://pastebin.com/7BVHmQGp
I apologize for that. My problem is I get into an infinite loop in my code, for example after I select 1 or 2 for encrypting/unencrypting it lets me enter the word, and when I next enter the "shift" ... | I think you should be ignoring the newline character instead of a space
I tried with the following and it works on VS2010
cin.ignore(1, '\n');
getline(cin, input);
|
4,342,293 | 4,342,368 | C++ project not compiling | I created an empty c++ console application with visual studio 2010 and dragged and dropped the source files from http://blogs.msdn.com/b/matthew_van_eerde/archive/2008/12/16/sample-wasapi-loopback-capture-record-what-you-hear.aspx but when I click on rebuild I get a load of errors which dont direct me anywhere in the s... | Well if you check in your source folder, you'll see that there are a few libraries that must be linked to:
TARGETLIBS = \
$(SDK_LIB_PATH)\avrt.lib \
$(SDK_LIB_PATH)\ole32.lib \
$(SDK_LIB_PATH)\winmm.lib \
In this particular case, you will want to go into your VS2010 settings for the project you've created ... |
4,342,459 | 4,342,818 | Outputting the data from a USB port? (Windows) | I was wondering if the WinAPI or something has a way to get the raw data from a USB device, or something that would lead me in the right direction for this sort of thing.
for example, for an midi device, this data might be the velocity, and which note was hit.
Thanks
| Not directly but you can now use usblib on windows
|
4,342,795 | 4,357,154 | How do I find intersection of mouse click and a 3D mesh? | In my program I'm loading in a 3D mesh to view and interact with. The user can rotate and scale the view. I will be using a rotation matrix for the rotation and calling multmatrix to rotate the view, and scaling using glScalef. The user can also paint the mesh, and this is why I need to translate the mouse coordinates ... | making the ray from the camera to the scene using the ray dir, I should've used:
bool intersected = findIntersection(gmVector3(m1x,m1y,m1z), dir, point);
(notice the different vector being passed to the function). This solved my problem, and didn't have anything to do with the gluLookAt after all!
Also, for the secon... |
4,342,831 | 4,342,848 | Storing and accessing a collection of strings (STD C++) | SKU1 SKU2 Description
"01234" "34545" "White Bread"
"01545" "34236" "Wheat Bread"
I need to cross-reference these three fields, i.e. retrieve SKU2 while knowing SKU1, SKU1 while knowing SKU2, and Description while knowing either SKU1 or SKU2.
I'm curious - what is the best way to do this? Ve... | Build three std::map<std::string, std::string>s: one to map SKU1s to SKU2s, one to map SKU1s to Descriptions, and one to map SKU2s to Descriptions. (Better yet, use std::unordered_map, if you have it (C++0x)).
This is assuming that you have a lot of data and are prioritizing speed rather than memory usage.
|
4,342,881 | 4,342,987 | PHP Extension with C++ | I recently started looking at writing PHP extensions and I read through this article, which describes a starting point for building an extension using C++. As I've started to customize, I've run into a hitch trying to split some of the functionality into a separate file. Everything compiles and links without problems, ... | When compiling template classes, the implementation must be available from the header file since the C++ complier needs the template arguments in order to compile a template class. If a C++ compiler were to compile just internals.cpp, it would not be able to create any code as the type T is not known. It would only be ... |
4,342,957 | 4,343,001 | Why does vector not have sort() method as a member function of vector, while list does? | There is a sort() method for lists in STL. Which is absurd, because I would be more inclined to sort an array/vector.
Why isn't sort() provided for vector? Is there some underlying philosophy behind the creation of the vector container or its usage, that sort is not provided for it?
| As has already been said, the standard library provides a nonmember function template that can sort any range given a pair of random access iterators.
It would be entirely redundant to have a member function to sort a vector. The following would have the same meaning:
std::sort(v.begin(), v.end());
v.sort();
One of... |
4,343,130 | 4,343,150 | Why does STL set have count() when all elements are supposed to be unique? | I can understand that multiset has count(), for counting the number of occurrences of a value, because elements can be repeated in multiset.
But what's the point of having count() in set, when all the values are already unique?
| count is part of the associative container requirements(1).
Every associative container is required to provide it as part of its interface, even if the result is always zero or one as is the case with std::set.
(1) This is a link to the SGI STL documentation describing the Associative Container concept; the concept ... |
4,343,175 | 4,347,470 | Where is boost::filesystem::last_write_time? | This is the linker error I'm getting. All the rest of my boost::filesystem things are resolving. I'm not understanding why this one does not. I thought it was a problem with boost 1.40, so I upgraded to 1.44 and the problem remains. I'm using #define BOOST_FILESYSTEM_VERSION 3 but I see no mention of last_write_tim... | Ok, the problem is as simple as it is obtuse. In VS2008 and above time_t is 64 bits, unless you #define _USE_32_BIT_TIME_T. The boost libraries are compiled without this definition and therefore time_t is 64 bits for them. My project due to some legacy issues does define _USE_32_BIT_TIME_T and therefore generates th... |
4,343,220 | 4,343,274 | Does insertion to STL map invalidate other existing iterator? | I used std::map in STL. Can I use iterator after some other element inserted to the map? Is it still valid?
| When in doubt as to the semantics of an operation on a container, consult the documentation:
Map has the important property that inserting a new element into a map does not invalidate iterators that point to existing elements.
Erasing an element from a map also does not invalidate any iterators, except, of course, for... |
4,343,267 | 4,343,310 | C++ : In how many ways compiler optimizes away our code? | .
I would like to know all the possible ways (or atleast the popular ones) in which compilers can/do optimize away our code written in C++? I also would like to know how exactly the optimization is done (in each case)!
So far, I'm aware of two optimizations, viz. Empty Base Optimization (EBO) and Return Value Optimizat... | Incredibly broad, because there are many optimizations and compiler writers are always thinking up more. There are tons of them, some optimizing for run time, others optimizing for binary size. Many aren't specifically C++ either, the general compiler optimization techniques are implemented for many compilers/interpret... |
4,343,576 | 4,384,033 | Determine whether caller is called from EXE or DLL | I need to determine the caller code whether is coming from EXE or DLL.
DLL
#ifdef DLL_EXPORTS
__declspec(dllexport) void say_hello();
__declspec(dllexport) void getCurrentModuleName();
#else
__declspec(dllimport) void say_hello();
__declspec(dllexport) void getCurrentModuleName();
#endif
#include <cstd... | Here is the solution. The limitation is that, it is only able to trace up to 62 frames.
// Must have in order for us to turned address into module name.
SymInitialize(GetCurrentProcess(), NULL , TRUE);
// Limitation of RtlCaptureStackBackTrace.
const int kMaxCallers = 62;
void* callers[kMaxCallers];
int count = RtlCap... |
4,343,850 | 4,350,645 | Variable Length Array overhead in C++? | Looking at this question: Why does a C/C++ compiler need know the size of an array at compile time ? it came to me that compiler implementers should have had some times to get their feet wet now (it's part of C99 standard, that's 10 years ago) and provide efficient implementations.
However it still seems (from the answ... |
How VLAs are implemented in gcc / VC++ ?
AFAIK VC++ doesn't implement VLA. It's a C++ compiler and it supports only C89 (no VLA, no restrict). I don't know how gcc implements VLAs but the fastest possible way is to store the pointer to the VLA and its size in the static portion of the stack-frame. This way you can ac... |
4,343,867 | 4,343,949 | Deleting a pointer to an automatic variable | Please look at this code
int i = 10; //line 1
int *p = &i; //line 2
delete p; //line 3
cout << "*p = " << *p << ", i = " << i << endl; //line 4
i = 20; //line 5
co... | You can delete only a pointer if you have ever allocated it dynamically using new. In this case you have not allocated the pointer using new but simply defined and initialized it to point to a local variable of type int.
Invoking delete on a pointer not allocated dynamically using new is something called Undefined Beha... |
4,343,875 | 4,343,920 | Linking against hard-coded function pointer | I know that a particular function with a known signature is located at a known address. How do I initialise the function pointer in C++?
I have tried the following (and many variations thereof) to no avail:
int (*FunctionName)(int arg1, long arg2, char *arg3) = (int (*FunctionName)(int arg1, long arg2, char *arg3))0xCA... | Aside from the fact that CAKE is not a proper Hex value because K is not a valid hex character, plus any issues about different pointer types your main error is that FunctionName is a variable not a type.
It is like doing
px = (px)0xBADFACE;
where px is an regular pointer
If you remove FunctionName on the right leaving... |
4,343,934 | 4,343,953 | Uninitialized constant members in classes | This is probably a ridiculously easy question, but I've been searching around for the answer for a while yet can't seem to figure this out. I'm trying to initialize a constant variable constant pointer in a class. Here is the header file:
class Scheduler{
public:
Scheduler();
explicit Scheduler( unsigned long * )... | You must initialize your constant member in the initialization list of ALL constructors. You are doing it only for the one with an argument. Do it for the default one too, and everything will be fne. In this particular case, either initialize your thresh with 0, or disable the default constructor.
|
4,344,043 | 4,344,178 | How to create a little database with search function and pdf download / upload | I'm trying to code a small program for my friend's company. They build metal cabinets and every cabinet is made out of several parts. So when a customer tells them they need a new cabinet, they tell them the single part numbers. My friend needs now a little tool/database where he can look after those part numbers and i... | Have used sqlite for database applications and found it to have a lot of functionality and speed. It lacks all the advanced database admin stuff but for single user/embedded databases its ideal. I use it over MySQL because of a significant performance improvement.
It has a Java interface via java.sql.Connection.
|
4,344,137 | 4,344,146 | find method of the set | What exactly find method of the standart set returns? Iterator to the actual element in the set or to its copy.
| It returns an iterator pointing to the actual element in the set
From table 69 in standard 23.1.2/7
expression
a.find(k)
assertion/note pre/post-condition
returns an iterator pointing to an
element with the key equivalent to k,
or a.end() if such an element is not
found.
|
4,344,162 | 4,345,305 | How to pass user-defined data to a worker thread using IOCP? | Hey... I created a small test server using I/O completion ports and winsock.
I can successfully connect and associate a socket handle with the completion port.
But I don´t know how to pass user-defined data-structures into the wroker thread...
What I´ve tried so far was passing a user-structure as (ULONG_PTR)&structure... | You can send special-purpose data of your own to the completion port via PostQueuedCompletionStatus.
The I/O completion packet will satisfy
an outstanding call to the
GetQueuedCompletionStatus function.
This function returns with the three
values passed as the second, third,
and fourth parameters of the call... |
4,344,201 | 4,344,420 | Boolean_conversions Using reinterpret_cast<> | Can any one Give the example for
Boolean_conversions Using reinterpret_cast<>
Iam getting the execution failure..Any one explain ..
Ex:
void Boolean_Conversions()
{
bool b = 0;
int *i = reinterpret_cast<int*> (&b);
// iam expecting as *i is 0/false ,but it is showing runtime error ... | No, the output is not defined. Note that the conversion is undefined.
On my machine *i = 0xcccccc00
Note the lsb which is 00
which corresponds to the value of the bool variable initialized with 0(false). The byte pattern in the other three bytes (assuming the size of int as 32-bits) is completely unspecified and depe... |
4,344,202 | 4,344,340 | CloseHandle confusion - Must I call CloseHandle on multiple "copies" of a handle? | I have some (more) questions about calling CloseHandle.
So, the SO citizens have spoken, and you must always close a handle.
Question 1
I've written the following code snippet in a destructor:
HANDLE handles[] = { m_hGrabberThread, m_hCtrlThread, m_hErrDispatchThread };
int nNumHandles = sizeof(handles) / sizeof(han... | To Question 2: The number of calls to CloseHandle should balance the number of calls to handle creation functions.
If you simply assign a handle to another HANDLE variable, you have not created a new handle - the two handles have the same value.
You can share the handle value as much as you want, but only one object mu... |
4,344,245 | 5,350,643 | vs2005 general error C10100b1(C++) | I'm ready to release my *.exe and set the release build in virtual studio 2005, but I got a error like that:
mt.exe: failed to load file "..\release\hasm.exe" {_~0 BEL SUB EOT BEL v STX
the BOLD string with 3-characters are symbol that can not print in plain text, and I can't copy them from my working conputer, but I e... | My guess is that the project settings for release got broken somehow. Compare all settings between the debug and release configs. If you can't find anything, it's probably something internal in the project. The best way to fix that is to create a new project in the same solution and add all your source files to it.
Hop... |
4,344,279 | 4,344,390 | How to pass a pointer to a C++ plugin | In our company we're using a plugin system that I've written using QT plugin system.
Each plugin has "needed functions" and "own functions" so, if a plugin needs a function called *func_1*, there must be a plugin that has a function called *func_1*.
This works great, but now I have a problem: a plugin needs to know the... | The modern C++ "replacement" for a void-pointer is something like Boost.Any. It'll allow you to pass anything through the interface, and still gives you a certain type-safety.
|
4,344,402 | 4,344,521 | C and C++ : Difference between Casting and Conversion | Is there any difference between line 2 and line 3 in the following code? What does compiler do in each case?
char ch = 'A'; //line 1
int i = ch; //line 2
int j = (int) ch; //iine 3
In general, what is the difference between Casting and Conversion (in C and C++)?
| There's no difference in the final effect.
A cast is to use explicit, general, built-in cast notation for conversion.
Although in some cases we say "up-cast" when we mean an implicit conversion from Derived* to Base* (or from Derived& to Base&).
And in some cases one defines new cast notation.
The above definition of t... |
4,344,464 | 4,344,530 | Initializing map and set class member variables to empty in C++? | I have a C++ class with two member variables
std::map<int, Node*> a;
and
std::set<Node*> b;
A style checker used at my University requires all member variables to be initialized in the constructor of the class. How can these member variables a and b be initialized to empty in the constructor of the class they are in... | Like this:
class A
{
public :
A() : s(),
m()
{
}
std::set< int > s;
std::map< int, double > m;
};
|
4,344,495 | 4,344,560 | Connecting T-SQL to C++ or C# | Which language is preferable if Im wanting to access a T-SQL like MS Server 2008? within my code?
I know both languages probably have extensions, I do use Visual Studio 2010. However I want to know which language is probably more.....lets say "well formed" to access the database with.
Like I know C# is kinda Microsofts... | Well, "the one you can do effectively now" would be a good start, which for you sounds like C++; I'm pretty sure both have extensive support for talking to SQL Server.
Personally I'd use C#, but that is simply because I know the libraries and tools pretty well, and could whack out a SQL call in a few seconds. I might e... |
4,344,569 | 4,572,925 | Visual Studio .NET 2003 - Ignore Specific Library for libcmt vs libcmtd | I have a template VS .NET 2003 project, which colleagues copy and customise when developing their software.
It appears the template was altered a while back to set the IgnoreSpecificLibrary property to have libcmt.lib for both release and debug builds (i.e. for both release and debug, the build should ignore libcmt.lib... | This is what happened:
After compiling the linker takes your object-files and create among others
a symbol table ,which has symol-request that have not been fullfilled.
Then the linker goes through your list of libraries trying resolve those
unfullfilled symbols. Since you ignore libcmt.lib ,your third-party library... |
4,344,623 | 4,344,770 | How do I profile code beyond per-function level? | AFAIK profilers can only tell how much time is spent in each function. But since C++ compilers tend to inline code aggressively and also some functions are not that short it's often useful to know more details - how much time each construct consumes.
How can this be achieved except restructuring code into smaller funct... | If you use a sampling profiler (e.g. Zoom or Shark), rather than an instrumented profiler (e.g. gprof) then you can get much finer grained profiles, down to the statement and instruction level.
|
4,344,878 | 4,345,162 | implementation of the set | Is it possible to find in the net the full implementation of the STL Set, particularly I'm interested in the iterator?
|
Under Visual Studio, an easy way is to right click on a #include <set> and "Open Document" : the IDE will search the include paths for you and open up the file regardless of your installation directory
The sources for libstdc++ are available and can be easily browsed online (as a matter of fact, I'm often referring to... |
4,345,148 | 4,345,170 | a socket and queue problem | I have some code:
a declaration of a queue:
typedef deque<char*, allocator<char*> > CHARDEQUE;
typedef queue<char*,CHARDEQUE> CHARQUEUE;
CHARQUEUE p;
size_t size_q;
char recv_data[1024];
I use a udp socket to receive data from a distant machine:
this is the loop:
while (1)
{
bytes_read = recvfrom(sock,recv_... | sizeof is determined in compilation time. You probably mean something like p.size().
|
4,345,235 | 4,345,316 | Saving pointers to file in C++ | I'm developing a game for a course at my school. One of the assignments is to enable saving the game to a file and later load the game from the same file.
The problem I'm having are pointers. I'm not allocating anything on the stack (due to ownership of an item for example) so all the classes have pointers to whatever ... | By using UIDs, you create a mapping:
serialized_object -> UID -> deserialized_object.
Why bothering? You already have UIDs, and these are pointers to objects. By using this mapping:
&serialized_object -> &deserialized_object
you drop a level of indirection, UIDs as created automatically, and all you have to do is to... |
4,345,357 | 4,345,660 | C++: tall class hierarchies | What are the run time disadvantages of having a tall class hierarchy?
Let's call H the height of the hierarchy (ie: how many classes are traversed to go from the base class to a leaf).
dynamic_cast will cost more: it costs O(H).
Are there other operators or language features suffering?
| The main problem will be maintainability. A deep class hierarchy is probably not modeled correctly. Anything more than 3-4 levels should get you alerted. You are probably deriving from concrete classes, something you should never do (Liskov Substitution principle doesn't allow this). Refactoring will be difficult if yo... |
4,345,415 | 4,345,534 | socket, detect connection is lost | I'm connecting a server process and a client process with a TCP connection, and I have to detect
that physical connection between the two machines is down. I'm trying to do this using the keepalive,
decreasing the default system wide values to:
TCP_KEEPIDLE=5
TCP_KEEPCNT = 5
TCP_KEEPINTVL = 1
When the connection go... | TCP Keepalive isn't intended for this use.
If you want to detect outages at the application layer, do what protocols like SSH, IMAP and IRC do - implement an echo/ping type message at the application layer. Send them on a regular basis, and if you don't get a timely reply, the connection can be assumed to be down.
|
4,345,429 | 4,345,582 | What kind of encoding is used by torrent files and how can i append trackers? | I need to modify trackers in torrent files using C, What type of encoding do they use?? When I just print characters in ascii they print gibberish.
Or is there a direct way of adding trackers to a torrent file using C?
| Have you tried documenting yourself regarding .torrent file format ? The Wikipedia article seems to be pretty complete on this question.
|
4,345,536 | 4,346,253 | What should a developer know about interoperability with managed code | As a C# developer, I think many of us have the experience as calling unmanaged code from managed code.
What is the most difficult problem you've ever faced when dealing with interoperability between managed code and unmanaged code? (You had better give code examples such as C++ function signature and C# wrappers)
How d... | In general, finding an authoritative reference for P/Invoke declarations is difficult if you don't know enough about C to get the declaration right. There are a lot of bad declarations out on the Internet. The typical traps are VB6 declarations, there are a lot of them out there, where arguments that are really int a... |
4,345,566 | 4,345,607 | CUDA Beginner - Force waiting for a thread to finish before moving on | I am learning CUDA and I have something like this at the moment.
__device__ void iterate_temperatures(int fieldSize, Atom *atoms) {
int temperature = threadIdx.x + blockDim.x * blockIdx.x;
nAtoms = pow(fieldSize, DIMENSION);
iterate_atoms<<< nAtoms >>>(atoms, nAtoms, temperature);
}
Thing is, each temperatur... | Just putting in a call to __syncthreads() should do exactly what you want.
|
4,345,767 | 4,345,809 | Calling a virtual function statically through a function pointer | Please consider the following code.
#include <iostream>
#include <memory>
struct A {
A() {}
virtual void f() {
std::cout << "A::f" << std::endl;
}
private:
A(const A&);
};
struct B : public A {
virtual void f() {
std::cout << "B::f" << std::endl;
call(&A::f);
}
private:
void call(void (A::*a... | That's expected. The object expression is a Reference to the Base class A and hence virtual function mechanism (dynamic binding) is triggered as A::f is virtual.
Only the :: operator can supperess virtual function call mechanism.
$10.3/12- "Explicit qualification with
the scope operator (5.1) suppresses
the virtua... |
4,345,968 | 4,346,214 | Boost: having an array of ints and some special int how to find nearest to yours in array? | So I hava an unsorted array of 30 ints like 340, 6401 1280, and so on random numbers. I have int x which was cined by user. I need to find which value in array is nearest down (lower, smaller,less) to that x value. How to do such thing?
| You could use std::max_element() with a custom comparison operator:
struct limited_cmp {
int limit;
limited_cmp(int a_limit) : limit(a_limit) {
}
bool operator()(int left, int right) const {
if (left <= limit && limit < right) {
return false;
}
return (left < right);
}
};
int ... |
4,346,010 | 4,346,087 | Copy std::stack into an std::vector | Is the following code guaranteed by the standard to work(assuming st is not empty)?
#include <vector>
#include <stack>
int main()
{
extern std::stack<int, std::vector<int> > st;
int* end = &st.top() + 1;
int* begin = end - st.size();
std::vector<int> stack_contents(begin, end);
}
| Yes.
std::stack is just a container adapter.
You can see that .top() is actually (§23.3.5.3.1)
reference top() { return c.back(); }
Where c is the container, which in this case is a std::vector
Which means that your code is basically translated into:
extern std::vector<int> st;
int* end = &st.back() + 1;
in... |
4,346,150 | 4,346,396 | How to change the amount of building threads in Xcode? | I'm building a couple of C++ files in xcode that take a lot of memory to compile (+1 GB / file). Because I do this on my dual core laptop, xcode uses 2 threads for building. The two threads will eventually be building the files that take a lot of memory simultaneously so the system suffers memory starvation and the com... | The number of threads Xcode is using to perform tasks is controlled by PBXNumberOfParallelBuildSubtasks option. You can change it with the following command: - defaults write com.apple.Xcode <key> <value>. For example:
defaults write com.apple.Xcode PBXNumberOfParallelBuildSubtasks 8
See Xcode User Defaults for more d... |
4,346,240 | 4,353,718 | How can I read from memory just like from a file using iostream? | I have simple text file loaded into memory. I want to read from memory just like I would read from a disc like here:
ifstream file;
string line;
file.open("C:\\file.txt");
if(file.is_open())
{
while(file.good())
{
getline(file,line);
}
}
file.close();
But I have file in memory. I have ... | I found a solution that works on VC++ since Nim solution works only on GCC compiler (big thanks, though. Thanks to your answer I found other answers which helped me!).
It seems that other people have similar problem too. I did exactly as here and here.
So to read from a piece of memory just like form a istream you hav... |
4,346,403 | 4,346,462 | buffer's socket to queue issue | I have some code:
a declaration of a queue:
typedef deque<char*, allocator<char*> > CHARDEQUE;
typedef queue<char*,CHARDEQUE> CHARQUEUE;
CHARQUEUE p;
size_t size_q;
char recv_data[1024];
I use a udp socket to receive data from a distant machine:
this is the loop:
while (1)
{
bytes_read = recvfrom(sock,recv_data,10... | The problem is that you are pushing a "char*" which is a pointer into your queue, not the actual data!
Use a std::vector<char>, as below (no error checking etc - which you should do btw.!):
std::deque<std::vector<char> > p;
std::vector<char> read_buff;
// per loop iteration
read_buff.resize(1024);
// read
bytes_read... |
4,346,425 | 4,356,709 | Unix Domain Sockets, Udp Sockets Objective C what to use? | I'm writing an interactive editing video application that uses Quartz Composer as a real time video processor. Time and synchronization are very important in my application.
My first application coded in C++ must send commands like "play" at this "path" "this file video" "start" at this "time" "stop", etc. For this ud... |
Yes i'm using UDP for Local machine
i'm wondering if Unix domain sockets
are faster enough to send for example
25/s or 30/s updates to my GUI in the
other application UDP just gets
stuck...
Unix sockets might be a little faster, and probably more importantly they provide reliable delivery (unlike UDP). But... |
4,346,450 | 4,346,470 | Unfamiliar Basic C++ Code |
Possible Duplicate:
What does '?' do in C++?
xo = ((temp.npieces%2)==1)? 1 : 2;
I can't figure out what this means in it's entirety.
xo is an integer (I think simply determining the difference between a naught and a cross)
temp is an instance of position which stores information about a naughts and crosses board ... | xo = ((temp.npieces%2)==1)? 1 : 2;
if temp.npieces is Even (therefore division remainder is 0) xo is now equal to 2
other wise xo is now equal to 1;
Edit : It does not check if it is Odd, it checks whether the remainder is positive 1.
X ? A : B
is another way of writing
if(X)
{
A
}else
{
B
}
Edit2 :
The pu... |
4,346,480 | 4,346,519 | error in class destructor | I just started my container class and already I'm having issues:
class Container
{
private:
string* BasePointer; // The starting pointer.
unsigned int Capacity; // The number of values the container can hold.
public:
Container() // Default constructor.
{
Capacity = 1;
BasePoin... | The XXX ptr = new XXX[size] should be matched with array version delete [] ptr, not just regular delete.
Read about free store management in C++, and as James reminds us - follow the rule of three in cases like this.
|
4,346,535 | 4,346,660 | linking problem tinylibxml C++ Ubuntu | I am getting error when I try to execute the simple tinylibxml program.
OS -> Ubuntu
IDE -> e
I have download libtinyxml through apt-get install
and included the header in my program
But I am still getting error
Sample code is pasted below
#include "tinyxml.h"
#define TIXML_USE_STL
#include <tinyxml.h>
void dump_to_st... | when building you will need to do something like
g++ -c mycode.cpp (assuming your source file is mycode.cpp)
this should generate mycode.o
you now need to do:
g++ -o mycode -ltinyxml mycode.o
which is the linking step. This will combine your compiled source file with the tinyxml library to produce a final executable bi... |
4,346,742 | 4,346,759 | STL vector and thread-safety | Let's say I have a vector of N elements, but up to n elements of this vector have meaningful data. One updater thread updates the nth or n+1st element (then sets n = n+1), also checks if n is too close to N and calls vector::resize(N+M) if necessary. After updating, the thread calls multiple child threads to read up to... |
I want to ask whether a problem may occur during reallocating of vector to a larger memory block, if there are some child working threads left from the previous update.
Yes, this would be very bad.
If you are using a container from multiple threads and at least one thread may perform some action that may modify the s... |
4,346,828 | 4,347,106 | Using _bstr_t to pass parameter of type BSTR* in function | What is the correct way of doing this:
_bstr_t description;
errorInfo->GetDescription( &description.GetBSTR() );
or:
_bstr_t description;
errorInfo->GetDescription( description.GetAddress() );
Where IError:GetDescription is defined as:
HRESULT GetDescription (BSTR *pbstrDescription);
I know I could easily do this:
... | The BSTR is reference counted, I seriously doubt that will work right if you use GetAddress(). Sadly the source code isn't available to double-check that. I've always done it like this:
BSTR temp = 0;
HRESULT hr = p->GetDescription(&temp);
if (SUCCEEDED(hr)) {
_bstr_t wrap(temp, FALSE);
// etc..
}
|
4,346,852 | 4,346,952 | why its jumping out of program? | I just start learning C++.
When I execute my code it's jumping out of the program without any error. Why?
#include "stdafx.h"
#include <iostream>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
char s1[20],s2[10];
cout<<" enter a number : ";
cin.get(s1,19);
cout<<" enter a number : ";
cin.get(... | The method get() reads upto the '\n' character but does not extract it.
So if you type: 122345<enter>
This line:
cin.get(s1,19);
Will read 12345, but the '\n' (created by hitting <enter>) is left on the input stream. Thus the next line to read:
cin.get(s2,9);
Will read nothing as it sees the '\n' and stops. But it do... |
4,346,909 | 23,494,057 | Is it possible to run a cuda kernel on multiple gpus | This is a fairly simple question but googling doesn't seem to have the answer, so.
What I want to know is if I have two gpu cards (identical) capable of running cuda, can my kernel span these cards? Or is it bound to one card or the other? I.e. is cuda presented with the entire set of available gpu cores, or just the o... | A single CUDA kernel launch is bound to a single GPU. In order to use multiple GPUs, multiple kernel launches will be required.
The cuda device runtime API focuses on whichever device is selected. Any given kernel launch will be launched on whichever device was most recently selected using cudaSetDevice()
Examples of... |
4,347,010 | 4,347,227 | Is (++i)++ undefined behavior? | Is (++i)++ undefined behavior? Is it possible that the side effect of prefix increment happens after retrieving the incremented object for postfix increment to operate on? That would seem strange to me.
My gut feeling says this is undefined in C++03 and well-defined in C++11. Am I right?
|
My gut feeling says this is undefined in C++03 and well-defined in C++0x.
Yes you are right. The behaviour is undefined in C++03 because you are trying to modify i more than once between two sequence points.
The behaviour is well defined in C++0x because (++i)++ is equivalent to (i += 1)++. The side effects of the +=... |
4,347,151 | 4,368,756 | How to use the boost library (including shared_ptr) with the Android NDK and STLport | This is more of an answer than a question, because I've figured it out, at least as far as cleanly compiling the library. The main issue for me was to get shared_ptr working.
Ingredients:
Boost v. 1.45.0
The version of STLport at http://www.anddev.org/viewtopic.php?p=29939.
Version r4b of the NDK.
Directions:
In your A... | It turned out that this approach does not entirely work when compiling a debuggable library. The release library is compiled with -O2 which optimizes out some infelicities, but the debug library is done with -O0 which reveals some additional problems. Furthermore, I wasn't too happy about having to edit the boost files... |
4,347,286 | 4,347,335 | C++ Binary Scope Resolution Operator and Classes | Is there a way to use "block" class scope resolution in C++ so that I don't have to write the same boilerplate code for every function in my class' implementation file.
I find it extremely repetitive to write the same class name and binary scope resolution operator (Classname::) when defining a function outside of the ... | No, unless you would implement it all in the header in the class definition (which you usually shouldn't).
Technically you could hack it with macros, but everyone else looking at the code would hate you for it. You'll have to get used to "the C++ way" here.
Depending on what IDE you work with, there are usually tools (... |
4,347,661 | 4,347,783 | implementing a C++ postfix increment operator | I compiled the following example:
#include <iostream>
#include <iterator>
using namespace std;
class myiterator : public iterator<input_iterator_tag, int>
{
int* p;
public:
myiterator(int* x) :p(x) {}
myiterator(const myiterator& mit) : p(mit.p) {}
myiterator& operator++() {++p;return *this;}
myiterator& ope... |
Is there somewhere defined what the postfix signature should look like on STL iterators?
The Standard.
The Standard dictates such things. In the case of this operation, the standard basically says "you have to return something that is convertible to const X&" where X is the iterator. In practice, this means you can... |
4,347,730 | 4,348,172 | Use of typename keyword with template function parameters | In C++, the typename keyword is needed so the compiler can disambiguate between nested types and nested values in templates. However, there are certain situations where no ambiguity is possible, such as when a derived class inherits from a nested class type.
template <class T>
class Derived : public T::type
{ };
Here... | If you slightly change your declaration, you get an entire different story
template <class T>
void foo(T::type& v);
That isn't unambiguous anymore. It could declare a variable of type void that is initialized by a bit-wise AND expression. The entire declaration would be templated. Of course, this semantically is all n... |
4,347,803 | 4,360,648 | Intercepting and hiding a window before it appears | I am developing a (in-process) plug-in to application and as part of my plug-in I want to replace the application's tool-tips with my own. However, there is no API available for me to do so, so I've decided to go low-level.
I know the window class of the tool tip, but the question is, how do I detect it being created a... | If you know the type of the window you want to block, you can simply subclass it and handle the destruction in your own WndProc. Use GetClassLongPtr() with GCL_WNDPROC on the tooltip class, use SetClassLongPtr() with GCL_WNDPROC to set your own WndProc and have it call DestroyWindow() on WM_CREATE and call the old WndP... |
4,347,820 | 4,347,852 | operator<< overloading ostream | In order to use cout as such : std::cout << myObject, why do I have to pass an ostream object? I thought that was an implicit parameter.
ostream &operator<<(ostream &out, const myClass &o) {
out << o.fname << " " << o.lname;
return out;
}
Thanks
| You aren't adding another member function to ostream, since that would require redefining the class. You can't add it to myClass, since the ostream goes first. The only thing you can do is add an overload to an independent function, which is what you're doing in the example.
|
4,347,921 | 4,409,249 | SFINAE compiler troubles | The following code of mine should detect whether T has begin and end methods:
template <typename T>
struct is_container
{
template <typename U, typename U::const_iterator (U::*)() const,
typename U::const_iterator (U::*)() const>
struct sfinae {};
template <typename U> static char... | Stephan T. Lavavej has this to say:
Please note that it is technically forbidden to take the address of a Standard Library member function. (They can be overloaded, making &foo::bar ambiguous, and they can have additional default arguments, defeating attempts to disambiguate via static_cast.)
So I guess I'm going to ... |
4,347,923 | 4,347,987 | Which one is the real Bubble Sort, and which one is better? | I had an argument with a friend about the real bubble sort of the following two algorithms, and about which one is better, no mention which one is mine, I just want to hear your answers on these two questions about those two algorithms (written in c++)
1-which one is the real bubble sort?
2-which one is better?
here ar... | Number Two is closer to the real one. All comparisons should be between adjacent elements.
But the real bubble sort would take a while loop instead of an outer for loop, and the while loop would execute again only if elements had to be swapped on the last pass, like this:
void BubbleSort(int Arr[], int size)
{
... |
4,347,944 | 4,350,917 | IOCP with task scheduler (Threaded Building Blocks) | I'm using TBB and was wondering how I could use IOCP with its task scheduler. Has anyone done this? If so, some details would be greatly appreciated.
I don't have much experience with IOCP, but I'd like to use it to send messages to all of my threads and outside of a task scheduler you can just give it the handle to th... | If you're using TBB, don't think in terms of threads, think in terms of tasks instead.
You probably want to use TBB's pipeline class. Assuming your interest is reading stuff in, the head of the pipeline would be doing IOCP stuff and feeding the rest of the pipeline with tasks.
This series of articles might be of inter... |
4,347,983 | 4,348,156 | How to redirect python interpreter output and catch it in a string in C++ program? | i am using python C++ API to run python commands from C++ program. I want to catch all the python output to a string, I've managed by the following redirection, to catch pythons stdout and stderr output:
#python script , redirect_python_stdout_stderr.py
class CatchOutput:
def __init__(self):
self.value = ''... | The Python interpreter will run inside your C++ process, so all its output will go to the stderr and stdout of the C++ program itself. How to capture this output is described in this answer. Note that with this approach you won't need to capture the output in the Python script any more -- just let it go to stdout and... |
4,348,058 | 4,348,101 | C++ operator overloading for complex number operations | I have an assignment in C++ and I'm having trouble getting started. The goal is to "design a class that uses the following overloaded operators for complex numbers: >> << + - * / "
My question isn't about the syntax of this, but more about the logic. I could use some help brain storming.
Input Sample:
2.5 -2.2
1.0 1... | It seems to me that the point is to demonstrate class operation overloading, so I think the idea is for you to make a class Complex which holds information about the real number and the imaginary number (the i means it's imaginary). Handle various operations between complex numbers in operator overrides you do yoursel... |
4,348,154 | 4,348,188 | Non null-terminated string compiler option for gcc | Update
turns out this is just another case of "c++ is not c blues"
What I want
const char hex[16] = "0123456789ABCDEF";
the only thing that works
char hex[16] = "0123456789ABCDE"; hex[15] = "F";
are there any compiler options or something I can do to make strings not null terminated in the gcc compiler. so that I ca... | No need for a compiler option, it's already non-NUL terminated. The standard says a NUL should only be added if it can fit, otherwise it would be an overflow. It may just be that the next byte in memory past your array is \0
§ 6.7.8p14
An array of character
type may be initialized by a character
string literal,... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.