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 |
|---|---|---|---|---|
6,563,300 | 6,563,327 | Function/variable auto completion C++ in visual studio 2010 | I created 2 games using the visual studio 2010 for WP7 using XNA and when trying to create one using c++ in visual studio I dont know how to turn on the auto completion thing. When for example I wanted to write a function/variable, I just used to write the first 2 letters then choose it from the list. This helps me sa... | Hit CTRL+SPACE after typing a few letters.
|
6,563,734 | 6,563,753 | Why SFINAE trick doesn't work for non-class type when tried for class member pointer? | With curiosity, I was trying an alternate implementation of is_class construct using the sizeof() trick. Following is the code:
template<typename T>
struct is_class
{
typedef char (&yes)[7];
typedef char (&no)[3];
static yes check (int T::*);
static no check (...);
enum { value = (sizeof(check(0)) == sizeof... | yes and no are not templates, SFINAE cannot possibly apply to them. You need to do this:
template<typename T>
struct is_class
{
typedef char (&yes)[7];
typedef char (&no)[3];
template <typename U>
static yes check (int U::*);
template <typename>
static no check (...);
enum { value = (sizeof(check<T>(0)... |
6,563,764 | 6,564,224 | Converting from C: fputc and fwrite in C#? | Question: In order to write a C# interface to libespeak, I need to convert the callback SynthCallback to C#.
See the below C code.
You might need this for reference:
https://ccrma.stanford.edu/courses/422/projects/WaveFormat/
http://www-mmsp.ece.mcgill.ca/documents/audioformats/wave/wave.html
Basically,
espeak_initia... | FileStream sink;
Int32 SynthCallback(IntPtr wav, Int32 numsamples, IntPtr events)
{
var wavm = new Int16[numsamples];
Marshal.Copy(wav, wavm, 0, numsamples);
// and do something with wavm
//or
var wavbytes = new Byte[numsamples * 2];
Marshal.Copy(wav, wavbytes, 0, numsamples*2);
sink.Write(... |
6,563,810 | 6,563,891 | M_PI works with math.h but not with cmath in Visual Studio | I am using Visual Studio 2010. I have read that in C++ it is better to use <cmath> rather than <math.h>.
But in the program I am trying to write (Win32 console application, empty project) if I write:
#define _USE_MATH_DEFINES
#include <math.h>
it compiles, while if I write
#define _USE_MATH_DEFINES
#include <cmath>
... | Interestingly I checked this on an app of mine and I got the same error.
I spent a while checking through headers to see if there was anything undef'ing the _USE_MATH_DEFINES and found nothing.
So I moved the
#define _USE_MATH_DEFINES
#include <cmath>
to be the first thing in my file (I don't use PCHs so if you are y... |
6,563,946 | 6,564,180 | Linking curl after compiling fails in netbeans build | if i try this
g++ -o testApp main.cpp -I/usr/local/include -L/usr/local/lib -lcurl -lssl -lcrypto -lz -lz
it works perfect...
BUT if i want to run my sample app by using netbeans directly it gives me some errors.
here a part of Makefile-Debug.mk
# Build Targets
.build-conf: ${BUILD_SUBPROJECTS}
"${MAKE}" -f nbpro... | The -L option needs to be before the library you specify with -l on the command line.
So if you need -L/usr/local/lib for libcurl (as in your small sample) you need to first specify -L to the correct dir and then -l with the correct lib name.
|
6,564,016 | 6,564,126 | How to perform deep copying of struct with CUDA? | Programming with CUDA I am facing a problem trying to copy some data from host to gpu.
I have 3 nested struct like these:
typedef struct {
char data[128];
short length;
} Cell;
typedef struct {
Cell* elements;
int height;
int width;
} Matrix;
typedef struct {
Matrix* tables;
int count;
} C... | The short answer is "just don't". There are four reasons why I say that:
There is no deep copy functionality in the API
The resulting code you will have to writeto set up and copy the structure you have described to the GPU will be ridiculously complex (about 4000 API calls at a minimum, and probably an intermediate ... |
6,564,107 | 6,564,118 | Interlocked functions c++ | I am developing a system that uses shared memory and interlocked functions.
Let's assume i have volatile unsigned int n, a, b. I want to do the following pseudocode atomicly:
if (a <= n && n < b)
{
n++;
}
else
{
//Do nothing
}
How would I do that? Can you use multiple Interlocked functions together?
| You need a lock or a CAS type operation. No amount of volatile is going to help here. Neither will a true atomic data type.
|
6,564,574 | 6,564,608 | Testing for Endianness: Why does the following code work? | While I do understand endianness, I am slightly unclear on how the code works below. I guess this question is less about endianness and more about how the char * pointer and int work i.e. type conversion. Also, would it have made any difference if the variable word was not a short but just an int? Thanks!
#define BIG_E... | A short int is made up of two bytes, in this case 0x00 and 0x01. On a little endian system, the small byte comes first, so in memory it appears as 0x01 followed by 0x00. Big endian systems are, naturally, reversed. This is what the pointers look like for short integers on a little endian system:
--------------------... |
6,564,581 | 6,564,664 | Initializing a Vector of Objects from a .txt file | #include<iostream>
#include<vector>
#include<fstream>
#include "stock.h"
int main(){
double balance =0, tempPrice=0;
string tempStr;
vector < Stock > portfolio;
typedef vector<Stock>::iterator StockIt;
ifstream fileIn( "Results.txt" );
for(StockIt i = portfolio.begin(); i != portfolio.end(); i... | First of all, iterating over the vector only makes sense when it isn't empty. So remove the line:
for(StockIt i = portfolio.begin(); i != portfolio.end(); i++)
because otherwise the contents of this loop will never be executed.
Second, you have problems with your input reading: you use getline for the first field, whi... |
6,564,823 | 6,565,328 | Visual C++ 2010 Express Compile Error | I am experimenting with C++ but am having trouble compiling with Visual C++ 2010 Express through the command line. I have been doing this without problem for several days, but now when typing cl /EHsc program.cpp into the Visual Studio Prompt, the program is not compiled. It instead outputs the following:
/EHsc
progr... | I have a guess at what is in program.cpp. I bet it is a small program that prints the values of argv[i] in a for() loop. If that's anywhere accurate, you probably got yourself into trouble earlier with a wrong command line and accidentally created cl.exe instead of program.exe.
Well, it works. Type "del cl.exe" to g... |
6,564,857 | 6,564,921 | How to figure out which methods increases size of 'exe' | I'm trying to write my first 'demoscene' application in MS Visual Studio Express 2010. Suddenly I realized, that my binary expanded from 16kb to ~100kb in fully-optimized-for-size release version. My target size is 64k. Is there any way to somehow "browse" binary to figure out, which methods consumes a lot of space, an... | I think you should have MSVC generate a map file for you. This is a file that will tell you the addresses of most of the different functions in your executable. The difference between consecutive addresses should tell you how much space the function takes. To generate a map file, add the /MAP linker option. For mor... |
6,564,944 | 6,565,057 | Questions about MMGR | I have been taking a look at MMGR for a memory allocation checker and I have a few questions that I don't see anywhere else on the internet.
1) There is a "reported size" and an "actual size". I understand what the "reported size" is, with it being the size that new receives, however, what is "actual size"? Why is ther... | I'm afraid I do not have any experience with MMGR, so I can only provide an answer for your first question.
The reason some memory debuggers mention a reported (or requested) and an actual allocation size has to do with the way memory allocators work. They rarely allocate exactly the requested size - usually they reser... |
6,565,007 | 6,575,670 | Brox Dense Optical Flow tracker error 'EFilterIncompatibleSize' | I am using the Linux 64-bit non-GPU executable dense optical flow tracker provided by Thomas Brox (available here: < http://lmb.informatik.uni-freiburg.de/people/brox/code.html >). I've followed the instructions there and correctly set up a .bmf file listing my own custom images for tracking. I have installed the libra... | After some more digging and contacting the author, it turns out that this error is caused when images of different sizes are given to the tracker. The container size is related to the pixel dimensions of the images. In my case, I believed that all of my images had identical dimensions since they were outputs from a cro... |
6,565,040 | 6,565,112 | SSE2 double multiplication slower than with standard multiplication | I'm wondering why the following code with SSE2 instructions performs the multiplication slower than the standard C++ implementation.
Here is the code:
m_win = (double*)_aligned_malloc(size*sizeof(double), 16);
__m128d* pData = (__m128d*)input().data;
__m128d* pWin = (__m128d*)m_win;
__m1... | First of all, VS 2008 is a bad choice for intrisincs as it tends to add many more register moves than necessary and in general does not optimize very well (for instance, it has issues with loop induction variable analysis when SSE instructions are present.)
So, my wild guess is that the compiler generates mulss instruc... |
6,565,352 | 6,565,375 | C++ If statement problem - displaying wrong info | I am having issues with my program displaying information from different if statements when they shouldn't be.
http://i53.tinypic.com/1zyx68.png
#include <iostream>
#include <string>
using namespace std;
int main( )
{
string smreturn = "";
string jointsingle = "";
double income = 0.00;
double taxedincome = ... | if (smreturn == "m" || "M")
should be
if ( (smreturn == "m") || (smreturn == "M") )
And mistakes like these in few other conditions. If you need to compare, you need to repeat it for each identifier in the if condition.
|
6,565,371 | 6,565,395 | how do C++ professional programmers implement common abstractions? | I've never programmed with C++ professionally and working with (Visual) C++ as student. I'm having difficulty dealing with the lack of abstractions especially with the STL container classes. For example, the vector class doesn't contain a simple remove method, common in many libraries e.g. .NET Framework. I know there'... | You would use the "remove and erase idiom":
v.erase(std::remove(v.begin(), v.end(), mystring), v.end());
The point is that vector is a sequence container and not geared towards manipulation by value. Depending on your design needs, a different standard library container may be more appropriate.
Note that the remove al... |
6,565,489 | 6,565,606 | Exact meanings of Should and Shall in the C++ standard | I've been reviewing the C++ standard 03 version. And I'm beginning to get confused with the meanings of the words Should and Shall.
Shall in the standard seems to indicate a compulsory requirement (will-have), where as Should in the standard seems to indicate an optional requirement (could-have). In English, Should imp... | From ISO TR 10176, Information technology – Guidelines for the preparation of programming language standards:
3.7 Auxiliary verbs used in this text
3.7.1 shall:
An indication of a requirement on programming language standard or processors.
3.7.2 should:
An indication of a recommendation to programming language standard... |
6,565,556 | 6,565,712 | Constant floats with SIMD | I've been trying my hand at optimising some code I have using microsoft's sse intrinsics. One of the biggest problems when optimising my code is the LHS that happens whenever I want to use a constant. There seems to be some info on generating certain constants (here and here - section 13.4), but its all assembly (which... | Simply cast __m128i to __m128 using _mm_castsi128_ps. Also, the second line should be
t = _mm_slli_epi32(t, 25)
|
6,565,675 | 6,565,680 | C++ (Allegro Library) Bitmap Two-Dimensional Array Question | I have a quick question. I am using C++ with the Allegro library.
If I make the following declaration BITMAP* blocks[600][14];, is it going to be wasted space if I only occasionally am using all 14 all of the second dimension or is that space only used when I specifically declare that part of the array?
For example:
BI... | In C++, arrays are contiguous so yes, you are 'wasting' the additional elements if you don't use them.
However, what you are wasting is only a single pointer (8 bytes on a 64-bit machine); not the actual bitmap data. So even if you use only one BITMAP* element in your 600x14 array you're wasting ~67kB; which isn't a m... |
6,565,823 | 6,565,837 | Help with type conversion error | When I try to compile my program, I get the following error:
main.cpp: In function ‘int main()’:
main.cpp:67: error: cannot convert ‘int (*)[(((long unsigned int)(((long int)mapSizeY) - 1)) + 1u)]’ to ‘int (*)[10]’ for argument ‘3’ to ‘void initializeMap(int, int, int (*)[10])’
main.cpp:68: error: cannot convert ‘... | C++ does not support variable-length arrays, which is what map is in your code. However, some compilers may support it as a non-standard extension. However, it certainly won't be compatible with a function expecting a "standard" array.
If you make mapSizeX and mapSizeY constants, this should work.
|
6,565,838 | 6,565,877 | Casting from unknown pointer to class; how to check validity? | I am using the LPARAM (essentially a long, unless we're on a 64-bit system in which case it is a long long) member of an LVITEM (called lParam) to store a pointer to the object that coincides with that entry in the ListView.
When I want to edit that item, I want to cast that LPARAM to a MyClass*, which works fine so lo... | You can't check it at all in pure standard C++. You can only do a probabilistic check using the Windows API. So, in practice you can only guarantee it, by making your code correct.
If you could check it you would still not know that it was the correct MyClass instance.
So, the only good way is to make your code guarant... |
6,566,204 | 6,566,212 | Minor memory allocation question C++ | int main() {
char **k;
char *s ="abc";
char *b ="def";
*k = s;
}
//Why does this produce segmentation fault? Shouldn't everything be store on the stack without any problems?
| k has no defined value yet, so dereferencing it (*k) causes undefined behaviour. If you add an initialization, i.e. k = &b;, *k = s; will work afterwards.
|
6,566,295 | 6,566,441 | OpenCV C++, getting Region Of Interest (ROI) using cv::Mat | I'm very new to OpenCV (started using it two days ago), I'm trying to cut a hand image from a depth image got from Kinect, I need the hand image for gesture recognition. I have the image as a cv::Mat type. My questions are:
Is there a way to convert cv::Mat to cvMat so that I can use cvGetSubRect method to get the Reg... | You can use the overloaded function call operator on the cv::Mat:
cv::Mat img = ...;
cv::Mat subImg = img(cv::Range(0, 100), cv::Range(0, 100));
Check the OpenCV documentation for more information and for the overloaded function that takes a cv::Rect. Note that using this form of slicing creates a new matrix header, b... |
6,566,395 | 6,570,380 | How to set UMFPACK's tolerance | I am using umfpack in c++ to solve a sparse matrix. I am having trouble finding where the [UMFPACK PIVOT TOLERANCE] parameter is set. Would anybody know how to set this control parameter?
My current code is
umf::symbolic_type<double> Symbolic;
umf::numeric_type<double> Numeric;
umf::symbolic(J, Symbolic);
umf::numeric... | umf::control_type<ublas::compressed_matrix<double>::value_type > myControl;
myControl.ptr[UMFPACK_SYM_PIVOT_TOLERANCE]=0;
myControl.ptr[UMFPACK_PIVOT_TOLERANCE]=0;
|
6,566,426 | 6,567,414 | boost signal with min_element | I am writing a little example to try to understand multiple return values of boost::signal. However, the result seems weired to me.
#include <boost/signal.hpp>
#include <iostream>
#include <algorithm>
int func1()
{
return 3;
}
int func2()
{
return 4;
}
int func3()
{
return 2;
}
template <type... | Weird. Replacing operator():
T operator()(InputIterator first, InputIterator last) const
{
InputIterator result = first;
while (++first != last) {
// *result;
std::cout<<*first<<std::endl;
}
return T();
}
Works, but as soon as you dereference result, first and result both get stuck at 3... |
6,566,539 | 6,566,567 | Another minor memory C++ question | int main() {
char **k;
char *s ="abc";
char *b ="def";
k = &s;
k++;
k = &b;
cout<<*(k - 1)<<endl; // nothing but newline. Shouldn't I get "abc"?
//EDIT: corrected a typo should be *(k - 1)
}
I got nothing but a newline from cout. When I looked at the behavior of char* I get the impression th... | k is a pointer to a pointer to a char, so when you advance it, it does not walk down the string as you're expecting it to. Instead, it now points to the char * that is located adjacent to the one it was pointing to. In your case there is none, so you're de-referencing a random memory location when you print the value o... |
6,566,632 | 6,566,733 | FMOD Result not being recognized as a valid type? | I have following block of code copied almost verbatim out of the fmod tutorials, with a minor modification of variable names so as not to conflict with anything. My code compiles fine without any of the fmod statements. When I put the FMOD_RESULT fm_result line and all that follows I get an error stating error C4430: m... | I don't know, it must be something about Visual Studio, or something else you're not telling us... The following compiles fine with me in GCC 4.6:
#include <fmod.hpp>
#include <fmod_errors.h>
#include <cstdio>
#include <cstdlib>
int main()
{
FMOD_RESULT fm_result;
FMOD::System *fm_system;
fm_result = FMOD::Syste... |
6,566,678 | 6,566,730 | How do I #define multiple values C / C++ | How would I define multiple values of the same type in an array using #define ?
For instance, I would like
#define DIGIT 0x30 | 0x31 | 0x32 | 0x33 | 0x34 | 0x35 | 0x36 | 0x37 | 0x38 | 0x39
#define QUOTE 0x22 | 0x27
ETC...
|
How would I define multiple values of the same type in an array using #define ?
For instance, I would like
#define DIGIT 0x30 | 0x31 | 0x32 | 0x33 | 0x34 | 0x35 | 0x36 | 0x37 | 0x38 | 0x39
#define QUOTE 0x22 | 0x27
Well, the term array in C and C++ refers to a number of variables of the same type, all side by side... |
6,566,746 | 6,566,864 | What is wrong with my libcrypto linking on Windows? | I am trying to link my c++ program against the libcrypto library, using Cygwin and Windows.
I have this in my .cc file
#include <openssl/dh.h>
I have the header file dh.h in usr/include/openssl
And I have the required files (libeay32.dll and ssleay32.dll) in /usr/lib/ however, when I build (using the python build to... | Libcrypto.so is Linux's dynamically linked library.
According to this on Windows You need to use libeay32.a and ssleay32.a.
If that doesn't work You have to make your own library from OpenSSL source.
|
6,566,826 | 6,567,510 | Segment Tree with lazy propagation Time limit problem | The following is the implementation of http://www.spoj.pl/problems/LITE/ using Segment Tree's with lazy propagation. I am new to segment trees and I cannot understand why I am getting TLE. Could someone please look at it and help me correct my error?
#include <iostream>
#include <iostream>
#include <cstdio>
#include <c... | M[node]^=1; might be faster than M[node] = (M[node]==0)?1:0;, and (begin+end)>>1 faster than (begin/end)/2, but not very relevant
LE: Try if making the recursive functions inline will run faster. I think it unravels the recursion a couple of times and works a little bit faster. Maybe sending the parameters as referenc... |
6,566,920 | 6,566,952 | Can not read byte data from inputstream | I wrote a server using c++ and the code looks like this
char *sendBuffer = new char[4+4+1+8+48];
m_magicNumberBuffer[0] = 0xA9;
m_magicNumberBuffer[1] = 0xA9;
m_magicNumberBuffer[3] = 0xA9;
m_magicNumberBuffer[4] = 0xA9;
int m_dataLength = 4+4+1+8+48;
unsigned char m_type = 1;
long long m_deviceId = 12123122123;
char m... | Pretty simple, really: you want to add your offset to the destination sendBuffer, not your sources. E.g. instead of
memcpy(sendBuffer, &m_deviceId + offset, 8);
you want
memcpy(sendBuffer + offset, &m_deviceId, 8);
As it is, you are storing various random data to the first few bytes of sendBuffer, and nothing to the... |
6,567,326 | 6,567,699 | Does std::sort check if a vector is already sorted? | I believe that the C++ standard for std::sort does not guarantee O(n) performance on a list that's already sorted. But still, I'm wondering whether to your knowledge any implementations of the STL (GCC, MSVC, etc) make the std::is_sorted check before executing the sort algorithm?
Asked another way, what performance can... | Implementations are free to use any efficient sorting algorithm they want so this is highly implementation dependant
However I have seen a performance comparison of libstdc++ as used on linux and against libc++ the new C++ library developed by Apple/LLVM. Both these libraries are very efficient on sorted or reverse sor... |
6,567,606 | 6,571,786 | How to monitor a process's resource usage(time, memory) at run-time? | I am trying to monitor a process's resource usage(time, memory, system calls) at run-time, is there apis in windows like ptrace, setrlimit in linux ?
Thanks
| There are a bunch of APIs depending on what you want in C/C++ (or C# through P/Invoke):
e.g, to start looking,
Process CPU time (UM/KM):
http://msdn.microsoft.com/en-us/library/ms683223(VS.85).aspx
Process VM (working set):
http://msdn.microsoft.com/en-us/library/ms683226(v=VS.85).aspx
Process I/O data:
http://msdn.mi... |
6,567,644 | 6,567,679 | Trouble with templates | I have three files and I want to compile and run them, but I keep getting some errors and warnings. Redefinition of struct Node< T >. I don't know much about templates, but this looks right to me. And, I spent a lot of time trying to figure out whats wrong. Thanks.
//mystack.h
#ifndef MYSTACK_H
#define MYSTACK_H
tem... | If you were designing a class instead of a template, what you're doing would be wrong because you're redefining types.
But since you're writing templates, you're wrong earlier than that: you can't separately compile templates.
Brief pointer on the C++ compilation model:
// Definition of Node
template<typename T>
struct... |
6,567,697 | 6,569,549 | replacement for findfirst() and findnext() | Is there any replacement for findfirst() and findnext().
I am using microsoft visual c++ 2010 express and it doesn't support these functions neither the header file <dir.h> ?
I was looking to count the number of files in the directory using these functions but i am having a problem without these functions.
If there is ... | As 'iammilind' said in the comments (probably worthy of an answer) - you can use the windows api's FindFirstFile and FindNextFile functions, you just have to fill up a struct and iterate through the latter until you reach an invalid handle. These functions do work on console, but you must include the 'Windows.h' header... |
6,567,720 | 6,567,939 | Reading Targa File. Missing Dark Colors? | Due to being new, I can only have two links and can not post my images. Sorry for the inconvenience of having to copy+paste addresses
I am parsing a Targa (.tga) image file with code similar to that found at steinsoft.net/index.php?site=Programming/Code%20Snippets/Cpp/no8
After retrieving the data into the unsigned cha... | First of all, why do you check if the data[i]==NULL? There might be 0-pixels (black), so keep them all in. You basically check if the color is 0 and then you exit your loop. Just read all pixels no matter the value.
|
6,567,760 | 6,567,857 | Linked list destructor | I'm studying C++ on my own time, and writing a linked list to try and get the hang of it. I'm worried about the way I've come up to delete the object. It's a singly linked list. Here's the destructor:
template <typename T>
LinkedList<T>::~LinkedList()
{
Node<T> * current = this->first;
do {
Node * temp = curre... |
Don't delete this in the destructor.
If Node is a template, then you need to write Node<T> in all of those definitions.
Don't redefine current, just assign it a new value.
Other than that, I don't see any other problems in this snippet.
|
6,567,854 | 6,567,962 | Can anyone explain me this code | #ifndef EIGHT_BIT
#define THIRTYTWO_BIT // default 32 bit
#endif
#ifdef THIRTYTWO_BIT
#define WORD unsigned long
#define WORDLENGTH 4
#if defined(WIN32) && !defined(__GNUC__)
#define WORD64 unsigned __int64
#else
#define WORD64 unsigned long long
#endif
// THIRTYTWO_BIT
#endif
#ifdef EIGHT_BIT
#define WORD unsi... | The first thing to note about this code is that none of it will actually be compiled into C. Every line that isn't whitespace or a comment starts with a pound sign (#), meaning they are preprocessor directives. A preprocessor directive alters the code before it even makes it to the compiler. For more information of pre... |
6,568,049 | 6,572,212 | What are the scenarios that cause the compiler to emit spurious warnings? | I sometimes read such comment by previous developers inside the source code:
// and this is to make compiler stop crying
I think with C/C++ it's typical that something you are doing practically legal, but still compiler sees it as illegal.
Is there a list of the scenarios that cause the compiler to emit spurious warni... | There is no definitive list of such warnings, because the C standard does not disallow a conforming compiler from emitting warnings or diagnostic messages for legal code. Each C compiler therefore has its own list of warnings, some of which can trigger on perfectly correct, perfectly legal code (the canonical example ... |
6,568,188 | 6,568,312 | Error: argument of type char* is incompatible with parameter of type LPCWSTR | #include <windows.h>
#include <iostream>
using namespace std;
int main() {
char* file="d:/tester";
WIN32_FIND_DATA FindFileData;
HANDLE hFind;
hFind = FindFirstFile(file, &FindFileData); // line of error says argument of type char* is incompatible with parameter of type LPCWSTR
}
I can't understand the error.What... | You are calling function that expects wide character string (FindFirstFileW). You either change file to use wchar_t* file = L"d:\\tester"; or use an ASCII version of the function FindFirstFileA.
|
6,568,300 | 6,569,034 | How to invoke C++ function? | I have a function with the prototype as
void test( int array [] , int b);
I know we can replce the protoype as: void test(int*, int);
In main() we declare the following arrays :
int array1[10], array2[10];
To set the body of the function to 0,
test ( array1 , b)
{
for ( int i = 0 ; i < b ; i++)
array1[i] = 0;
}
... | You may be asking about the difference between formal parameters and actual parameters.
In your prototype
void test(int *array, size_t size);
the names 'array' and 'size' are the formal parameters. You use those names inside the body of your function.
In the code that invokes the function, you can use different names,... |
6,568,486 | 6,568,502 | When do we need a private constructor in C++? | I have a question about private constructors in C++. If the constructor is private, how can I create an instance of the class?
Should we have a getInstance() method inside the class?
| There are a few scenarios for having private constructors:
Restricting object creation for all but friends; in this case all constructors have to be private
class A
{
private:
A () {}
public:
// other accessible methods
friend class B;
};
class B
{
public:
A* Create_A () { return new A; } // creation rig... |
6,568,557 | 6,568,661 | Clamping degree values to 0 <= x < 360 algebraically | Given the function:
void Arc::SetAngles(double startAngle, double endAngle) {
while(endAngle > (startAngle + 359.0)) endAngle -= 1.0;
while(startAngle > 360.0) startAngle -= 360.0;
while(startAngle < -360.0) startAngle += 360.0;
while(endAngle > 360.0) endAngle -= 360.0;
while(endAngle < -360.0) end... | In C or C++ you'd use fmod to get rid of some of your loops. Instead of this:
while(startAngle > 360.0) startAngle -= 360.0;
while(startAngle < -360.0) startAngle += 360.0;
Do this:
startAngle = fmod(startAngle, 360.0);
if(startAngle < 0)
startAngle += 360.0;
Don't use the normal modulus operator (%) as that's fo... |
6,568,645 | 6,574,273 | operator<<(ostream&, X) for class X nested in a class template | This one compiles and works like it should (non-nested template):
#include <iostream>
template<typename T> class Z;
template <typename T>
std::ostream& operator<< (std::ostream& os, const Z<T>&) {
return (os << "Z");
}
template<typename T> class Z {
friend std::ostream& operator<< <> (std::ostream& os, cons... | Matthieu explained the problem very well, but a simple work-around can be used in this case.
You can implement the friend function inside the class with the friend declaration:
#include <iostream>
template <typename T> class Z {
public:
class ZZ {
friend std::ostream& operator<< (std::ostream& os, const ZZ&) {
... |
6,568,656 | 6,568,912 | Why does the size of a derived class include private members from the base class? | I have the following code:
class A {
private:
int i;
};
class B : public A {
private:
int j;
};
When I check sizeof(B), it appears to be sizeof(base) + sizeof(derived). However, my understanding of inheritance is that the private members of a base class are not inherited. Why then are they included in the ... | You either misunderstand sizeof or your misunderstand the layout (in memory) of C++ objects.
For performance reason (to avoid the cost of indirection), compilers will often implement Derivation using Composition:
// A
+---+
| i |
+---+
// B
+---+---+
| A | j |
+---+---+
Note that if private, B cannot peek in A even t... |
6,568,668 | 6,568,756 | cmake cannot find static library | g++ (Ubuntu/Linaro 4.5.2-8ubuntu4) 4.5.2
I have a static library called sdpAPI.a
I am trying to link my cpp file to it using cmake.
My CMakeLists.txt looks like this?
CMAKE_MINIMUM_REQUIRED(VERSION 2.8)
PROJECT(demo_project CXX)
IF(CMAKE_COMPILER_IS_GNUCXX)
SET(CMAKE_C_FLAGS "-Wall -Wextra -Wunreachable-code -O0 -D... | I should have renamed sdpAPI.a to libsdpAPI.a
This solved my problem. A silly mistake which cost me 3 hours.
Hope this helps someone else.
|
6,568,778 | 6,568,822 | call overwritten child function within parent function | is it possible in c++ to call a child function from a parent function.
Let's take an example: The parent class defines in a function (parse) the general workflow. The workflow then calls different methods which represent part of the flow (parseElementA). These functions can be overwritten by the child class, if not the... | After fixing compiler errors from your code, it works fine.
|
6,569,095 | 6,569,188 | How to create pthread specific variables without __thread | I'm maintaining a library that has a function that needs thread specific variables.
Due to a bug in gcc 4.2, if I define
static __thread in x;
when the library function is called via unnamed API from PERL, it hangs.
I'd like to define the thread local variables using pthread_key_create(), but I need to do it
in the l... | To do something once use pthread_once:
pthread_key_t tls_key;
pthread_once_t tls_init_flag=PTHREAD_ONCE_INIT;
extern "C"
{
static void tls_destructor(void*); // run when thread exits to cleanup TLS data
static void create_tls_key()
{
if(pthread_key_create(&tls_key,tls_destructor))
{
... |
6,569,176 | 6,654,311 | MIDL. Why callback c++ interface doesn't renewed after method added to idl? | I try to implement callback interface with COM techonlogy and have IDL like that:
library LogstreamScannerLib
{
importlib("stdole2.tlb");
[
uuid(8CACF064-EF0E-4496-92D5-F26C64A5858A)
]
dispinterface _IMyClassEvents
{
properties:
methods:
[id(1)] void Som... | Finally, I have found the issue.
When you use "Implement Connection Point Wizard" you should choose generate connection point from "Type Library" (instead of "IDL"). You see this choice in combobox and should change default option IDL -> Type Lib.
|
6,569,255 | 6,579,060 | glmapbufferOES and glunmapbuffer undeclared in opengl-es 2.0 | I am doing coding in ubuntu 10.10 with kronos headers but i am stuck because whenever i try to compile the code they there is an error comes :
glmapbuffer undeclared
glunmapbuffer undeclared
i have gl2.h and gl2ext.h in my header file .Can anyone tell me
If I am doing like this what else can i do :
glBindBuffer(GL... | The suffix …OES indicates that those functions are not part of the core OpenGL-ES specification, but are considered optional functionality, very much like …ARB extensions mentioned in standard OpenGL specifications. Like with standard OpenGL the method to access the extension, if available, depends on the target plattf... |
6,569,412 | 6,569,454 | Container Adapters do not support iterators | In one of the C++ articles on STL, is being said that -
Since container adapters do not support iterators, hence they cannot be used with the STL algorithms.
But it did not explain as to why Container Adapters do not support iterators? Can anybody explain me the same?
| What's the point of a stack or a queue having an iterator? A stack is by definition something that you can only push and pop into... An iterator would destroy the whole purpose of these adapters
|
6,569,566 | 6,570,718 | parse plain python list of double | What's the best way to parse a line like this (the number of elements is not fixed):
[ 0.0125, 2.9518e+02, 1.2833e+00, -3.5302e-04, 1.2095e+01, 1.0858e-01, 1.2112e-04, 1.1276e+03 ] # comments
to obtain a std::vector of double in c++? I've done this:
vector<double> read_line(string line)
{
vector<double> c... | Given the format, I would think it is simple enough to use IO Streams.
#include <iostream>
#include <sstream>
#include <vector>
int main() {
std::istringstream line("[ 1.23, 1.24e+3, 3, 1.44e-2 ]");
char c;
while ((line >> c) && c != '[');
if (!line) { return 1; }
std::vector<double> v;
double d;
whil... |
6,569,619 | 6,569,747 | Regarding error thrown by sizeof(class) usage in C++ | When I compile my project in C++, the following error is thrown by MSVC :
error #94: the size of an array must be greater than zero
The error is thrown in the following line on doing sizeof :
if (sizeof (MyNamespace::MyClass) == 60)
MyClass is defined thus :
class MyClass: public ParentClass
{
public:
M... | This error is caused when you take the sizeof of a class that's only declared at that point. E.g. class MyClass; const size_t error = sizeof(MyClass);.
Note that it doesn't matter whether the class is fully defined later: the definition must precede the sizeof.
|
6,569,716 | 6,572,669 | template of template c++? | i've managed to create some preperty class with all the thing we expect from one. I mean when using it you don't need to call functions just using operator = will do all the work. but there is only one thing I guess it would be nice if we could resolve :
template <class T, class X,void (T::*setFunc)(const X&),const X& ... | If you'd like to omit specifying the type parameters explicitly,
the following code will meet the purpose.
However, this code requires VC2010.
template <class> struct class_type;
template <class C, class T> struct class_type< T(C::*) > { typedef C type; };
template <class> struct param_type;
template <class C, class T... |
6,569,761 | 6,570,394 | A smart way to export c++ polymorphic functions with boost.python | I have a highly polymorphic c++ function that can be called with nearly 20 diferent types.
In order to expose it to python I'm doing something like this:
#include originalFunctionNamespace.hpp
template<class T>
T foo(T x)
{
return orignalFunctionNamespace::foo(x);
}
but then to call them from pyth... | Looks like a possible use for typelist magic, to me.
If you're using (or can use) the new C++0x standard, you can write something like this:
template <typename ArgType>
void def_foo_overloads()
{
def("foo", foo<ArgType>);
// last type in list
}
template <typename ArgType, typename... MoreArgTypes>
void def_foo_... |
6,569,946 | 6,569,981 | destructor of a singleton class is called twice! | i have the code as below :
class Singleton {
private:
int i;
static bool stnflag;
static Singleton* single;
Singleton(int a)
{
i=a;
}
public:
static Singleton* getinstance(int);
void function();
~Singleton()
... | Well, don't call delete on it twice!
Calling delete on an already deleted object is undefined behaviour, not a guaranteed crash.
You should consider having getinstance() return a reference, rather than a pointer.
|
6,570,139 | 6,570,154 | MinGW error: 'min' is not a member of 'std' | I'm trying to convert some VC++ 6 code to a console app using only the standard libraries but am getting the following error from MinGW (whatever version is supplied with the Code::Blocks 10.05 IDE):
error: 'min' is not a member of 'std'
This is related to the following line of code:
L.Precision=std::min(1.e-4,0.001*r... | You should uncomment and fix #include <algorithm>, (without the .h) which is where std::min is declared.
This has absolutely nothing to do with MinGW or GCC or Windows, this is standard C++ stuff. If you hit any other errors like this, search for the missing identifier on http://en.cppreference.com/w/.
Also: use <cmath... |
6,570,205 | 6,572,378 | MoveWindow() missing in C++ OpenCV 2.3 | I am using the C++ version of OpenCV 2.3 and am struggling to do a basic task. What I would like to do is create a window and move it to a specific location on the screen using for example:
cv::namedWindow("My Window", 1);
cv::MoveWindow("My Window", 10, 10);
However, it appears that the MoveWindow() function is not a... | You are supposed to use the C function for this:
cvMoveWindow(const char* name, int x, int y);
You can verify this info by downloading OpenCV 2.3 for *nix, and under the C++ samples directory OpenCV-2.3.0/samples/cpp/tutorial_code/Basic/ search for a file named Drawing_1.cpp. It uses the C++ interface for everything..... |
6,570,286 | 6,570,314 | Primitive #define understanding in C | I have a macro defined in C something like this:
#define SOME_FIELD(_A_,_B_,_C_) \
MyObj[ ## _A_ ## ].somePTR = \
(DWORD_PTR) (buff_ ## _C_ ## _C_ ## _ ## _B_ ## );
What i can understand that for index A we are getting some value for "somePTR". My question is, What is ## <name> ## notation for and wi... | That is called token concatenation. It allows you to glue arguments together.
For your example, SOME_FIELD(Param1,Param2,Param3); expands like this:
MyObj[Param1].somePTR = (DWORD_PTR) (buff_Param3Param3_Param2);
It's easy enough to try this out yourself by using your compiler's pre-processor. You don't generally need... |
6,570,970 | 6,573,968 | How should I implement peer-to-peer networking in C++? | I have previously implemented server/client networking programs in C, but I have never done peer-to-peer program or any socket programming in C++.
For peer-to-peer, I guess I would have to create multiple threads and manage incoming and outgoing connections, since each program will work like a client and a server at th... | You're not required to use multiple threads. An alternative is to use a single thread, and multiplex the sockets using select() (or poll() or epoll() or etc).
|
6,570,984 | 6,571,087 | std::for_each ignoring default function argument | I stumbled on a strange compilation problem. I want to process a list of strings, using std::for_each. The following simplified code illustrates the problem :
# include <list>
# include <string>
# include <algorithm>
using namespace std ;
void f(wstring & str)
{
// process str here
}
void g(wstring & str, int du... | Default arguments are just a code-generation tool and not part of the function signature, so you can't really get around that. You could wrap your function in a function object, but that's precisely what bind already does for you.
However, in C++0x you can conveniently store the result (and use std::bind) to maybe make... |
6,571,160 | 6,571,361 | Multidimensional polynomial regression (preferably C/C++, Java or Scala) | Given a collection of (N+1)-dimensional real valued vectors with N independent and 1 dependent value, I would like to compute a polynomial of degree 1 (linear), 2 (quadratic) or higher that provides a reasonably good fit (e.g. as determined by least squares error). In other words, when applied to the elements of the co... | You might want to explore the Weka data mining and machine learning platform - it's extremely comprehensive and includes all kinds of different regression algorithms.
A big bonus is that it is all open source so you can also study the code if you like.
|
6,571,314 | 6,571,351 | This is not the output i asked for | #include <fstream>
#include <iostream>
#include <string>
using namespace std;
int main() {
ofstream w("d:/tester.txt");
int f = 1;
int s = 2;
int t = 3;
string x = "hello";
w << f << endl << s << endl << t << endl << x ;
w.close();
ifstream r("d:/tester.txt");
r >> x;
cout << x << endl ;
s = s + 10 ;
r.clo... | In fact, it is the output you ask for: you are reading the first string token from the file. And that happens to be the number “1” you wrote on the first line into the file.
The streaming operators don’t magically parse your file for the most suitable token; they are simply reading the next available token. And even if... |
6,571,381 | 6,571,447 | Dependent scope and nested templates | When I compile this:
#ifndef BTREE_H
#define BTREE_H
#include <QList>
template <class T, int degree>
class btree
{
public:
class node
{
public :
node();
private:
node* parent;
QList<T> values;
QList<node*> children;
};
public:
btree();
void insert(const T& va... | The C++ grammar is horrendous, and as such it is not possible, when given a template class, to know whether the ::node you refer to is a variable/constant or a type.
The Standard therefore mandates that you use typename before types to remove this ambiguity, and treats all other usages as if it was a variable.
Thus
tem... |
6,571,550 | 6,571,960 | My class interferes with library class | I am currently programming on a 3d visualization program so I wrote my own Vector3 class to have some convenient vector operations. That worked fine until I needed to load some Meshes which I used an external library for that has its own Vector3 class. Now the compiler can't tell them apart and I can not change both be... |
EDIT Unfortunately my own project as well as the library have no own namespace.
The solution is obvious. Put your project in a namespace. And refer to the Vector3 in the library with ::Vector3, if it truly does not have any namespace.
|
6,571,837 | 6,572,570 | Why does boost::spirit::qi::parse() not set this boost::variant's value? | When trying to parse text into a boost::variant, the variant's value does not get changed.
The parsers by themselves appear to work fine, so my assumption is that I'm doing something wrong with the variant code.
I'm using boost 1.46.1 and the following code compiles in Visual Studio 2008.
1st Update
hkaiser noted that ... | The rule's attribute must be specified using the function declaration syntax:
qi::rule<Iterator, Variant()> m_rule;
I have not tried, but I believe it will work after this change (the same is required for the grammar, btw).
|
6,572,191 | 6,572,246 | How to get the typeid of a void* pointer? | I have a list of pointers to objects. These objects have nothing in common (i.e. no common base class); for better understanding: It is a list of objects that lie under the mouse cursor in a GUI.
Now I would like to know what kind of object it is. A node, a node handle, a line segment, a tag, and so on. However I canno... | For a technical solution, not considering design level, use a std::map or hash table (whatever) to associate the untyped pointers with type descriptors or typed pointers, of course before the user starts using the mouse.
At a higher level, the void* pointers are just ungood.
It would be best to fix the design instead o... |
6,572,229 | 6,590,356 | Drawing a transparent object inside an opaque one | I'm trying to draw a transparent object inside an opaque cage, but what ever I seem to try I can't get it right.
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glClearColor( 0.0f, 0.0f, 0.0f, 0.0f );
glDisable(GL_BLEND);
glEnable(GL_DEPTH_TEST);
glEnable(GL_CULL_FACE);
glCullFace(GL_BACK);
glColor4f(1.0, 1.... | A few things.
Check the depth function in your initialisation and that your pixel format has a depth buffer.
Try it with the standard gouraud shader first.
Triple check that all the vertices of the transparent object are inside the cage.
Use some sort of camera rotation each frame so that you can see the rendered scen... |
6,572,550 | 6,614,372 | boost::property_tree XML pretty printing | I'm using boost::property_tree to read and write XML configuration files in my application.
But when I write the file the output looks kind of ugly with lots of empty lines in the file.
The problem is that it's supposed to be edited by humans too so I'd like to get a better output.
As an example I wrote a small test pr... | The solution was to add the trim_whitespace flag to the call to read_xml:
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/xml_parser.hpp>
int main( void )
{
// Create an empty property tree object
using boost::property_tree::ptree;
ptree pt;
// reading file.xml
read_xml("fil... |
6,572,679 | 6,572,700 | How to delete multiple added pointer of a vector? | I have a vector with some (among other classobjects) multiple added objects
class Foo {
...
vector<Bar*> v;
Bar* b = new Bar();
v.push_back(b);
v.push_back(b);
...
}
in Foo's destructor I do
for (vector<Bar*>::iterator it = v.begin(); it != v.end(); ++it)
delete *it;
this causes an exception on the se... | Solve it by not using the terrible idea of storing raw pointers in a container. Instead, use a container of smart pointers:
#include <memory>
#include <vector>
typedef std::shared_ptr<Foo> FooPtr;
std::vector<FooPtr> v;
FooPtr b(new Bar()); // #1
v.push_back(b);
v.push_back(b);
v.push_back(b);
// C... |
6,572,707 | 6,572,751 | Why is a second pointer to an Object not set to NULL but the Object pointer? | #include <iostream>
using namespace std;
class Object{};
class Connection
{
public:
Connection(Object * _obj);
Object * obj;
void status();
};
Connection::Connection(Object * _obj)
{
obj = _obj;
}
void Connection::status()
{
cout << obj << endl;
}
int main() {
Object * myObj = new Object();
... | It shouldn't be 0 because you are copying pointer value. Try using references (&) instead.
Maybe this is not a best example, and boost::shared_ptr will be better solution, but this code will work:
// skipped...
class Connection
{
public:
Connection(Object **_obj);
Object **obj;
void status();
};
Connect... |
6,572,787 | 6,572,977 | Spitting a char array into a sequence of ints and floats | I'm writing a program in C++ to listen to a stream of tcp messages from another program to give tracking data from a webcam. I have the socket connected and I'm getting all the information in but having difficulty splitting it up into the data I want.
Here's the format of the data coming in:
8 byte header:
4 character ... | The buffer only contains the raw image of what you read over the
network. You'll have to convert the bytes in the buffer to whatever
format you want. The string is easy:
std::string s(buffer + sOffset, 4);
(Assuming, of course, that the internal character encoding is the same
as in the file—probably an extension of... |
6,572,874 | 6,593,899 | Vectorization with unrolled loop | I'm using intel-cc to compile some C++ code and with the -Wall option it seems to be vectorizing a lot of my loops. I'm working under the assumption this is good for performance for now.
Now my question is this; if instead of a for loop I have unrolled it so we have for example
a[0] = b[0] + 1;
a[1] = b[1] + 1;
a[2] =... | So I had a delve into the assembly generated by the three simple cases. below;
for(int i=0;i<3;++i) a[i] = 1.0; // case 1
a[0] = a[1] = a[2] = 1.0; // case 2
a.x = a.y = a.z = 1.0; // case 3
The assembly generated for cases 2 and 3 was identical. This is good since in case 2 the compiler gave a "rema... |
6,572,923 | 6,572,944 | Is accessing data outside an array incorrect if you don't use it? | In an algorithm I'm writing, I can have the following (simplified of course)
int a[3] = {1,2,3};
int b = a[3];
when the index used to fill b overflows, I never use the value of b. Is the code still incorrect? Do I have to make an explicit boundary check?
| This code has Undefined Behavior whether or not you use b. Why? Because a[3] is equivalent to *(a+3) by definition. And here's a quote from the standard that proved that *(a+3) is in itself undefined, regardless of whether the value is stored, used, or left alone.
When an expression that has integral
type is added t... |
6,573,029 | 6,579,316 | Read From Media Buffer - Pointer Arithmetic C++ Syntax | This may well have come up before but the following code is taken from an MSDN example I am modifying. I want to know how I can iterate through the contents of the buffer which contains data about a bitmap and print out the colors. Each pixel is 4 bytes of data so I am assuming the R G B values account for 3 of these b... | I solved the problem myself and thought it best to add the answer here so that it formats correctly and maybe others will benefit from it. Basically in this situation we use 32 bits for the image data and what is great is that we are reading raw from memory so there is not yet a Bitmap header to skip because this is ju... |
6,573,146 | 6,713,012 | OpenCV different output results using a BruteForceMatcher over two different runtimes with same input | Intro :
First and as an introduction, i am quite "proud" to ask my first question on StackOverflow. I hope I'll be able to help other people as much as they help me.
Context :
I am developping an application that searches for features in an image using a SURF algorithm. I compute the keypoints and I extract the descri... | Could you check the order of the featuers? If you have multiple CPUs, the code may run parallel so the features are not in the same order (for each time).
|
6,573,174 | 6,573,665 | C++ Idiomatic Type Traits | I have a system of type traits that resides in a namespace, like so:
namespace my_namespace
{
template <typename T>
struct magic_traits
{
static const int value = 0;
};
}
Because people hate the syntax of template specializations, I have this convenient little macro:
#define DECLARE_MY_MAGIC_TRAITS(type_, value_... | Maybe a bit ugly, but how about this as an idea :
namespace my_namespace
{
typedef bool The_DECLARE_MY_MAGIC_TRAITS_macro_should_be_used_in_the_global_namespace;
template <typename T>
struct magic_traits
{
static const int value = 0;
};
}
#define DECLARE_MY_MAGIC_TRAITS(type_, value_) \
namespace my_namespa... |
6,573,225 | 6,573,303 | What requirements must std::map key classes meet to be valid keys? | I want to map objects of a given class to objects of another. The class I want to use as key, however, was not written by me and is a simple struct with a few values. std::map orders it's contents, and I was wondering how it does it, and if any arbitrary class can be used as a key or if there's a set of requirements (o... | All that is required of the key is that it be copiable and assignable.
The ordering within the map is defined by the third argument to the
template (and the argument to the constructor, if used). This
defaults to std::less<KeyType>, which defaults to the < operator,
but there's no requirement to use the defaults. Jus... |
6,573,460 | 6,574,181 | Qt calling QApplication::exec from library | This is a follow on from a question I asked about embedding Qt code in a legacy C application.
I am able to build Qt code into my C application and was surprised to find that I can even run gui code from within the static library I'm using to do this.
(My C application is also GUI driven, by the way).
This opens up so... | The answer to your problem is threading.
Since you are doing C, pthreads is probably available to you.
void * qt_thread(void * parm) {
// code here
QApplication::exec();
}
//some where in your main()
pthread_t qt;
pthread_create(&qt, NULL, qt_thread, NULL); //returns immediately
// rest of code
This is a VER... |
6,573,465 | 6,573,500 | C++ error with classes: expected initializer before '*': | I'm implementing a list (just for fun):
#include <iostream>
template <class T>
class list {
private:
struct node {
T data;
struct node *next, *prev;
} head;
unsigned int length;
public:
class iterator {
private:
node *ptr;
public:
iterator ();
inlin... | Because your definitions are out-of-class, the nested type iterator is not in scope; You need to qualify the reference to iterator
template <class T>
inline iterator list<T>::iterator::operator++() {
should be
template <class T>
inline typename list<T>::iterator list<T>::iterator::operator++() {
|
6,573,472 | 6,573,525 | Replace if-else with ?: in c++ | The original code is:
if (expression1) statement1;
else statement2;
is it possible to transform it into this?
expression1 ? statement1 : statement2
or it depends on the compiler? it seems that this differs within c++ standards?
Sometimes the case is if (expression1) statement1; and how can i transform that?
b... | expression1 ? statement1 : statement2 This is actually incorrect. The correct is this:
expression1 ? expression2 : expression3
Not any statement can be equivalently transformed into a single expression, so in general it is not always possible. For example:
if(expr)
{
for(int i = 0; i < 2; ++i) {std::cout << i; }
}
e... |
6,573,552 | 6,574,195 | Console is intercepting all my assert messages | I have a simple assertion macro that prints out a message. This usually works when the application is not a console application (i.e. I get a nice dialog that pops up, and has the expression including the message at which point I can hit retry to debug) but when it is, the console intercepts all the messages. This beco... | The CRT attempts to work out where you want assert output to go to based on the type of application. It detects this from the type of the executable (/SUBSYSTEM). However, you can override with _set_app_type so that the CRT acts as if your console app is a Windows app. More likely, you just want to impact assertions an... |
6,573,586 | 6,575,353 | BOOST_FOREACH Iteration over boost::shared_ptr<list> | I'm doing something similar to this item Correct BOOST_FOREACH usage?
However, my returned list is wrapped in a boost::shared_ptr. If I do not assign the list to a variable before the BOOST_FOREACH loop, I get a crash at runtime as the list is getting destructed as it is a temporary.
boost::shared_ptr< list<int> > Get... | Ok, the 'Best Practice' for shared_ptr mentions to avoid using unnamed temporaries:
http://www.boost.org/doc/libs/release/libs/smart_ptr/shared_ptr.htm#BestPractices
Avoid using unnamed shared_ptr
temporaries to save typing; to see why
this is dangerous, consider this
example:
void f(shared_ptr<int>, int); int g();
... |
6,573,718 | 6,573,736 | C++/Qt - Compile problem: syntax error : missing ';' before identifier - No idea | I have the very simple following code:
main.cpp
#include "ui_library_browser.h"
#include <QtGui/QApplication>
#include "StartWindow.h"
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
StartWindow w;
w.show();
return a.exec();
}
StartWindow.h
#ifndef STARTWINDOW_H_
#define STARTWINDOW_H_
#incl... | You have circular dependencies on your headers. Remove the #include "StartWindow.h" from your MainWindow.h file.
|
6,573,746 | 6,575,149 | What GCC Optimization Is Occurring In This For Loop? | Using gcc 4.6 with -O3, I have timed the following four codes using the simple time command
#include <iostream>
int main(int argc, char* argv[])
{
double val = 1.0;
unsigned int numIterations = 1e7;
for(unsigned int ii = 0;ii < numIterations;++ii) {
val *= 0.999;
}
std::cout<<val<<std::endl;
}
Case 1 r... | René Richter was on the right track regarding underflow. The smallest positive normalized number is about 2.2e-308. With f(n)=0.999**n, this limit is reached after about 708,148 iterations. The remaining iterations are stuck with unnormalized computations.
This explains why 100 million iterations take slightly more tha... |
6,573,830 | 6,573,846 | Converting std string to const char* | I am getting an error when I run this piece of code
string line;
getline (myfile,line);
char file_input[15];
strncpy(file_input, line, 6);
cout << line << endl;
Error - cannot convert ‘std::string’ to ‘const char*’ for argument ‘2’ to ‘char* strncpy(char*, const char*, size_t)’
How to get rid of this?
| strncpy(file_input, line.c_str(), 6);
But why would you want the fixed-length buffer file_input in the first place? It would be safer to construct it as a new std::string containing the first five characters in line:
std::string file_input(line, 0, 5);
|
6,573,878 | 6,573,940 | Circular dependencies with headers. Using #ifndef and #define | I have the very simple following code:
main.cpp
#include "ui_library_browser.h"
#include <QtGui/QApplication>
#include "StartWindow.h"
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
StartWindow w;
w.show();
return a.exec();
}
StartWindow.h
#ifndef STARTWINDOW_H_
#define STARTWINDOW_H_
#include... | So called "header guards" are used to prevent a bit different kind of error: including same header multiple time through different indirect inclusions in one compile unit. For example,
you include "a.h" from main.cpp and then include "b.h" from main.cpp, that includes "a.h" itself somewhere inside.
In your case two he... |
6,573,894 | 6,574,187 | why compiler can't deduce template argument in my code? | I'm using visual studio and I've tried every thing I could think of. but don't know why this piece of code generates error, this is my code:
template <class A,class B> B returnArgtype(void (A::*)(B)) {return *new B;}
struct test
{
void function(int);
decltype(returnArgtype(&test::function)) x;
};
and it gener... | This is the same bug I linked to on your other question (please upvote it to make it more likely MS will spend time fixing it):
C++ compiler loses member-ness of pointer-to-member-function during template deduction, causes ICE
Then, look at @Ise Wistera's answer which is much simpler and probably doesn't cause this pro... |
6,573,979 | 6,574,118 | boost asio ssl async_write send me mostly gibberish | I'm in the process of converting my non secure socket to ssl, using boost::asio::ssl
While everything was working fine with non-ssl, async_write send me mostly gibberish.
The funny thing is when I put a sleep(1) between every async_write, I get mostly good data, with a little gibberish (something like that "?????@??" )... | The problem is that you are interleaving writes..
while (1) {
boost::asio::async_write(m_socket,
boost::asio::buffer(ss.str().c_str(), ss.str().size()),
boost::bind(&MyClass::done_writing,
... |
6,574,150 | 6,575,261 | Is there a "built in way" to log everything with glog up to the program crash? | I'm interested in using some logging to help me detect potential problems in my code, and to detect where my program crashed. My problem is that lib that I used (google glog) doesn't log the stuff if they occur just before the program crash. So I tried to do something like this (this is template for 3 arguments):
mutex... | I use gflags with glog and if you run --help the option logbuflevel might be what you are looking for.
-logbuflevel (Buffer log messages logged at this level or lower (-1 means
don't buffer; 0 means buffer INFO only; ...)) type: int32 default: 0
|
6,574,269 | 6,574,302 | "Interactive" Sleep in C++ | I started to learn c++ a while ago. I done a lot of console program with Visual Studio 2010 and now I want to make win32 programs. I read a lot of tutorial and I understand the basics now.
I made a button which call another function. The function is doing great everything working. But there are Sleep(x) in this functi... |
In my opinion the problem is Sleep totally pause the application
Yes.
How can I make a Sleep/pause which doesn't freeze the GUI?
Why do you need to sleep in the first place? If the function is misbehaving, you can always run it in a background thread (but be aware that this adds quite a bit of complexity and diff... |
6,574,711 | 6,602,965 | google::dense_hash_map vs std::tr1::unordered_map? | I'm working on a Mobile Game for several platforms ( Android, iOS, and some maybe even some kind of console in the future ).
I'm trying to decide whether to use tr1::unordered_map or google::dense_hash_map to retrieve Textures from a Resource Manager (for later binding using OpenGL). Usually this can happen quite a few... | http://attractivechaos.wordpress.com/2008/10/07/another-look-at-my-old-benchmark/
http://attractivechaos.wordpress.com/2008/08/28/comparison-of-hash-table-libraries/
|
6,574,715 | 6,690,419 | Inserting in a WStandardItemModel is too slow | I am working on a application built uppon WT.
We have a performance problem, as it must display a lot of data in a WTableView associated with a WStandardItemModel.
For each new item to be added in the table it does:
model->setData( row, column, data )
(which happens a few thousand times).
Is there some way to make it ... | WStandardItemModel is a general-purpose model that is easy to use, but it's not optimal for very large models. Try to specialize a WAbstractTableModel; you only need to reimplement three methods and you can read your data from wherever it resides, or compute it on the fly.
It's not normal that a view takes minutes to d... |
6,574,806 | 6,574,856 | C++: How to Encrypt XML Configuration File | I have a proprietary application which uses an xml config. Currently I use boost::property_tree to read the xml file.
I would like to deploy both executable and xml file on a more public system and want to avoid anyone, including that system's administrator, from reading the xml.
Ideally, I would like to maintain the c... | Since you're already using boost, you could always serialize it. If you use binary archives, the file will be essentially unreadable. I guess my follow-up question would be: do you also want it to be secure? Or just unreadable?
|
6,574,814 | 6,576,532 | Using Nsight to determine bank conflicts and coalescing | How can i know the number of non Coalesced read/write and bank conflicts using parallel nsight?
Moreover what should i look at when i use nsight is a profiler? what are the important fields that may cause my program to slow down?
| I don't use NSight, but typical fields that you'll look at with a profiler are basically:
memory consumption
time spent in functions
More specifically, with CUDA, you'll be careful to your GPU's occupancy.
Other interesting values are the way the compiler has set your local variables: in registers or in local memory.... |
6,574,825 | 6,575,052 | Use of constructor in C++ | This is very trivial question regarding the use of a constructor in C++. I will present in the form of an interview dialogue (it was difficult to present it in any other forms)
interviewer - what is a constructor?
me - constructor are special functions which makes sure that all objects are initialized before their use.... | You're overthinking it and allowing the interviewer to confuse you.
Initializing the members of an object is not the same thing as initializing the object itself. Just because the members have sane values doesn't mean the object has been constructed. Until the constructor has completed, the object itself has not been p... |
6,574,852 | 6,574,953 | Are abstract methods and pure virtual functions the same thing? | As far as I know, both abstract methods and pure virtual functions do NOT provide any functionality ... So can we say they're both the same thing ?
Also, suppose a class (not necessarily declared as abstract) contains a number of implemented methods (not abstract or virtual), but contains a pure virtual function. Is th... | Yes, they are the same thing. In C++, an abstract method is just another way of describing the characteristics of a pure virtual function. Both just mean a method with no implementation provided that needs to be implemented in a sub-class before the class can actually be instantiated.
The situation with pure virtual f... |
6,574,914 | 6,574,983 | Speech recognition library for known limited dictionary | I'm looking for a good speech recognition library for a known limited dictionary.
For example a list of names in a phone book, or city addresses.
| I'd suggest looking at Sphinx
An open source toolkit for speech recognition, which includes a recognizer library written in C; an adjustable, modifiable recognizer written in Java
CMU Sphinx Toolkit is actively used in speech recognition research
|
6,575,127 | 6,575,168 | How two convert the following lines in matlab to c++ | I want to convert the following lines written in matlab to c++
int i = 5;
m=cos(pi*theta(i)/180.0);
n=sin(pi*theta(i)/180.0);
Please Help! I am a newbie...
| Though I'm not sure what the theta() function does in MATLAB, I'll make an attempt to answer your question:
The C++ library you are looking for is math.h
It has the sin() and cos() functions in it. List of all functions in math.h refer this page.
Both sin() and cos() function accept one argument of type 'double', which... |
6,575,200 | 6,577,540 | How can I make a scrolling game using Cocos2D without a tile map? | I want to move the background when I tilt the iPhone so it will look like it is moving your character. So if I tilt it forward, my background will go backwards.
| Use a CCParallaxNode.
Here is a good article / blog, about using CCParallaxNode in a 2d scrolling game. In this person's example, they are moving the background on every frame, but you could modify it to only move when tilting the iphone by using the UIAcceleration delegate.
Here is the link: here
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.