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
5,135,900
5,135,934
Stack around the variable ' ' was corrupted
void GameBoard::enterShips() { char location[1]; int ships = 0; int count = 1; while(ships < NUM_SHIPS) { cout << "Enter a location for Ship " << count << ": "; cin >> location; cout << endl; Grid[location[0]][location[1]] = SHIP; ships++; count++; ...
You are prompting the memory address of location array to your user. You should ask location indices separately: void GameBoard::enterShips() { int location[2]; int ships = 0; int count = 1; while(ships < NUM_SHIPS) { cout << "Enter a location for Ship " << count << ": "; cin >> loc...
5,136,234
5,136,235
Does a loop reset every time you go through it?
#include <iostream> using namespace std; int main (void) { cout << " 1\t2\t3\t4\t5\t6\t7\t8\t9" << endl << "" << endl; for (int c = 1; c < 10; c++) { cout << c << "| "; for (int i = 1; i < 10; i++) { cout << i * c << '\t'; } cout << endl; } return 0; } Hey so this code produces a times table...I ...
It "reverts" to 1 because you explicitly set it to 1 as the start condition of the loop... The "i" name does not exist outside this loop, so each time this loop is run (for each iteration of 'c'), then "i" is a new variable, set to a start of 1.
5,136,295
5,136,332
switch "transfer of control bypasses initialization of:" when calling a function
I get a "transfer of control bypasses initialization of:" error when i try to build the following switch: switch (retrycancel) { case 4: //The user pressed RETRY //Enumerate all visible windows and store handle and caption in "windows" std::vector<MainHandles::window_data> windows = MainHandles()...
section 6.6.4 of the C++ standard: The goto statement unconditionally transfers control to the statement labeled by the identifier. The identifier shall be a label (6.1) located in the current function. section 6.7 of the C++ standard: It is possible to transfer into a block, but not in a way that bypasses...
5,136,419
5,136,722
Problem with CUDA program
Here's my code: #include <vector_types.h> #define sizeOfGrid 5 __global__ void stuff( float3 *grid ) { grid[0].x = 0.4f; //PROBLEM HERE?! } int main( void ) { float3 *grid[sizeOfGrid]; float3 *dev_grid; HANDLE_ERROR(cudaMalloc( (void**)&dev_grid, sizeOfGrid*sizeof(float3))); for(int i = 0; i < siz...
With float3 *grid[sizeOfGrid]; you are allocating an array of pointers to float3, not an array of float3. You should declare float3 grid[sizeOfGrid]; and use . instead of ->, or float3 *grid; and use malloc and free.
5,136,465
5,136,587
What is wrong with my logic?
if(location[0] <= 'H' || location[0] >= 'A' && location[1] <= 8 || location[1] >= 1) I am checking to see if the first indice is between 'A' and 'H' and the second indice is between 1 - 8. so the argument would = 1 if the user entered { A, 1 } -1 if the user entered { J, 1 }
Sorry guys, new here. I should have posted my entire method. Thank you for explaining the precedence of the operators, but my issue was that I was comparing a char with an int. All I needed to do was put ' ' around my numbers. void GameBoard::enterShips() { char location[2]; int ships = 0; int count = 1; ...
5,136,595
5,136,632
problem with sending bytes from client to server using TCP
My send() and recv() looks like this: int Send(const char* buffer, int size) { cout << "SIZE: " << size << endl; int offset; while(offset < size) { int n = ::send(getSocket(), buffer + offset, size - offset, 0); if(n == SOCKET_ERROR) { break; } offset ...
You have to initialize offset with zero. Otherwise it could be any random value. You do not need Sleep as send call is blocking. Buffer that you are sending could be split. So if you send, for example, 2K buffer, you could get it in two parts - 1.5K and 0.5K, so you have to perform multiple reads on a client side. MTU...
5,136,658
5,136,777
Using images in QListWidget, is this possible?
I am using QT to create a chat messenger client. To display the list of online users, I'm using a QListWidget, as created like this: listWidget = new QListWidget(horizontalLayoutWidget); listWidget->setObjectName("userList"); QSizePolicy sizePolicy1(QSizePolicy::Preferred, QSizePolicy::Expanding); sizePolicy1.setHoriz...
This is how you may conduct your debugging: Try the constructor that has both icon and text as arguments. Try to use that icon in another context to ensure it is displayable (construct a QIcon with same argument and use it elsewhere, e.g. QLabel!). Use icon() from the QListWidgetItem to receive back the icon and then ...
5,136,724
5,136,880
I have a table stored into memory. How do I sort it based on a column?
I have a table stored in contiguous memory. It needs to stay in that format after the sort. For example: int table[5][3] = { { 60, 5, 10 }, { 0, 200, 15 }, { 55, 50, 365 }, { 4, 7, 78 }, { 555, 8, 11 }, }; Except much bigger (the size of the biggest, in bytes, is approximately 27 KB). Each cell is ...
std::sort won't do it easily because arrays aren't assignable. However, std::qsort will do it: int cmp_first_column(const void *lhs_, const void *rhs_) { // optimize this to taste const int *lhs = static_cast<const int*>(lhs_); const int *rhs = static_cast<const int*>(rhs_); if (lhs[0] < rhs[0]) return ...
5,136,769
5,136,837
string::erase() gives different result in linux/windows
I have a piece of code which reads in a line from a file, then removes the whitespace and tells you the length of the string. In windows it works as I expect it to, however in linux it returns a different result. Code: // Find how many characters are in the first line std::string line; std::ifstream map ("l...
I think therefromhere is right. The solution is two-fold: Always set the binary flag when constructing an ifstream or ofstream. Let your code handle newlines however it wants, but don't rely on non-portable newline conversion. Choose a standard format (LF or CRLF) for the tile map, and output that format on all plat...
5,136,905
5,136,967
How to reset a radiobutton? Set back to default
You know the radiobutton? You can klick on it, then you got a simple black point in the circle. Fine. How can i get this out? I would like to reset the button, this circle should be clear. Im not able to do this, i tried everyhing... this->ui->radiobutton->clear this->ui->radiobutton->reset ... Any idea? Thank you
This should work: this->ui->radiobutton->setAutoExclusive(false); this->ui->radiobutton->setChecked(false);
5,136,928
5,137,177
Implementing nested linked lists (list of lists)
My linked list is about a video store . I should make a list with video details ( I know this part) and a list of customer details. Now the CUSTOMER list (The second nodetype) is where my problem lies. I have to display the customer's name ,acc no. etc AND the videos checked in and out by that customer (deleting and in...
If I understand correctly, this is a design question, and has nothing to do with linked lists in C++. For the rest of the implementation, I assume the following: There are N videos. The are currently K rentals, where 0 <= K <= N. There are M customers. There is no relationship between N and M, but it would be safe to...
5,137,111
5,137,192
OpenGL Alternative for Drawing Textures with Immediate Mode?
I'm writing a simple graphics engine that draws textures on the screen using OpenGL and C++. The way that I draw the textures is using the source code below--the drawing is done in a method contained in a "Sprite" class that I wrote, which is called by the main scene's game loop. glEnable(GL_TEXTURE_2D); glBindTexture...
You are using immediate mode, which isn't used much (if at all) in serious 3D graphics programming these days. In fact, on mobile devices with OpenGL ES (1.1 and 2.0) it isn't even available. At the very least, you should use vertex arrays, which are set up using glVertexPointer, glNormalPointer, glColorPointer and glT...
5,137,244
5,137,263
For loop logic error?
void GameBoard::print(const GameBoard& computerBoard) { Grid[0][0] = '1'; Grid[0][1] = '2'; Grid[1][0] = '3'; int i, j; int sides = SIZE; cout << " Your bombs: Your navy:" << endl << endl; for(i=0; i<SIZE; i++) { // prints your bombs cout << sides << " "; for(j=0; j<SIZE; j++) ...
I guess what you want is something like for(i=SIZE-1; i>=0; i--) because this is equivalent to for(i=0; i<SIZE; i++) both of these go from 0..SIZE-1 while for(i=SIZE; i>0; i--) goes from 1..SIZE (and so if you access an array of length SIZE using arr[i], will produce an error).
5,137,322
5,137,372
C++ problem "adapting" a three-parameters class template into a two-parameters class template
I have a class expecting a two parameters template, like this: template<template <class, class> class TwoParamsClass> class Test {}; also I have a class like this: template<int a, class A, class B> class ThreeParamsClass {}; I need an adapter that sets the first int param of "ThreeParamsClass", to be able to use them...
Not really understanding your reasoning, but try this: template<int n> struct Wrap { typedef Test<Alias<n>::template Type> WrappedTest; };
5,137,427
5,137,632
Trying to link my C++ executable with Fortran library (Cygwin environment)
All my fortran sources compiled fine with gfortran -g -c fortran_source.f and archived in a single library called "mylibrary.a" In there, there exists a function of interest called "myfunction" In my C++ file, I have: extern "C" void myfunction_(/* all pointers */); int main(){ cerr << "Mark 1" << endl; myfunction_(/*...
You need to name your library libMyLibrary.a and put it in your current directory then you can link it using g++ mainfile.cpp -L. -lMyLibrary or g++ mainfile.cpp ./libMyLibrary.a You can put the library somewhere else. In the first case you'd change the -L. to -L/path/to/the/lib, in the second ./libMyLibrary.a to /p...
5,137,636
5,138,197
C++ cannot find stdafx.h
My program was working fine until I decided to rename one of the directories in where I have my projects. I tried changing the name back to the original but now it's giving me problems where it can't find .h files when their obviously still there in the project explorer. The first one it tells me is that it cannot find...
I gave up and just spent the last 30min copying an old version and replacing the old version with the newer code files. Visual Studio should have some type of feature to rescan your project to make sure the directories line up with the current directories.
5,137,637
5,137,736
Coming up with simple formula for linked list
I've been at this for days honestly. I've already implememnted the hard part of this function, but now theres just one small thing. The method I want to write is to remove every Nth block of blockSize of a linked list. So if I have a linked list of size 7 {1,2,3,4,5,6,7}, N=2, blockSize=2, I want to remove every Nth(2n...
Try floor(ceil(size/blockSize)/N) floor(ceil(7/2)/3) = 1 floor(ceil(7/2)/2) = 2 floor(ceil(8/2)/2) = 2 The number of blocks that you have: blocks = ceil(size/blockSize) ceil because you don't mind for not-full blocks. then you skip every N, so: floor(blocks/N) floor because you either count a block or you don't.
5,137,800
5,137,876
How to rename a resource in Visual Studio?
Okay, I've never done win32 programming before, and I have a question that seems fairly stupid.. How do I rename IDR_MENU1 to, for example, IDR_MAIN_MENU? I tried everything couldn't find a way.
You can modify the resource if you select your resource, example IDR_MENU1 in resource view. Activate the property palette (Ctrl +W, P) and you can then edit the IDR_MENU1 value.
5,137,919
5,137,955
C++ Pointer to Members
If I have two classes that are in the same hierarchy with a member of the same name and type, what is the "correct" way to create a member pointer to the base class's variable. Ex. class A { int x; A():x(1){} }; class B : public A { int x; B():x(2){} }; int main(int argc, char *argv[]) { B classB; ...
I believe all three are safe, although I can't cite chapter and verse from the standard on them. :) That said, I have run across one very specific bug in member function pointers on an older version of Visual Studio (I don't remember which, I'm afraid). Specifically, I had a structure like this: struct optable_entry { ...
5,137,981
5,230,821
A recursive parser help
I'm supposed to write this c++ that take in 01 and on. for example: 01010101 but not 0,1,10,011,110. Can someone help me figure out what I need to do to fix the problem. Sorry guys the code isn't working right.I pushed ctrl+k and posted the code but everything wasn't in place. What I was trying to do is that when some...
#include <iostream> //#include<stdlib.h> // for the exit(1) function using namespace std; char text[300]; char ToBeChecked; char lexical(); //identify the characters void SProd(); void BProd(); int main(){ cout<<"Enter some strings (max. 300 characters"<<endl; cin>>text; ToBeChecked = lexical(); //ide...
5,138,102
5,138,514
constructing a large multi dimesional vector array
Right now I have a vector std::vector<char> myVector(4) containing any combination of a set of char lets say {@,#,O,*,%,$,!} may be more or less but not many more than that, might not always be 4 members either, but will be constant for any instance one instance. now I stuck trying to create a data structure that can u...
Since the number of possible characters is limited to 8, you can use an enumeration instead. You'd therefore only need 3-bits to represent each "character". You can pack several of these 3-bit "characters" into a short integer using bitfields. The resulting packed integer becomes the index into your vector<SomeData>. T...
5,138,156
6,212,418
Access violation exception in 64bit MFC version
I am trying to port a 32bit application to 64 bit. The calculations appear to run correctly, but I cannot configure the views properly. I am using MFC, C++ and OpenGL, Intel 10.0.027 compiler inside VS2005 on a W7 x64 machine. When the crash happens, I get the following message: "First-chance exception at 0xffffffff804...
I have just fixed an issue with the same behavior. The bug was in passing parameters to SetWindowLongPtr( GWLP_WNDPROC ), pointer to WndProc was improperly casted to LONG instead of correct LONG_PTR. This way, bad pointer to WndProc was put into internal OS WND struct, so any following call to the HWND's WndProc crashe...
5,138,225
5,138,254
C++, reference "constructor"
template<typename T, typename R> T f(R &r) { return T(r); } int main() { int o; f<int&>(o); } Is this ok? Comeau didnt complain, so I assume int&(...) form is fine? reason example: typename boost::mpl::if_c< (rank == 1), reference, tensor_ref<typename detail::array_ref<A>::type> ...
This is fine, it acts like a cast from int& to int&, and returns int&, referring back to o. I'm not sure what purpose this would serve, though.
5,138,609
5,138,621
Why does main() require braces?
I tried several variations on main() return; or main() if(); and obtained different errors, the most peculiar of which was /usr/lib/gcc/i686-linux-gnu/4.4.5/../../../../lib/crt1.o: In function `_start': (.text+0x18): undefined reference to `main' collect2: ld returned 1 exit status While it's uncommon for a progra...
Because you are defining a function named main() and a function definition is basically a function declaration (the int main() part) followed by a compound statement (the { /* ... */ } part) (you could also use a function try block, but those are very rarely used and still require braces). You can't define any function...
5,138,629
5,138,645
Passing a list of derived classes to a function expecting a list of base classes in C++
I have the following classes class Parent { virtual void doStuff() = 0; }; class Child : public Parent { void doStuff() { // Some computation here } }; And I have a function with the following signature. void computeStuff(std::vector<boost::shared_ptr<Parent> >); Provided I can refactor my code (including ...
The "best" way would be to have the function take a pair of iterators: template <typename ForwardIterator> void computeStuff(ForwardIterator first, ForwardIterator last) { /* ... */ } You can call this function as: std::vector<boost::shared_ptr<Child> > listOfChilds = getList(); computeStuff(listOfChilds.begin(), ...
5,138,739
5,138,903
try catch duo in c++
I know that the general method for using the try catch duo is something like this: try { //your code } catch(...) { //any error goes here } Is there a way by which catch() catches the error code without giving any input... i.e if I didn't throw an exception but the c compiler did, then the error code can be anyt...
Apparently, you're trying to catch errors from functions that don't throw exceptions but return numerical error codes. That's impossible. The closest you can get is wrapping all your C functions in exception throwing code yourself: FILE *safe_fopen(char const *path, char const *mode) { FILE *f = std::fopen(path, mo...
5,138,892
5,139,218
new operator (Error :expected expression before struct)
struct node* NewNode(int data) { struct node* node = new(struct node); node->data = data; node->left = NULL; node->right = NULL; return(node); } I am getting this error in first line of the function. Cant figure out whats wrong? Thanks.
This code compiles perfectly fine under Comeau try-it-out: #define NULL 0 struct node { int data; struct node* left; struct node* right; }; struct node* NewNode(int data) { struct node* node = new(struct node); node->data = data; node->left = NULL; node->right = NULL; return(node); }
5,138,935
5,138,943
Explanation for assert macro
I couldn't comment on the answer itself, so: about Using comma to prevent the need for brace pair #define MY_ASSERT(expr) ((expr) || (debugbreak(), 0)) Here debugbreak() returns void, but we still wish to have 0 as an rvalue. How does (debugbreak(), 0) work to return 0? I understand that the return value of debugb...
Nothing will be evaluated if the assert fires, but both expressions must have the right return type, otherwise this macro will just break compilation.
5,139,036
5,139,041
How to use an stl container's size_type type when using templates?
I'm trying to use the size_type from std::list and I have the following list: std::list<T*> mylist; template <class T> T* at(std::list<T*>::size_type pos); But this doesn't work as I get a bunch of syntax errors.
template <class T> T* at(typename std::list<T*>::size_type pos); // ^^^^^^^^ See also this question.
5,139,142
5,139,347
system-wide hook for 64-bit operating systems
I want to perform a system-wide hook (using SetWindowHook) on a 64bit operating system. I know that 64bit processes (= proc64) can load only 64bit dlls (= dll64) and 32bit processes (= proc32) can load only 32bit dlls (= dll32). Currently I am planning to call SetWindowHook twice, once with dll32 and once with dll64, ...
Approach that you've described is correct and documented. From http://msdn.microsoft.com/en-us/library/ms644990(v=vs.85).aspx: SetWindowsHookEx can be used to inject a DLL into another process. A 32-bit DLL cannot be injected into a 64-bit process, and a 64-bit DLL cannot be injected into a 32-bit process. If ...
5,139,312
5,139,882
Check for all used OpenGL Extensions
I'm using GLEE in my application and everything works just fine on regular Windows. However, when running under virtualization my application does not work properly. Either it crashes or just renders black. This is probably due to some OpenGL extension missing. I have tried to identify all the used extensions and check...
Possible, but it will be a bit of work. GLEE offers lazy loading, so you should be able to trivially modify it to log each function that is called. The lazy loading code (I have not looked at it, admittedly, but it is probably something similar) probably looks something like:if(funcptr == 0) { _ _ glee_load_fp(funcptr,...
5,139,494
5,139,566
C++: non-native types promotion
Let's suppose I've got a 2D vector template class: template<typename T> class Vec2 { T x, y; // ... }; I'd expect that the result of a sum between a Vec2<double> and a Vec2<int> would be a Vec2<double>, but C++ won't do this by default. Am I thinking in the wrong way? Should I try and implement this behavior? ...
I do like this: template<class V, class W> struct vector_add; template<typename T, typename U, size_t N> struct vector_add<Vec<T,N>, Vec<U,N> > { typedef BOOST_TYPEOF_TPL(T()+U()) value_type; typedef Vec<value_type, N> type; }; http://www.boost.org/doc/libs/1_43_0/doc/html/typeof/refe.html#typeof.typo also:...
5,139,707
5,139,732
Nested class initialization list question
//header file class Foo { public: struct FooBar { bool ok; string msg; }; }; // .cpp file Foo::FooBar::FooBar():ok(false), msg("hello") {} When attempting to compile, I get: error: definition of implicitly-declared ‘Foo::FooBar::FooBar()’ Silly, simple scope related mistake I'm sure, but I can't ...
You're trying to implement a constructor that you didn't declare. Declare it like this: //header file class Foo { public: struct FooBar { FooBar(); bool ok; string msg; }; }; // .cpp file Foo::FooBar::FooBar():ok(false), msg("hello") {}
5,139,808
5,140,443
TCP simultaneous open and self connect prevention
TCP standard has "simultaneous open" feature. The implication of the feature, client trying to connect to local port, when the port is from ephemeral range, can occasionally connect to itself (see here). So client think it's connected to server, while it actually connected to itself. From other side, server can not op...
For server you need to bind() socket to port. Once addr:port pair had socket bound, it will no longer be used for implicit binding in connect(). No problem, no trouble.
5,139,834
5,139,850
Is it legal to use char overflow in C++ code
Good day, colleagues! I need to obtain cyclic series on successive numbers from 0 to 255. Is it legal to use unsigned char overflow like this: unsigned char test_char = 0; while (true) { std::cout << test_char++ << " "; } Or will be more safely to use this code: int test_int = 0; while (true) { std::cout << ...
Even though sizeof(char) will always be 1, it is not necessary that a char will be exactly 8 bits. (I am guessing unsigned char will be similar). So of the two, if given a choice, I would prefer the latter as the former might not even be correct. btw, You probably intended unsigned int instead of int for the latter? Mo...
5,139,859
5,139,888
what the difference between map and hashmap in STL
in C++ STL, there are two map, map and hashmap. Anyone know the main difference of them?
map uses a red-black tree as the data structure, so the elements you put in there are sorted, and insert/delete is O(log(n)). The elements need to implement at least operator<. hashmap uses a hash, so elements are unsorted, insert/delete is O(1). Elements need to implement at least operator== and you need a hash functi...
5,139,910
5,139,954
C# equivalent of (reading a variable as a different type)
I have been converting some part of my application from C++ to C#. There's this encoding/decoding part which I need to read a variable as a float which is defined as uint: uint result = 0; ... // a value is set to result return (*((float *)&result)); // get result as a float value Anyway to convert last line to C#? ...
You can do that with unsafe code - or you could use BitConverter.GetBytes() to convert the value into a byte array, and then BitConverter.ToSingle() to convert back. That's less efficient, obviously, but will work if you're in a situation where you can't use unsafe code. EDIT: There's another alternative that I've used...
5,139,975
5,140,011
std::sort problem on solaris (libCstd)
I have a problem on Solaris using the Sun Studio compiler, which is most likely due to the strange STL implementation (libCstd) used, see http://developers.sun.com/solaris/articles/cmp_stlport_libCstd.html. Consider this: std::vector<C*> v; // .. populate the vector std::sort(v.begin(), v.end()); where C is some class...
Looks like your actual vector is const. Is it a member variable accessed in a const member function? Is it a const function argument?
5,140,076
5,140,686
STDERR in a c++ program
I have a c++ program that ssh's into a server and runs some commands. If the ssh fails, the error is printed on the screen and the program doesnt know about that.. and it returns a blank list of output. How do i know that ssh has failed? is there a way to redirect STDERR to something other than a FD?
I don't know the way you actually do the ssh. If you system(), then I may suggest you to use popen(). It will allow you to retrieve the output of the program. You'll be able to read it from a file descriptor, instead of it being displayed. Then, you can append a redirection to you command so that stderr is redirected t...
5,140,239
5,140,292
C++ STL Map - find(pair<string,bool>) works in windows Visual Studio but not with g++ in Linux!
I seem to be having issues with using find() with the STL map on different platforms. Here is my code to be complete: #include <stdio.h> #include <stdlib.h> #include <iostream> #include <fstream> #include <string> #include <map> using namespace std; void constructDictionary(map<string,bool> &dict); bool isInDictiona...
Is the error in getline and line-endings in your input file? You might find on Linux it is adding an extra \r to each word. Assuming none of your words contain spaces, you can get around this by simply using: std::string word; while( wordListFile >> word ) { if( !word.empty() ) { // do the insert } } Y...
5,140,312
5,150,435
Is Boost IPC any good?
My default choice for cross-platform IPC would be boost, but I saw it criticised in two different forums when I asked about it and this concerned me. Perhaps this was simply a coincidence, so what are the thoughts on boost IPC and choosing a cross-platform C++ IPC library in general? For Windows dev we're using VC++ 20...
From my limited experience with Boost.Interprocess, I didn't have any major problems but I can't really comment on performance. While it's true that it does use files created outside of your program's folder to do its stuff, they should all be memory mapped which negates most of the performance problems. In any case, w...
5,140,576
5,140,644
How to Read from Registry "Name" using VC++?
I want to Read from Registry the Name.how i can do this using VC++ ? Ex : I have one folder called ABC in Registry under that i have 3 enteries Name , Type, Data. Now i want to read all Name one by one Name Type Data V:\ REG_SZ \\124.158.14.74\CIFS J:\ REG_SZ \\124.158.14.74\CIFS In m...
I think RegEnumValue is the API you are looking for.
5,140,651
5,219,489
Enable C++ compiler warning for missing XML documentation
When XML documentation is enabled for my C++ projects (managed) the compiler does not raise any warnings for missing comments. I have enabled the documentation generation by setting "Generate XML documentation Files" (/doc) to true as described here. The project is configured as a dynamic library with /clr and warning ...
The VC++ XML comments are not processed the say way as for .NET. The VC++ compiler processes the comments and generates .xdc files which are later assembled by a tool called xdcmake.exe into xml files. However, there is no option to tell the compiler to issue warnings if XML comments as known to .NET are missing. (See ...
5,140,871
5,140,942
sprintf for unsigned _int64
I am having following code. output of second %d in sprintf is always shown as zero. I think i am specifying wrong specifiers. Can any one help me in getting write string with right values. And this has to achieved in posix standard. Thanks for inputs void main() { unsigned _int64 dbFileSize = 99; unsigned _int6...
I don't know what POSIX has to say about this, but this is nicely handled by core C99: #include <stdio.h> #include <inttypes.h> int main(void) { uint64_t dbFileSize = 99; uint64_t fileSize = 100; char buf[128]; memset(buf, 0x00, 128); sprintf( buf, "\nOD DB File Size = %" PRIu64 " bytes \t" ...
5,140,893
5,141,575
Struct defined differently for C and C++ - is it safe? PC-Lint warns
The following declaration adds a couple of operators for compilation in a C++ file. The definition is included in both C and C++ files. PC-Lint is reporting Error 114: Inconsistent structure declaration for tag 'Rect' but I am certain it is safe. I'm compiling with Visual Studio 2008. edit - adding the explanation I ...
Am I correct to assume that the header file containing this definition is included in several translation units, some of which are compiled as C++, and some -- as plain C? If it is true, then you have an ODR violation, which, according to the C++ standard, invokes undefined behavior. There are two ways to deal with it....
5,141,068
5,141,161
Weird characters appear after writing to a textfile
I am currently trying to read a file, put extra backward slash () if it finds a backward slash, and write it to another file. The problem is, there are weird characters being printed inside the path.txt. I suspect that, the space characters from the file logdata is the root of this problem. Need advice how to solve thi...
Every char string in C has to end with character \0. It is an indicator that the string ends right there. Your newPath array, after iterating through your for-loop is not correctly ended. It probably ends somewhere later, where \0 appears by accident in memory. Try doing the following right after exiting the for-loop: ...
5,141,312
5,143,403
Get last match with Boost::Regex
I have a regular expression in C++ with Boost which matches lines in multi-line strings. Regex search finds the first match, however I'm interested in the last line which matches. The code I'm using now is something like this: matched = boost::regex_search(input, results, regex); if (!matched) { retu...
operator[] of match_results returns a sub_match. sub_match inherits std::pair of iterators. Its first and second members correspond to matched range. So, you can use its second for start point of new search. For example: string input = "Data1 Data2 Data3"; regex re("(?<Group>Data.)"); string::const_iterator begin = ...
5,141,402
5,141,727
location of variables on the stack w/o using (&)
I'm trying to determine a way to test the location of variables on the stack (without doing it the common sense way). int main() { int i,j; return 0; } there's really no difference between stating int i; intj; and int i,j; I can tell by simply cout'ing the addresses. i goes on the stack, then ...
So you want to find the addresses of local variables without using the C operator designed specifically to find the address of a variable. Why? It's worth pointing out that, in any modern compiler/processor combination, the i and j in your example may not be on the stack if you don't use the & operator. Even if you d...
5,141,482
5,141,890
Visual Studio C++: Refactoring between member and non-member functions
I have a library, and I need to refactor a class X such that every call of the form: f(x); //Non-member function is subsituted with: x.f(); //Member function where f is a fixed method (same name in all the code) but x is an instance of type X, and as such will change. Is there an wasy way to do a globl find and repl...
Find and Replace, using regular expressions and tagged groups. Then you can replace f\({:i}\) with \1.f() and f\(\*{:i}\) with \1->f()
5,141,485
5,141,500
Threaded Program to compute Fibonacci numbers
I'm trying to write a program in C++ to compute the Fibonacci series. I create a thread that does the calculation and output. But nothing in my for loop seems to get executed. Can anyone have a look at my code and tell me what I might be doing wrong? #include <iostream> #include <Windows.h> #include <stdio.h> #include ...
You're passing the address of a double to CreateThread, then you try to treat it as an int * in the thread func. Change double x; to int x;
5,141,700
5,141,741
Convert TCHAR to LPWSTR in VC++?
How to Convert TCHAR to LPWSTR in VC++ ? Ex: I have TCHAR achValue[16383]; I want assign this value to LPWSTR . How to achieve that in VC++ Any help is appreciated.
TCHAR is either char or wchar_t based on your projects Unicode/MBCS setting. If you're compiling as unicode, achValue can be used as a LPWSTR. If not, you need to use MultiByteToWideChar in order to convert the characters in achValue from the encoding you use to UTF-16.
5,141,886
5,142,226
Profiling with GCC: Get Call Count of Functions in a Shared Library
I would like to be able to count how many times a function is called in a library. I have the C++ source of the library available, but I don't have the source of the executable that uses it. Gprof seams to be a popular tool but it works only for executables. I have found very limited info on sprof, which is supposed to...
GCC, in recent versions, has a compiler switch -finstrument-functions which can be used to have it autogenerate tracepoint hooks within compiled code. See GCC Code Generation Options in the manual. With that, you don't even need a full-blown interceptor, only a tiny pair of functions: __cyg_profile_func_enter() __cyg_...
5,141,970
5,142,005
pipes vs tmfiles. What is better and why?
I want write program which creates child process and redirecting its stdout and stderr streams to parent. So what is good choice to do this for good performance tmpfile() or pipe(), and why?
Use pipe where possible, unless you expect large amounts of input to build up in the stream without being read. A pipe keeps data in RAM where a temporary file requires filesystem operations. An fdsync on a file will be much more expensive than on a pipe. A pipe is also less vulnerable to security issues caused by r...
5,142,069
5,143,928
What is the standard way to get the state of a C++0x random number generator?
I am trying to learn the new C++0x approach to random number generators (26.5), and implement at C++0x-compliant random number engine (26.5.1.4). The standard goes into detail on the required interface for seed sequences, and how they can be passed to the constructor or seed functions of engines. However, I cannot find...
There is no API for generating a seed or seed sequence from an engine's state. However the engine's state can be streamed into an istream, and extracted from an ostream. And the engine's state is EqualityComparable to another engine's state (for same-type engines). One might inspect the istream generated by streaming...
5,142,366
5,142,442
How fast is D compared to C++?
I like some features of D, but would be interested if they come with a runtime penalty? To compare, I implemented a simple program that computes scalar products of many short vectors both in C++ and in D. The result is surprising: D: 18.9 s [see below for final runtime] C++: 3.8 s Is C++ really almost five time...
To enable all optimizations and disable all safety checks, compile your D program with the following DMD flags: -O -inline -release -noboundscheck EDIT: I've tried your programs with g++, dmd and gdc. dmd does lag behind, but gdc achieves performance very close to g++. The commandline I used was gdmd -O -release -inli...
5,142,698
5,144,347
Is it possible to build a self-contained library with gcc (i.e., one which statically incorporates its dependencies)?
I'm trying to build a library with gcc (actually, MinGW) which depends on stdlibc++. I want to build mylib such that all of its dependencies get incorporated into it, so that anyone linking with mylib doesn't need to link against stdlibc++ (or, if they do, it's because their own code depends on stdlibc++). Can this be ...
Use ar -x to extract the .o files you need from the original library (libstdc++, in your case). Include those .o files with your own when you link your library. Make sure the distribution terms of the original library are compatible with those of your own.
5,143,313
5,144,070
Extra method in template specialization
I'm trying to write an templated class with some methods/operators etc.. Now when the class is of an specififc type i would like to have extra append methods specially suited for that type which arent there for any other type. I dont' want to copy all the code into an new class. Example: template<typename T> class Buff...
Use a policy class to manage the interaction with the type, then your class doesn't really have to worry about the type that is passed in, an appropriate policy (and specialization of said policy) can contain all the logic specific to that type. #include <iostream> #include <vector> template <typename T, typename U> s...
5,143,388
5,144,499
Why do images appear at incorrect positions in my QGraphicsView-derived class?
I have created an override of QGraphicsView for displaying images inside a QMdiSubWindow in my application. Later I plan to add support for other floating shapes on top of that so a QLabel just wasn't enough. Here's the basic layout of the class: class ImageView : public QGraphicsView { public: ImageView(QWidget *p...
The reason the image is showing with its top-left corner at the center of the view is because your scene has a sceneRect of (0,0,0,0) and QGraphicsView shows the scene centered by default. Set seneRect to a fix rect will probably solve your problem. Calling centerOn after the image change will also help.
5,143,673
5,143,992
Linking Error While using liboauth . Getting Error undefined reference to `oauth_url_escape'
I am getting linking error when I am using liboauth code id #include <cstdlib> #include<oauth.h> using namespace std; /* * */ int main(int argc, char** argv) { oauth_url_escape("vivek"); return 0; } Makefile is auto generated by Netbeans which is MKDIR=mkdir CP=c...
We just need to change include statement in C++ code extern "C" { #include <oauth.h> }
5,143,693
5,183,428
Qt xml file issues with content above root node
I'm having a difficult time with Qt DOM and the DTD of an XML file. Let's say that we have an xml file like the one bellow. The DTD is embedded into the file. <?xml version="1.0" encoding="utf-8"?> <!DOCTYPE notes [ <!ELEMENT (note+)> <!ELEMENT note (to,from,heading,message)> <!ELEMENT to (#PCDATA)> <!EL...
OK, I think the answer to my question is that Qt is not capable of dealing with an internal DTD. It should be... but it seems it is not.
5,144,329
5,144,395
Can I get a "__try"-clause to compile with /EHsc?
The Microsoft-approved way of setting a thread name doesn't compile with /EHsc enabled. The compiler tells me C2712: Cannot use __try in functions that require object unwinding http://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx // // Usage: SetThreadName (-1, "MainThread"); // typedef struct tagTHREADNAME_INFO { ...
The usual solution is to separate it into two functions, one calling the other. One sets up the SEH __try/__except block and the other has all the stuff related to C++ exceptions and destructor calls for local variables. But I don't see any types that need a destructor call. Maybe it's just a typo (except) vs (__excep...
5,144,380
5,144,431
Converting to binary in C++
I made a function that converts numbers to binary. For some reason it's not working. It gives the wrong output. The output is in binary format, but it always gives the wrong result for binary numbers that end with a zero(at least that's what I noticed..) unsigned long long to_binary(unsigned long long x) { int rem;...
You're reversing the bits. You cannot use the remains of x as an indicator when to terminate the loop. Consider e.g. 4. After first loop iteration: rem == 0 converted == 0 x == 2 After second loop iteration: rem == 0 converted == 0 x == 1 And then you set converted to 1. Try: int i = sizeof(x) * 8; // i is now nu...
5,144,444
5,144,509
C++ Why isn't the second expression valid?
Suppose you have the following object hierarchy: class Vehicle { public: virtual ~Vehicle() {} }; class LandCraft: public Vehicle {}; class Truck: public LandCraft {}; Now, we have the two expressions: Truck truck; Vehicle& vehicle = truck; According to a solution to a homework, the second expression is not valid. ...
It sounds like the homework solution is incorrect then. There is nothing wrong with initializing a reference to a base type from an instance of a derived. EDIT As several people have pointed out (Slaks in particular) while there is nothing wrong with this statement in itself, it does provide the potential for future...
5,144,545
5,144,575
Is this C++ in an Objective-C code file?
I am going over a sample project from Apple called Mixer Host. In the callback function there are a few lines which use the "->" syntax to refer to mBuffers which is a struct. I thought this was C++ syntax but this file has a .m extension which I thought was C plus Objective-C extensions. Is this actually C++ syntax? C...
No, that's perfectly valid C. It's how you refer to data members via a pointer in both C and C++. In C++ you can also refer to member functions that way, but there's no function call in sight.
5,144,589
5,144,683
How to detect at runtime whether symbols are stripped?
In my C++ program, how can I detect programmatically at runtime whether symbols have been stripped via the 'strip' gnu development tool on Linux? I'd like a function definition which returns true if stripped, otherwise false. Would using dlsym() on "main()" work to detect this reliably?
I know the file command can tell the difference, so you could possibly look at its source to see what mechanism it uses.
5,144,623
5,145,010
Google Mock: Return() a list of values
Via Google Mock's Return() you can return what value will be returned once a mocked function is called. However, if a certain function is expected to be called many times, and each time you would like it to return a different predefined value. For example: EXPECT_CALL(mocked_object, aCertainFunction (_,_)) .Times(2...
Use sequences: using ::testing::Sequence; Sequence s1; for (int i=1; i<=20; i++) { EXPECT_CALL(mocked_object, aCertainFunction (_,_)) .InSequence(s1) .WillOnce(Return(i)); }
5,144,678
5,144,711
What is an "orthogonal linked list"?
I understand what a linked list is, but my question is what is an orthogonal linked list? I searched on the web but couldn't find any helpful information. I am studying liked list in C++, if there any good books related to linked lists, please mention them.
This is not a very common term, but, according to the Dictionary of Computing, it is a multi-dimensional linked list whose elements hold pointers to neighbors in each dimension. Take a simple matrix: 1 2 3 4 5 6 7 8 9 Then,the element 5 would have a pointer to 4 and 6, but also to 2 and 8. And the following questions...
5,144,794
5,144,867
What does stream mean? What are its characteristics?
C++ and C# both use the word stream to name many classes. C++: iostream, istream, ostream, stringstream, ostream_iterator, istream_iterator... C#: Stream, FileStream,MemoryStream, BufferedStream... So it made me curious to know, what does stream mean? What are the characteristics of a stream? When can I use this ter...
Many data-structures (lists, collections, etc) act as containers - they hold a set of objects. But not a stream; if a list is a bucket, then a stream is a hose. You can pull data from a stream, or push data into a stream - but normally only once and only in one direction (there are exceptions of course). For example, T...
5,144,999
5,146,566
Exe file icon change. Icon taken from SHELL32.dll
I need to change some exe files icon using my program. I've found some info and sample codes in MSDN and websites but i'm still in same place. I need to extract icon from SHELL32.dll uInt = ExtractIconEx("%SystemRoot%\\system32\\SHELL32.dll" , -63008, &hIcon, NULL, 1); Then update some exe file resources. But here my...
You can't use a HICON in this case, a HICON is a single image in a specific size and color depth, but a "real" icon resource is usually a collection of images (16x16, 32x32 etc) Don't use ExtractIconEx, switch to LoadLibraryEx (and use one of the load as data file flags) and then use FindResource[Ex] to find the icon ...
5,145,558
5,239,326
Adding control symbols to a byte stream
Problem: sometimes we have to interleave multiple streams into one, in which case its necessary to provide a way to identify block boundaries within a stream. What kind of format would be good for such a task? (All processing has to be purely sequential and i/o operations are blockwise and aligned.) From decoding sid...
So I ended up using the ugly parser from OP in my actual project ( http://encode.ru/threads/1231-lzma-recompressor ) But now it seems that the actual answer is to let data type handlers to terminate their streams however they want, which means that escape coding in case of uncompressed data, but when some kind of entro...
5,145,634
5,145,670
C++ Segmentation when using erase on std::list
I'm trying to remove items from a C++ linked list using erase and a list iterator: #include <iostream> #include <string> #include <list> class Item { public: Item() {} ~Item() {} }; typedef std::list<Item> list_item_t; int main(int argc, const char *argv[]) { // create a list and add items list_item_...
The core problem here is you're using at iterator value, it, after you've called erase on it. The erase method invalidates the iterator and hence continuing to use it results in bad behavior. Instead you want to use the return of erase to get the next valid iterator after the erased value. it = newList.begin(); for...
5,145,792
5,146,007
In C++, I thought you could do "string times 2" = stringstring?
I'm trying to figure out how to print a string several times. I'm getting errors. I just tried the line: cout<<"This is a string. "*2; I expected the output: "This is a string. This is a string.", but I didn't get that. Is there anything wrong with this line? If not, here's the entire program: #include <iostream...
Well, ideally, you would use a loop to do that in C++. Check for/while/do-while methods. #include <iostream> #include <string> using namespace std; int main() { int count; for (count = 0; count < 5; count++) { //repeating this 5 times cout << "This is a string. "; } ...
5,146,044
5,156,255
QCompleter for QTableWidgetItem to autocompelte
I have a QTableWidget has a QTableWidgetItem that contains a code a user will supply. This code is known to the database and is suppose to autosuggest to the user as he types. How do I connect a QCompleter to a QTableWidgetItem. I know how to do it with a QLineEdit, but I have not found an example with a QTableWidgetIt...
I managed to come up with a solution, though not exactly by using a QTableWidgetItem, basically I placed a QLineEdit in the cell instead and attached the QCompleter to that.
5,146,073
5,146,094
g++ linker order question
I am trying to figure out something that is causing an error when trying to compile code in Qt Creator, that is linking in my externally built libraries. It is complaining about an "undefined reference to myclass::myclass(args)" constructor. However, this class has been built, and the object file was included in an arc...
You may need to make sure that on the linker command line CSV.a is followed by common.a, not the other way around.
5,146,314
5,146,338
Multiple class names inside single .hpp file
I'm just beginning with C++, so I'm looking some code to learn. I found this code fragment in a Breakout game. #pragma once #include "force.hpp" #include "brick.hpp" #include <vector> class Painter; class Ball; class Wall { public: enum { ROWS_COUNT = 16, COLS_COUNT...
Those are forward declarations, which can be used to say that a name exists, but no definition of it exists at this time yet, but I want to use the name. Note that in the class, it only uses pointers and references to Painter and Ball. When using forward declarations, this is completely fine, but if you put in code tha...
5,146,427
5,146,564
How do I add sqlite3 to my project
How do I statically link the sqlite3 libary to my C++ program? I am using the G++ compiler.
in Unix/Linux you'll have to make sure the library (e.g. libsqlite3.a) is in your LD_LIBRARY_PATH and then you add "-lsqlite3 -static" to the g++ option.
5,146,712
5,146,739
Initialize C++ struct
struct CUSTIOMSTRUCT { FLOAT x, y, z; DWORD color; }; CUSTOMSTRUCT MyVertex = {320.0f, 50.0f, 1.0f, 0xFF00FFCC}; I don't understand that part: {320.0f, 50.0f, 1.0f, 0xFF00FFCC}; I have to put them in order? Sorry but I'm C# guy.
Yes, you have to put them in order. C99 version of C language offers "tagged" aggregate initializers, which allows one to "put them" out of order, but it is not in C++ (yet?).
5,147,008
5,147,289
Simple pointer question (Sharing a vector between different classes)
I have a class AudioDeviceManager that passes a std::vector by reference to an AudioAnalyzer class. I want other objects to be able to access this vector (that is passed to the AudioAnalyzer class). To do this, I created a pointer in the AudioAnalyzer class: std::vector<float> *pointer; I created a getter for it usin...
You can't just pass (by reference) the same instance of the same std::vector to the constructors of all classes that need it?
5,147,337
5,147,416
Writing multiple variable types to a text file using ofstream
I just want to write a simple text file: ofstream test; test.clear(); test.open("test.txt",ios::out); float var = 132.26; BYTE var2[2]; var2[0] = 45; var2[1] = 55; test << var << (BYTE)var2[0] << (BYTE)var2[1]; test.close(); But in the output file I get: 132.26-7 I don't get what the problem is...
BYTE is nothing but an alias for unsigned char. By default, when you output a char in a stream, it is converted to its ASCII character. In the ASCII table, the character 45 is '-' and the character 55 is '7'. Try this instead: test << var << (int)var2[0] << (int)var2[1];
5,147,490
5,147,532
Problem when compiling C++ code with Xcode
I was trying to compile some C++ code in Xcode and I got this error: Undefined symbols: "Editorial::sm_nTotalEditorials", referenced from: Editorial::AskTotal() in editorial.o Editorial::~Editorial()in editorial.o Editorial::~Editorial()in editorial.o The list follows with two more entries for ...
In C++, creating a static data member for a class is a two-step process. First, you have to declare the variable, which you've done here. However, you also have to define it somewhere so that the compiler knows where to put the storage space for the variable. Typically, this is done in the .cpp file for the class. ...
5,147,492
5,159,293
Member function call in decltype
The following code: struct A { int f(int); auto g(int x) -> decltype(f(x)); }; Fails to compile with the error: error: cannot call member function 'int B::f(int)' without object If I change it to: struct A { int f(int); auto g(int x) -> decltype(this->f(x)); }; I get another error: error: invalid use...
Currently you can only access 'this' and members of the class inside the function body, but this is likely to be changed soon: http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1207
5,147,506
5,147,529
typedef struct and enum, why?
Possible Duplicates: Purpose of struct, typedef struct, in C++ typedef struct vs struct definitions In code that I am maintaining I often see the following: typedef enum { blah, blah } Foo; typedef struct { blah blah } Bar; Instead of: enum Foo { blah, blah }; struct Bar { blah blah }; I always use the latter, and...
In C++ this doesn't matter. In C, structs, enums, and unions were in a different "namespace", meaning that their names could conflict with variable names. If you say struct S { }; So you could say something like struct S S; and that would mean that struct S is the data type, and S is the variable name. You couldn't s...
5,147,672
5,147,809
C++: reading data from an external file; problem with my code for stopping read before end of file
To use code I have written for performing calculations, I need to read in data (numbers and strings) from an external text file and store them in vectors of either strings or ints/doubles. I have written a template function for doing this. CashCow, Howard Hinnant, and wilhelmtell kindly helped with a previous problem....
Looks to me like you may have a problem mixing getline and get. When you've read the name of the vector you want, you start reading the parts between single quotes. Once you've read whatever is between single quotes, you check to see if the next character is an end of line. If there's anything else on the line before...
5,147,759
5,147,823
solaris 8 vs solaris 10
I have a program that i compiled and ran using third party lib on solaris 8. after it ran successfully I ported it to solaris 10 without issues. Do i really need to compile/link and create a new exe on solaris 10? despite me testing the executable I made on solaris 8? Seems weird that I would need to. can someone shed ...
Sun makes a binary compatibility guarantee that anything built to run on Solaris 8 or Solaris 9 will work on Solaris 10. When I worked in the Solaris world, I would link my code built in Solaris 10 with libraries built for Solaris 8 (binaries from 3rd party vendors, so I couldn't have recompiled if I wanted). This is a...
5,147,835
5,147,932
Override Methods in C/C++ like Delphi
In Delphi we have an option to do a thing like this: TClass1 = class procedure Test; virtual; end; TClass2 = class(TClass1) procedure Test; override; end; So in code, If I create an instance of TClass2, even if I cast the object like: TClass1(ObjectClass2).Test; The application will call the function declared on...
I'm not a Delphi expert, but I can explain how this stuff behaves in C++. So in C++, you can have a class that defines a virtual function, which means that if you use a base class pointer/reference to an object, that function can be invoked via dynamic dispatch (i.e. runtime function lookup). #include <iostream> class...
5,148,048
5,149,381
GL_LIGHT only creating one light source
Currently I am trying to illuminate an object with a light source and change the color of the object based on GL_COLOR_MATERIAL. For some reason, I am only able to see ONE light source being projected on to the model. I've tried various different positions and combination of light sources and I have noticed only GL_LIG...
There are several parameters (eg GL_DIFFUSE) which default to 0,0,0,0 for GL_LIGHT1 .. GL_LIGHT7 but something else (eg 1,1,1,1) for GL_LIGHT0. I don't know which one you've missed, but I bet you're relying on a default for both lights and it's "off" for GL_LIGHT1.
5,148,158
5,148,182
Passing a filename through a command-line argument vs. using a string literal in-code
The following bit of code seems to interpret the slash in the passed filename differently, depending on whether it was passed as a command line argument, or hardcoded by means of a literal. If the image filename C:\kimba.jpg is passed in as a command line argument, it works fine: int main( int argc, char** argv ) { ...
You need to escape the backslash with a backslash: IplImage* img = cvLoadImage("C:\\kimba.jpg", 1);
5,148,358
5,155,548
Error using boost::signals2::signal as handler
In the following code: boost::signals2::signal<void(const boost::system::error_code&)> signal; socket.async_connect(endpoint, boost::ref(signal)); (Found at http://liveworkspace.org/code/e04910cbcc4cfd9e42e34d1af55c393e) I get this error: In file included from boost/asio/detail/wrapped_handler.hpp:18:0, from ...
Looks like your signature is wrong? You need to specify a placeholder for the error_code Try boost::signals2::signal<void(const boost::system::error_code&)> signal; socket.async_connect(endpoint, boost::bind(boost::ref(signal), _1));
5,148,458
5,148,535
C++ issue concerning inheritance and casting
I am currently working on an amateur physic engine for a school project but I'm stuck because of a C++ issue. The setting is the following : I have three different classes : RigidBody (abstract) Sphere (inherits from RigidBody) CustomRigidBody (inherits from RigidBody and represents a polyhedra) I need to check if a ...
This problem is solved by Double Dispatch. Essentially, you need to add another overload to RigidBody and its derived classes: bool isCollidingWith(RigidBody* rb_p) = 0; In the derived classes, e.g. Sphere, the implementation would look like: bool Sphere::isCollidingWith(RigidBody* rb_p) { return rb_p->isCollidin...
5,148,653
5,148,803
Bit operations (C++)
Recently I had a question on the interview - I was asked to compare bitwise operations in performance terms. Like, give a brief description of the performance of different bit operations. I guess this question could is pretty general and pretty machine-specific, but I also think there should be some general rules abo...
I would imagine they mean comparing bit operations to arithmetic equivalents. For example, "is a = (a>>1) faster than a = (a / 2)?" In many cases, simple operations like this will (for various reasons including software and hardware optimisations, pipelining, caching, etc) effectively take 1 CPU cycle, so on modern pro...
5,148,656
5,148,693
How can we call "delete this; " in a const-member function?
I saw the code snippet as follows: class UPNumber { public: UPNumber(); UPNumber(int initValue); ... // pseudo-destructor (a const member function, because // even const objects may be destroyed) void destroy() const { delete this; } // why this line is correct??? ... private: ~UPNumber(); }; First,...
The const qualifier applied to a method have the effect of making the this passed to it a const pointer; in particular, in your case it will be a const UPNumber *. Still, this is not a problem for delete: actually you can use delete on a const pointer without having to cast anything, as specified at §5.3.5 ¶2: [Note: ...
5,148,706
5,148,751
Copying a Polymorphic object in C++
I have base-class Base from which is derived Derived1, Derived2 and Derived3. I have constructed an instance for one of the the derived classes which I store as Base* a. I now need to make a deep copy of the object which I will store as Base* b. As far as I know, the normal way of copying a class is to use copy constr...
This is still how we do stuff in C++ for polymorphic classes, but you don't need to do the explicit copy of members if you create a copy constructor (possibly implicit or private) for your objects. class Base { public: virtual Base* Clone() = 0; }; class Derivedn : public Base { public: //This is OK, its called co...
5,148,734
5,148,783
C++: Get char after space character instead or return carriage
Okay this is similar to my last question but what I ended up doing was way too complex for something as simple as this. I simply need to get a single character or number (I will know which of these I am receiving) from the console after I press space, instead of pressing enter. I'm sure there must be a way to have th...
Just issue multiple calls to getchar() (or getch()) in a loop and check the input every iteration. Something like this (untested but should work): int loop = 1 int spacehit = 0 char last_c = 0; while(loop) { char c = getchar(); switch(c) { case ' ': spacehit = 1; printf("hit ...
5,148,755
5,148,857
Array Path Combinations
I'm not sure how to title the question I have so I can't be certain this hasn't been answered before. That said, following is a description of my programming question. I have a class R containing 2 integer elements, say X and Y. I then have two 24 element arrays named A and B where each element contains an instance of ...
I think you came close to an answer in your own question. Make an array listing all the indices which you must try A or B. L={7,15,19} in the example. n=3. Then you'll loop from 0 to 2^n-1 inclusive. In each iteration of the loop, you'll test each bit b=0, bit 1, ... all the way to bit n-1. L[b] tells you which index y...
5,148,962
5,210,580
Phonon::MediaSource, cannot use resource as media source
with QT 4.6, I am trying to access a wav file in my QResource file to use as the media source of a media player and it does not work: Phonon::MediaObject *music; music=Phonon::createPlayer(Phonon::MusicCategory,Phonon::MediaSource(:/FPS_sounds/arming.wav)); music->play(); If I put the direct path it works. I have...
This one gave me a good scratch as well. But lo and behold, it can be implemented easily using a temporary file: { QTemporaryFile f; f.open(); QResource res(":/badger"); f.write((char*)res.data(),res.size()); f.flush(); f.setAutoRemove(true); f.close(); ...
5,149,044
5,149,227
Is it possible to modify the origin of a display? (win32)
I have a number of applications which I cannot modify(no source), they are hard coded to draw at 0,0. Normally this is not a problem however a new project(kiosk) has come along where I need to draw a boarder around the outside of these applications. I am looking for a way to change display range from: X: 0 to 1200 Y: 0...
This might be overkill, but if it's something you really want to have complete control over, you could always use API hooking to intercept the Window creation by hooking CreateWindow, CreateWindowEx in the target process and altering the X Y coordinates before passing control back to the system. Popular API hooking lib...
5,149,119
5,149,223
Template Arguments Needed in Return Types during Method Definition
Does anyone know why template arguments are needed for return-types but not for argument-types when defining template-methods? An example: template<typename T> struct Car { Car drive(Car); // will be defined after the template declaration. }; // Attempt #1: does not compile. // Error: use of class template Car req...
This is because argument(s) type(s) of a method are deduced using class scope, but return type is deduced from the same scope where a class is defined if those methods are defined outside class scope. This is true for everything, not only templates. To add to your example, the following won't compile: class Foo { t...
5,149,430
5,149,579
in C++, how do you code a class ADT--like std::vector or std::stack--that takes a data type in <> as argument and constructs the object accordingly?
Ie. I want to code a class ADT that can be used like this: myADT <type> objectA; in the same way that someone would use a vector like: vector <type> aVector; I'm guessing maybe it has something to do with templates and overloading the <> operator, but how do I get it to take a data type as an argument?
Let's say you have a class that implements your ADT using a hard-coded typedef T: class ADT { public: typedef int T; ADT(); T& operator[](size_t index); const T& operator[](size_t index) const; size_t size() const; ... private: T* p_; size_t size_; }; (You have to work out the inte...
5,149,447
5,158,944
PION : crash in HTTPRequest send
I am writing an application that uses pion library and notice a crash when I try to send a request. The crash is happening due to segmentation fault. This is in Linux and I am linking with PION_FULL. Code: pion::net::HTTPRequest httpRequest("/sm_login/trusted.asp?app-id=test"); int port = 80; httpRequest.setMethod("GE...
The problem was due to mismatch in cross compiler version used to build pion libs. The application is not crashing anymore.
5,149,513
5,149,686
How to make a dialog movable?
I'm starting out with win32 programming. I created my first dialog but I can't drag it around with my mouse; it simply stays where it is. Why? This is its proc function: static bool CALLBACK ChangeColumnProc(HWND dialog, uint32 message, WPARAM wParam, LPARAM lParam) { static ColumnInfo *column = NULL; switch(m...
The return type of the dialog procedure is INT_PTR, not bool. Return (INT_PTR)FALSE if you don't handle the message.