question_id int64 25 74.7M | answer_id int64 332 74.7M | title stringlengths 20 150 | question stringlengths 23 4.1k | answer stringlengths 20 4.1k |
|---|---|---|---|---|
4,742,106 | 4,742,134 | c++ implicit conversion rules | I am trying to understand the rules of c++ automatic and explicit conversions in regular or member function calls. I wrote the following code and it fails compilation:
#include <iostream>
#include <string>
using namespace std;
class testExplicit {
public:
int intval;
short shortval;
double... | void getVal(int& a);
This function takes an int by reference. You must pass it an int. This is similar to how if you had a function
void getVal(int* a);
you would need to pass it a pointer to an int (not a pointer to a short or any other type).
One reason for this is that you are able to modify the int from within ... |
4,742,264 | 4,745,450 | Can't call member function from c++/lua function | I've been trying something with lua and c++ for a while now, and all the "easy" functions work, ie can call a c++ function from lua and the other way around, however I have 1 major problem.
its a tiny game/simulator in the making and I wanted to use lua, ode and make my own tiny interface (not a direct one like LuaOde... | In C++, member functions are essentially functions with a hidden parameter. You write:
class Foo {
const int bar_;
public:
Foo(int b) : bar_ { }
int get_bar()
{
return bar_;
}
};
Foo f(5);
f.get_bar();
But, effectively, you actually get:
Foo f = Foo_constructor(5);
Foo_get_bar(f);
I... |
4,742,358 | 4,742,384 | C++/C# exception throwing | In c++, I am able to throw a bare string as an exception, but in c# I must throw an Exception. What is the c# equivalent to throwing a string in c++ ?
For example, in c++ I can throw "something bad happened". In c# this would be ..... ?
| The question is quite obscure, but I think that the problem is "in C++ you can throw strings; what about C#?"
In C# you throw exceptions in a similar manner to what you do in C++; the main difference is that in C# you can only throw classes derived from System.Exception, while in C++ you can throw any type (although of... |
4,742,550 | 4,742,658 | Qt - Maemo application - how to handle CTRL+C? | I wrote a simple application to take pictures in c++ and am guessing I probably should do some cleanup whenever CTRL+C is pressed. I am using QTCreator to write the application along with MADDE, but am not really using any Qt hooks that I know of.
How can I handle CTRL+C in my application?
Thanks,
Walter
| It appears that maemo is based on linux. In linux C programs, you get an OS signal that you must write a handler for. You can go that route, but Qt seems to offer a signal that it fires when a program is ready to quit.. http://doc.qt.nokia.com/stable/qcoreapplication.html#aboutToQuit
Here is some more info about how to... |
4,742,712 | 4,743,239 | How does Windows do its timed GUI animation? | When I use Spy++, I notice that mouse entering a button triggers a series of WM_TIMER .
How is Windows doing this? Is it requesting that the OS notify it or call a function pointer after X milliseconds, or does the widget register its own timer proc?
The reason I want to know this is because I'm building a game gui api... | MS Windows's GUI animation capability is very limited. You can say nothing if you had known real animation capable OS like Mac OS X.
Windows GUI is a composition of various child windows which has own event handler routine and drawing code. Very clumsy and performance inefficient of course, only provide easy access to ... |
4,742,737 | 4,742,952 | C++ class member name lookup issues (regarding the wording of standard n3225) | I am very confused about the standard 10.2/13,
[ Note: Even if the result of name lookup is unambiguous, use of a name found in multiple subobjects might still be ambiguous (4.11, 5.2.5, 5.3.1, 11.2).—end note ] [ Example:
struct B1 {
void f();
static void f(int);
int i;
};
struct B2 {
void f(double);
};
stru... | This:
int B1::* mpB1 = &D::i; // Unambiguous
Is unambiguous because the result is being assigned to a pointer to member of class B.
So it don't matter which i is chosen as the offset is relative to a B member (not the parent D class).
So it is unambiguous to you and me but I don't think the compiler can handle it.
|
4,742,753 | 4,742,854 | FCam - pictures are coming out weird | I am writing an FCam application and any picture I take that has movement has a noticeable distortion. I don't know if I'm using the API correctly or not.
It appears that the image is written from the top down. So, if I walk around with the camera, every row below it is shifted over to the right or left (depending on... | I figured it out, I used stream instead of capture. A good bit of the documentation used stream and I figured I'd use that to follow things exactly. After migrating, it works perfectly now.
Walter
|
4,742,765 | 4,743,047 | reduce singleton object in project | Recently, I refactor code of my project, I found there are lots of singleton object, almost one function one singleton.
For example, I should do period task, so I have a class called CPeriodTask, and have a thread function called ScanPeriodTaskThreadProc and a member variable which save tasks, and CPeriodTask is a sin... | One way to reduce singletons is to create some god-class, a SingletonManager, which can then contain all of the other singletons as instance members. That is, you remove the singleton behavior of the existing singletons in your projects, and this manager then creates/destroys these objects as desired, in the correct o... |
4,743,115 | 4,743,141 | How do I use bitwise operators on a "double" on C++? | I was asked to get the internal binary representation of different types in C. My program currently works fine with 'int' but I would like to use it with "double" and "float". My code looks like this:
template <typename T>
string findBin(T x) {
string binary;
for(int i = 4096 ; i >= 1; i/=2) {
if((x & i) != 0) ... | Succinctly, you don't.
The bitwise operators do not make sense when applied to double or float, and the standard says that the bitwise operators (~, &, |, ^, >>, <<, and the assignment variants) do not accept double or float operands.
Both double and float have 3 sections - a sign bit, an exponent, and the mantissa. S... |
4,743,468 | 4,743,501 | I'm having some scope issue (unidentified identifier error after a for loop) | I'm using visual studio 2008 to do some problems and brusg up on using c++. I have an error and I don't know why it occurs. Here's all the code. The error occurs on the line :
cout<<levels[0][0]->left->value;
with error:
error C2065: 'levels' : undeclared identifier
a shorthand of what's happening to levels is this:
... | This needs to be moved to before the conditional:
binaryValNode*** levels;
|
4,743,559 | 4,744,170 | How to execute child console programs without showing the console window from the Win32 GUI program? | (I've searched SO answers and found no clear solution to this problem.)
I'm working on a MFC GUI program. This program runs various child programs including console program and shell command script(.cmd).
Initially it displayed one GUI window and one console window (created with AllocConsole) because there are many con... | Setup the STARTUPINFO like this for the CreateProcess call:
STARTUPINFO si = { 0 };
si.cb = sizeof(si);
si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
si.hStdInput = GetStdHandle(STD_INPUT_HANDLE);
si.hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE);
si.hStdError = GetStdHandle(STD_ERROR... |
4,743,727 | 4,743,773 | How to Parse A file to block in C++ | I am looking for an elegant way to parse a file to blocks and for each block create a new file , for example :
original file:
line 1
line 2
line 3
line 4
line 5
line 6
line 7
result:
first file:
line 1
second file:
line 2
line 3
third file:
line 4
line 5
line 6
fourth file:
line 7
thanks
| You could use scoped_ptrs to change the output file when the input line does not begin with whitespace:
std::ifstream in("/your/input/file");
boost::scoped_ptr<std::ofstream> out(NULL)
int out_serial = 0;
std::string line;
while(std::getline(in, line))
{
// test: first character non blank
if(! line.empty() && (... |
4,743,814 | 4,743,881 | How is this private variable "not declared in this scope"? | I'm currently trying to learn more about object oriented design in C++ (familiar with Java) and am running into some walls. The project I am trying to put together to learn these principles in a game built using SFML for the graphics and audio. I have the following two files.
WorldObject.h
#ifndef WORLDOBJECT_H
#define... | The function GetGraphics that you define in WorldObject.cpp is not a member of class WorldObject. Use
sf::Sprite WorldObject::GetGraphic()
{
return _sprite;
}
instead of
sf::Sprite GetGraphic()
{
return _sprite;
}
Note that the C++ compiler only complains about the missing WorldObject::GetGraphic if this function... |
4,743,822 | 4,744,138 | Generate include file name in a macro | I'm trying to generate include file name in macro. This is supposed to be legal in C++:
#define INCLUDE_FILE "module_impl_win.hpp"
#include INCLUDE_FILE
this works fine, but as soon as I try to generated file name it failes to compile
#define INCLUDE_FILE(M) M##"_impl_win.hpp"
#include INCLUDE_FILE("module")
Actually... | I'd do this using a helper quoting macro. Something like this will give you what you want:
#define QUOTEME(M) #M
#define INCLUDE_FILE(M) QUOTEME(M##_impl_win.hpp)
#include INCLUDE_FILE(module)
|
4,744,001 | 4,745,221 | Determining template type when accessing OpenCV Mat elements | I'm using the following code to add some noise to an image (straight out of the OpenCV reference, page 449 -- explanation of cv::Mat::begin):
void
simulate_noise(Mat const &in, double stddev, Mat &out)
{
cv::Size s = in.size();
vector<double> noise = generate_noise(s.width*s.height, stddev);
typedef cv::Ve... | The problem is that you need determine to determine type and number of channels at runtime, but templates need the information at compile time. You can avoid hardcoding the number of channels by either using cv::split and cv::merge, or by changing the iteration to
for(int row = 0; row < in.rows; ++row) {
unsigned ... |
4,744,272 | 4,744,365 | Is it okay to use the this pointer? |
Possible Duplicates:
Is there any reason to use this->
When should this-> be used?
When should I make explicit use of the this pointer?
When working with pointers to classes, I like to add a this-> in front of variables in a class to make it clearer that the variable I'm talking about is in the current class, as opp... | Consistency consistency consistency.
I conisder the this-> prefix a valid coding style if you use it throughout your entire project everywhere a member is accessed.
I prefer using a signifying prefix for members, e.g. m_. I feel it is less cutter and less tag soup than the explicit this->:
(alpha-this->gamma > this->a... |
4,744,650 | 4,744,668 | (nil) pointer in C/C++ | I am working on a project and I keep coming across this error that will not allow me to complete the project. When I initialize one of my pointers to point to an object that will be made during the execution of the program and I initialize it to NULL. Then when I check to see what it is set to it returns a value of nil... | %p in printf formats a pointer type. This is going to distinguish a null-pointer and print (nil) because it is a special value in the context of a pointer. If you want to output 0 for a null pointer, cast the pointer to an integer and use %d instead:
printf("Head: %d\n", (int) front);
Original answer as it may still b... |
4,744,656 | 4,744,935 | Functions with C linkage able to return class type? | I observed a function in a dll which has C linkage. This function returns class type. I am not sure how this is made possible as C doesn't understand class.
I wrote a sample dll and program myself and noted that the VC++ compiler shows a warning to this effect but doesn't stop you. The program is able to GetProcAddre... | You are misunderstanding the behavior of extern "C".
It only impacts the name of the function in the object file by preventing name mangling. It does not make a function neither "more C" or "less C++". The only additional limitation which extern "C" adds to a C++ function is that is shall not be overloaded.
|
4,745,150 | 4,779,391 | ACE_SOCK_Dgram::open() and errno | I tried to open already opened UDP port and ACE_SOCK_Dgram::open() failed.
As expected, strace shows that bind() failed and errno is set to EADDRINUSE.
To see what error happen, I used ACE_OS::last_error(), but it's not updated.
I'd like to give informative error to user that the port already in use, instead of some ge... | I found the problem. I used ACE_OS::last_error() to macro (yes, macros are bad), which expanded to several links. One of the lines executed system call, and therefore value of errno changed
|
4,745,184 | 4,745,332 | Exception with CFileDialog (MFC) | I had the following lines of C++ code in my program
CFileDialog dialog(true);
CString strFileName=L"";
INT_PTR nResult = dialog.DoModal();
if(nResult == IDOK)
// Exception spotted here
// Debug information gives me --> dialog = {CFileDialog hWnd=0x00000000}
// What's the heck?
strFileName=dialog.GetFolderPat... | You need to call
DWORD WINAPI CommDlgExtendedError(void);
after the instantiation of CFileDialog to check that it is instantiated OK and if not why not.
Edit:
You are not able to call GetFolderPath after the dialog is closed which it is when DoModal() returns. Look at this MSDN page under remarks on how to pass a buf... |
4,745,201 | 4,745,250 | C++ - The name of the array and the starting address | In the C++ Without Fear: A Beginner's Guide That Makes You Feel Smart in Chapter (7), it mentions the following:
char str[10] = "Hello!";
This declaration creates the array shown, and associates the starting address
with str. (Remember that the name of an array always translates into its starting
address.)
What is mea... | It means that 'str' can be treated as a starting address where the "Hello" string is stored.
Consequently str + 1 is the address where the second character of the string is stored.
| str | str+1 | str+2 | str+3 | str+4 | str+5 |
| str[0] | str[1] | str[2] | str[3]| str[4]| str[5] |
| H | e | ... |
4,745,583 | 4,773,036 | VS2008 to VS 2010 migration - a breaking change? | I encountered a problem when migrating our C++ code from VS2008 to VS2010. I can't find an explanation for the reason of it so far and will appreciate your help.
We have a custom memory allocator and it resides in a dll. In the rest of the code we use the preprocessor to redirect the allocations to our functions. Thie ... | After some investigation using the /P option to create the preprocessor files and studying them I've found the root cause of the issue.
The xdebug header, which describes itself as "debug heap support header for Microsoft", contains the following lines:
#pragma push_macro("free")
#undef free
which obviously defeat our... |
4,745,671 | 4,745,735 | Is given name is file or directory while looping a directory structure in C++ | In C++, how can we find programatically while looping thourhg a directory structure if it is subdirectory or is it a file. This i want to perform with functions avaialble in C++ standard, with out using Boost or system call and implementaiton should be portable.
| Without a portable library (boost comes to mind) you will not be able to do this portably (pun may be intended). The c++ standard does not have this type of functionality.
Why do you not want to use boost?
|
4,745,821 | 4,750,565 | Making an event like subscribing system for C++ * chars | For simple data like ints or constants something like this would work
#include <iostream>
#include <vector>
using namespace std ;
typedef void FuncInt (int) ;
class GraphElementProto {
public:
void add (FuncInt* f)
{
FuncVec.push_back (f) ;
} ;
void call()
{
for (size_t i = 0 ; i < FuncVec.size() ; i++)
... | Consider the similarities between each node of the graph that you describe and create a class for them (class GraphElement below). It should encapsulate its relationship to its child nodes, and it should do something locally with any incoming messages (function localAction). You should then derive classes that repre... |
4,745,858 | 4,746,020 | std::cin.getline( ) vs. std::cin | When should std::cin.getline() be used? What does it differ from std::cin?
| In case with char*, std::cin.getline getting line, instead of std::cin getting first word.
|
4,745,897 | 4,746,019 | Spoofing file descriptor in C++ | I'm writing an library which will transmit data via multiple routes; TCP, UDP, RDMA (Remote Direct Memory Access) and occasionally via a straight function call where client/server are rolled into a single binary.
I'll be handling TCP, UDP, RDMA with file descriptors and have been looking at how I could achieve somethig... | You could use OS-specific calls to get file descriptors, if you want to. For example, the Unix open function would do just what you want.
Alternatively, you could make your code to read and write data part of a polymorphic class hierarchy, which would let you use file descriptors where appropriate and the streams libr... |
4,745,908 | 4,746,089 | Writing popen() output to a file | I've been trying to call another program from c++, and save the stout of that program to a text file. popen() seems to be the appropriate function, but saving it to a text file isn't working.
ofstream delaunayfile;
delaunayfile.open ("triangulation/delaunayedpoints.txt");
FILE *fp;
fp = popen("qd... | There are two ways to do this: The simple way
int rc = system("qdelaunay < triangulation/rawpoints.txt >triangulation/delaunayedpoints.txt");
and the slightly more elaborate way, using fork(), dup2() and execve(), the latter working without a shell interpreter installed on the system. Given that this looks like you ar... |
4,745,991 | 4,746,087 | Help needed in converting a few lines of ruby code to c++! | I have to convert the following code into Qt c++
So I need to understand what these lines to.
@key in this code is a pem key file contents by openssl
key = KEY+@key.public_key.to_der
so i think this is converting that key to der format and then combining it with KEY.
is it right?
whats does this do? to_sizet(key.siz... |
so i think this is converting that key to der format and then combining it with KEY. is it right?
Yes.
whats does this do? to_sizet(key.size) As you can see the function returns [num].pack('V'). But i dont know wht does it do? I mean [num].pavck('V'). what is it?
Well, just have a look at what the documentation on ... |
4,746,052 | 4,746,070 | Odd result when reading first byte of a PNG header | I'm trying to read the header from a PNG file.
The result should be
Dec: 137 80 78 71 13 10 26 10
Hex: 89 50 4E 47 0D 0A 1A 0A
However, I get
Dec: 4294967 80 78 71 13 10 26 10
What am I doing wrong?
Code:
char T;
pngFile = fopen(Filename, "rb");
if(pngFile)
{
fread(&T, 1, 1, pngFile);
fclose(pngFile);
pri... | 137 is too big for signed char - use unsigned char instead...
see this link for limits of data types.
|
4,746,135 | 4,746,206 | std::cin.getline(f_name, 10) | If I have for example the following statements:
char f_name[11];
std::cin.getline(f_name,10);
Does thia mean:
* Declare a string with 11-characters wide?
* Read the entered line and pass it as the value for "f_name"?
Thanks.
| Yes, you are correct!
char f_name[11];
declares the array f_name with 11 elements.
std::cin.getline(f_name,10);
prompts for the value to be entered, which then stores it in f_name[11].
|
4,746,139 | 4,746,214 | What are the most common configurations where pointer writes are not atomic? | I am interested in multithreading. There are a lot of gotchas in the field, for example, there is no guarantee that pointer writes are atomic. I get this, but would like to know what are the most popular current configurations when this is actually the case? For example, on my Macbook Pro/gcc, pointer writes definitely... | This is mostly a problem for CPU architectures where the pointer width is larger than the width of the CPU architecture. For instance, on ATmega CPUs, an 8-bit architecture, the address space is 16-bit. If there aren't any specific instructions to load and store 16-bit addresses, at least two instructions are needed to... |
4,746,208 | 4,746,246 | C++ - return 0 vs. return -1 |
Possible Duplicate:
What should main() return in C/C++?
In C++, return 0 tells that the program has ended successfuly.
What about return -1? Does it break (halt) the program?
| Short answer: no. Returning anything except 0 just means that there was an error.
|
4,746,216 | 4,746,274 | unresolved external symbol in c++ | I have defined a global variable in a c++ file. eg: bool _variable =1;
Now i use this variable in other c++ file using : extern bool _variable.
But i am getting the error error LNK2001: unresolved external symbol
"bool _variable" (?_variable@@3_NA).
How can i resolve this error??
| It means the linker cannot find the definition of such variable.
Are you sure you wrote it in the same way anywhere?
Are you sure the c++ file containing the definition gets compiled and linked with the others when you're getting such error?
Are you sure the namespace where such variable is defined is the same?
|
4,746,399 | 4,746,506 | What is the most efficient way to determine if a point is in any number of boxes | I know how to check if a X,Y point is a single rectangular region, but say I have multiple regions that can potentially overlap ( the regions would have X,Y,Width,Height,Z-index ( or x1,y1,x2,y2 if that's easier -- I am not fussed on how I store that, if it's relevant )
Are there any efficient algorithms to determine i... | You could store your regions into a Quadtree (or Octree if 3D). This would help you to reject most of the regions before getting into the real collision-test.
If you have multiple layers, simply have a quadtree per layer and use the relevant one according to the layer in which your point lies.
|
4,746,588 | 4,746,916 | How can I set the default file type for a CFileDialog? | I am using CFileDialog for displaying the open file dialog. I have set the filter as follows:
static TCHAR BASED_CODE szFilter[] = _T("Chart Files (*.xlc)|*.xlc|")
_T("Worksheet Files (*.xls)|*.xls|Data Files (*.xlc;*.xls)|")
_T("*.xlc; *.xls|All... | You're looking for the SetDefExt function. This allows you to specify the default file extension for an open/save file dialog box. Remember that the string you specify should not contain a period (.).
Of course, you could also just specify this in the constructor. The second parameter is the default extension (lpszDefE... |
4,746,631 | 4,746,927 | Passing from a DOMNode* to a DOMElement* in Xerces-C | I have a c++ application that manipulates xml.
Well, at a certain point of my application I get a DOMNode* and then I attach it to an element as a child.
Well the problem is that I would like to add parameters to that node... well it is a node so it is not an element... only elements have parameters...
This is my code:... | ok I discovered it...
Just re-cast the node to element and it is done... DOMNode is a pure virtual class and it is parent of DOMElement... so it is correct and it is also the way to do things (logically speaking).
DOMElement* = dynamic_cast<DOMElement*>(node);
:)
|
4,746,668 | 4,746,817 | API to detect usb device | Can some one please point to any API or links where i can detect a USB device and other interfaces to transfer data into it.I am trying to do this on linux
| Take a look at libusb - it's cross-platform.
|
4,746,679 | 4,746,737 | Is there an established pointer value for a released pointee? | Some programmers like to set a pointer variable to null after releasing the pointee:
delete ptr;
ptr = 0;
If someone tries to release the pointee again, nothing will happen. In my opinion, this is wrong. Accessing a pointer after the pointee has been released is a bug, and bugs should jump in your face ASAP.
Is there ... | No. Test for "0" when trying to delete something if you really want to warn or error out about it.
Alternatively, during development you could omit ptr = 0; and rely on valgrind to tell you where and when you're attempting a double free. Just be sure to put the ptr = 0; back for release.
Edit Yes, people I know C++ doe... |
4,746,707 | 4,746,727 | Bits needed to change one number to another | Say I have two positive numbers a and b. How many bits must be inverted in order to convert a into b ?
I just want the count and not the exact position of the differing bits.
Lets assume a = 10 ( 1010 ) and b = 8 ( 1000 ). In this case the number of bits that should be inverted equals 1.
Any generalised algorithm?
| The solution is simple
Step 1 ) Compute a XOR b
Step 2 ) Count the number of set bits in the result
Done!
|
4,746,778 | 4,746,850 | STL for_each complaining about argument list | As part of a homework assignment, we are supposed to map the occurrence of each character in a map. Our function is supposed to use std::for_each and pass in the character to be evaluated.
My function is:
std::for_each(document_.begin(),
document_.end(),
std::mem_fun(&CharStatistics::fill... | CharStatistics::fillMap is not a function taking 1 argument. it's member function and so it has implicit first argument - pointer to class instance.
in code:
std::for_each(document_.begin(),
document_.end(),
std::mem_fun(&CharStatistics::fillMap));
for_each don't know on which instance yo... |
4,746,980 | 4,747,014 | C++ - Quitting a program | In the C++ Without Fear: A Beginner's Guide That Makes You Feel Smart book in chapter(8), part of a code trying to display a text file is the following:
while(1)
{
for(int i=1; i <= 24 && !file_in.eof(); i++)
{
file_in.getline(input_line,80);
std::cout<<input_line<<std::endl;
}
if(file_... | Because input_line is string ( array from chars), so input_line[0] gets the first letter - this is in case, that the user write "quit" or "Quit", not just "Q"
std::cin >> c; would be correct, if you enter just one char and press Enter
|
4,747,071 | 4,747,088 | Standard Library for C |
Possible Duplicate:
C Analog To STL
Is there something like STL for C.
| You can have a look at the glib, which provides lots of interesting features
|
4,747,137 | 4,747,872 | Calling Objective-C method from C++ method? [2] | i found a great post Calling Objective-C method from C++ method?
however, i have to 2 questions, which makes me overcoming this issue very problematic :
note that i have made a change to MyObject-C-Interface.h
#ifndef __MYOBJECT_C_INTERFACE_H__
#define __MYOBJECT_C_INTERFACE_H__ 1
struct CWrap {
void * myObjectIn... |
i mean, i cannot cast to MyObject or otherwise let the compiler know, what method to call
Why not?
Your C++ wrapper class must be in an Objective-C++ file (usually denoted with the .mm) extension. Then, because you even have to declare your private instance variables in the class declaration, you need a private memb... |
4,747,263 | 4,747,399 | Insert map into vector fails second time | I have an error I couldn't figure where it occues on the following:
I'm acutally using a map with vectors in it:
map<vector<string> , vector<string> > parameterMap;
because I need a few of them (how many is decided on runtime) I put them into a list (vector):
vector declaration on head of method:
vector<map<vector<st... | I would like to see a test where you output something from your collections to see if you are seeing what you think you should see. Actually why not write a proper unit test?
You are passing a lot of collections around by value. This can be quite expensive, but in addition, you may be updating something that is a copy ... |
4,747,409 | 4,747,429 | How to associate to a number another number without using array | Let's say we have read these values:
3
1241
124515
5322353
341
43262267234
1241
1241
3213131
And I have an array like this (with the elements above):
a[0]=1241
a[1]=124515
a[2]=43262267234
a[3]=3
...
The thing is that the elements' order in the array is not constant (I have to change it somewhere else in my program).... | You need to use some sort of dynamic array, like a vector (std::vector) or other similar containers (std::list, maybe, it depends on your needs).
Such data structures are safer and easier to use than C-style array, since they take care of memory management.
If you also need to look for an element in O(1) you should con... |
4,747,597 | 4,747,665 | How can I fix the error in this Pthread example? | I did all the necessary configurations, like including Pthread library and header files...
The error is:
error C3867: 'FunctionClass::calledfunction': function call missing argument list; use '&FunctionClass::calledfunction' to create a pointer to member
Here's the example that causes the error:
class FunctionClass
{
... | You cannot use non-static member functions as callback.
Use a free function or a static member function as third parameter of pthread_create.
Edit to reflect OP's comment:
If you need to call a function member of FunctionClass for a specific FunctionClass object (obj in your example) the common way is that of calling ... |
4,747,646 | 4,753,558 | Adding a stylesheet declaration in my xml using Xerces-C | I have an application in c++ using Xerces-C as main xml manipulation library.
I have my DOMDocument* and my parser and I want to set declarations.
I do the following:
parser->setValidationScheme(xercesc::XercesDOMParser::Val_Never);
parser->setDoSchema(false);
parser->setLoadExternalDTD(false);
I want to add:
<?xml-st... | You'll need to use the createProcessingInstruction on the DOMDocument
http://xerces.apache.org/xerces-c/apiDocs-3/classDOMDocument.html#ce898787ba20c00c85be63f28a358507
Once you've created it, append it to the DocumentElement.
|
4,747,706 | 4,747,722 | Standard or custom exception in C++? | For a library code, is it better practice to create and throw custom exception class (library::Exception), or just throw standard exceptions (runtime_error, invalid_argument, etc.)?
| It's usually better to specialize (inherit) a standard exception and throw it.
This way it'll be possible to catch it as a generic exception just by catching a std::exception, but you could also catch specifically your custom exception type if you need more specialized code.
Also see this C++Faq about what to throw.
|
4,747,720 | 4,747,859 | Determining Purpose of operator[] Usage | Let's say I have something like the following method in my container class:
Datatype& operator[](const unsigned int Index) // I know this should use size_t instead.
{
return *(BasePointer + Index); // Where BasePointer is the start of the array.
}
I'd like to implement some sort of bounds-checking for the MyInstan... | Sketch:
return a proxy object instead of the actual data entry. The proxy object then defines operator = to handle the assignment case, and an implicit conversion operator for the reading-out case.
template <typename T>
class AccessorProxy {
friend class Container<T>;
public:
AccessorProxy(Container<T>& data, uns... |
4,747,920 | 4,748,097 | OpenCV rgb value for cv::Point in cv::Mat | I've looked at different questions already here on StackOverflow, but none seems to helps.
What I want to do is quite simple: I have a cv::Point and I need to get the RGB value for the pixel at that point in a cv::Mat so that I can compare it with a stored RGB value.
Now this should be very easy but I've tried 1001 dif... | That's really easy. However the documentation of OpenCV is good at hiding the simple answers.
Here is example code:
cv::Mat3b image = imread(filename);
cv::Point point(23, 42);
cv::Vec3b template;
template[0] = 128; template[1] = 12; template[2] = 64;
const cv::Vec3b& bgr = image(point);
if (bgr[0] == template[0] && b... |
4,747,934 | 4,748,042 | C++ : Catch a divide by zero error | Here is a simple piece of code where a division by zero occurs. I'm trying to catch it :
#include <iostream>
int main(int argc, char *argv[]) {
int Dividend = 10;
int Divisor = 0;
try {
std::cout << Dividend / Divisor;
} catch(...) {
std::cout << "Error.";
}
return 0;
}
But th... | It's not an exception. It's an error which is determined at hardware level and is returned back to the operating system, which then notifies your program in some OS-specific way about it (like, by killing the process).
I believe that in such case what happens is not an exception but a signal. If it's the case: The oper... |
4,748,083 | 4,748,291 | When should you use constexpr capability in C++11? | It seems to me that having a "function that always returns 5" is breaking or diluting the meaning of "calling a function". There must be a reason, or a need for this capability or it wouldn't be in C++11. Why is it there?
// preprocessor.
#define MEANING_OF_LIFE 42
// constants:
const int MeaningOfLife = 42;
// co... | Suppose it does something a little more complicated.
constexpr int MeaningOfLife ( int a, int b ) { return a * b; }
const int meaningOfLife = MeaningOfLife( 6, 7 );
Now you have something that can be evaluated down to a constant while maintaining good readability and allowing slightly more complex processing than jus... |
4,748,179 | 4,750,731 | How to get samples from a RTP packet carrying PCMU? | I have a pointer in a C++ code to a RTP packet (char* packet) carrying PCMU. How do I extract the samples so that I can dump to a file to play it? I've been able to extract the sequence number correctly, but how do I extract the samples to play them?
Thanks!
| I've been able to unpack data. The problem was related to the way I was reading the bits of the packets. Reading the CC and removing the header is sufficient to get the payload. According to the documentation it may be necessary to remove the padding as well.
|
4,748,391 | 4,748,431 | string causes a memory leak? | Visual C++ found memory leaks in my code so I whittled it down to as simplest test case as I could and got this:
#define _CRTDBG_MAP_ALLOC // required
#include <stdlib.h> // to enable MSVC++
#include <crtdbg.h> // memory leak detection
#include <string>
using namespace std;
int main() {
string... | You're running _CrtDumpMemoryLeaks() too early and it reports the string body as a leak. Only run it after all the local objects could have been destroyed.
Either wrap all meaningful work in a separate function
void doStuff()
{
string variable;
}
or add nested scope:
int main()
{
{
string variable;
... |
4,748,456 | 4,749,571 | Catching the output of a console app in visual studio | I have a simple console app providing me with some pre-build functionality in Visual Studio 2010. It goes on to spawn other child processes (though waits for the termination of those child processes.
When I run the app outside visual studio all its messages, etc, appear in the console window (ie stdout). However when ... | I believe you need to make explicit handles for the child process to hook them up. MSDN has an article on it (or several), see http://msdn.microsoft.com/en-us/library/ms682499%28v=vs.85%29.aspx for example.
Child processes inherit open object handles, but have their own stdin/stdout/etc. handles, unless you go through ... |
4,748,477 | 4,748,504 | I want to learn Visual C++ game development? | I want to start learning game programming on windows platform using Visual studio C++ can anybody guide me how to start how to develop a simple game what other libraries i need to add and other tools can any one guide me ??
hoping for quick and positive response
| Start here : http://nehe.gamedev.net/
It's about OpenGL. Then read other gamedev.net sections :D
|
4,748,669 | 4,748,721 | Destructor of class with pointer array C++ | If I have a class with an array of pointers to another class Vehicle :
class List {
public:
//stuff goes here
private:
Vehicle ** vehicles;
}
If I now write the destructor of the class List, do I manually iterate over the array (I know how many items are in the array) and delete every pointer t... | You have to delete all the entries in the array AND delete the array.
There are methods in C++ (STL) to avoid this: use a vector, so you don't have to delete the array. Use scoped_ptr/shared_ptr per Vehicle, so you don't have to delete the vehicles.
|
4,748,731 | 4,749,105 | access UNC drive/remote network drive in c++ | I'm trying to access a network drive (\servername or \ipadress). The idea is that the drive is accessed only through the application and the login on the network drive is supposed to be used only by the application.
So far i have found only the WNetUseConnection Function (http://msdn.microsoft.com/en-us/library/aa38548... | I believe that you need to clear the NETRESOURCE structure (or directly initialize all members). A memset prior to setting the other values may help:
memset( &nr, 0, sizeof( nr ));
In addition, you need to specify the share name as pointed out in the comments:
wchar_t remoteName[] = L"\\\\server\\share";
Also, if yo... |
4,748,772 | 4,748,869 | Visual C++ 2010: what major c++0x (and STL) features are still missing? | is there atomic_ operations? thread? bind? what is still missing?
EDIT: i'm interesting in c++0x and its STL
| There is no definitive list, but here are some resources that show what’s missing:
Apache C++0x Compiler Support Report
Scott Meyers’ Summary of C++0x Feature Availability
Note on the second link you should click on the tabs on the bottom of the page to see the reports.
Generalized binders, from TR1, are in MSVC 10.... |
4,748,998 | 4,749,098 | Why is my c++ clock() based function returning a negative value? | I am still new to C++, is the clock function absolute (meaning it counts how long you sleep for), or is it how much time the application actually executes for?
I want a reliable way to produce exact intervals of 1 second. I am saving files, so I need to account for that. I was returning the runtime for that in millis... | clock() returns the number of clock ticks elapsed since the program was launched. If you want to convert the value returned by clock into seconds divide by CLOCKS_PER_SEC (and multiply for the other way around).
There is just one pitfall, the initial moment of reference used by clock as the beginning of the program exe... |
4,749,026 | 4,749,129 | Does anyone know where the QT (4.7) headers and libraries are located (i.e. paths) on the mac? | For all my trying, I just can't find the damn things.
Thanks,
Ben.
| For me, it looks like this:
/usr/include
/Library/Frameworks
/Developer/Tools/Qt
/usr/local/Qt4.7
/Developer/Applications/Qt/plugins
I found this in the file qtdirs.out which happened to lie in my root. Not sure about when it was generated, either during Qt's installation or during PyQt's installation.
|
4,749,074 | 4,749,771 | How do I get a print of the functions called in a C++ program under Linux? | What I want is a mix of what can be obtained by a static code analysis like Doxygen and the stackframe you can see when using GDB. I know which problematic function I'm debugging and I want to see the neighbourhood of the function calls that guided the execution to this function call. For instance, running a simple Hel... | From reading the question I understand that you want a list of all relevant functions executed in order as they're executed.
Unfortunately there is no application to generate this list automatically, but there are helper macros to save you a lot of time. Define a single macro called LOGFUNCTION or whatever you want an... |
4,749,150 | 5,832,224 | Windows phone 7 native code support | 2 questions:
Can someone tell me if unmanaged c++ code will
be supported in future versions of Phone 7 OS for all developers?
What are MS reasons for not
supporting unmanaged c++ code?
| This answer is purely speculative, but I feel that most others who have answered this question miss the point by a long shot. Let's for a moment assume that this is not a vindictive decision by Microsoft, but instead actually a very well thought out engineering decision that has absolutely nothing to do with content re... |
4,749,163 | 4,749,275 | C++ list remove duplicates strings | I have a little problem when using lists.
What I have: I am reading lines from a chatbox where new lines of text come now and then.
I always fetch the last 20 lines from the box, then i want to compare them to all the lines i have fetched before. If a new line is discovered it is sent to an external function which dis... | You must never modify a list (or pretty much any other container) while iterating over it. That's your immediate problem.
A more interesting problem is why you're doing it like this in the first place. Isn't there a way to get sequential numbers on the lines, or maybe timestamps, so you could just compare those?
|
4,749,211 | 4,749,346 | MySQL Transactions using C++? | How would I go about wrapping an amount of queries in a transaction in C++? I'm working on Ubuntu 10, using this file:
#include "/usr/include/mysql/mysql.h"
with C++ to interact with a MySQL database.
EDIT: Right now I'm running queries through a small wrapper class, like so:
MYSQL_RES* PDB::query(string query)
{
in... | You could always just run START TRANSACTION / COMMIT / ... manually.
Another way would be to create a wrapper class which runs START TRANSACTION in the constructor, provides commit/rollback functions and, depending on your use case, does a rollback upon destruction.
|
4,749,293 | 4,850,365 | Rapidxml is not compiling on Visual Studio 2010. What am I doing wrong? | I am working on switching XML parsers from TinyXml to RapidXml in our codebase.
However, RapidXml does not seem to compile with Visual Studio 2010.
Basically, in the header file I am doing
#define RAPIDXML_NO_EXCEPTIONS
#include "RapidXml/rapidxml.hpp"
using namespace rapidxml;
And in the implementation
xml_document<>... | Here is my actual problem:
As part of some memory debugging, I overloaded new with a version that does not support placement new. However, rapidxml does require placement new to work, so that is where those errors came from. Oh my.
|
4,749,334 | 4,761,778 | 64bit architecture - character pointer truncated while returning from function | Environment:
Windows x64 bit with 5GB RAM. My binary is a 64bit one built with compiler of version - "Microsoft (R) C/C++ Optimizing Compiler Version 14.00.50727.762 for x64"
Environment setting:
Microsoft suggests to set the below registry key to test 64 bit applications and I have set the same in my box. The proble... | Two points about style, which could help to diagnose this kind of problems. As you use malloc I suppose that it is compiled as a C program. In that case, do not typecast when it is not necessary. Excessive typecasts may suppress the warnings telling you that you have not correctly declared your functions. If there is n... |
4,749,338 | 4,749,402 | strange template problem | I have the following function defined:
template<class KEY, class VALUE, class HASH_FUNCTION,
class COMPARATOR_FUNCTION, class GREATER_THAN_FUNCTION>
bool Test3(size_t szCount, double dLoadFactor, vector<KEY>& vVals,
const HASH_FUNCTION& hf, const COMPARATOR_FUNCTION& cf,
const GREATER_... | Looking at the function declaration, it has a template parameter V which isn't used anywhere in the actual parameter list. So it can't be deduced automatically at the call site.
Try just defining it as this instead:
template<class K class HF, class CF, class GF>
bool Test3(size_t szCount, double dLoadFactor, vector<K>&... |
4,749,790 | 4,749,832 | Won't match template function | In:
#include <string>
void f( char const*, char const* = "" ) {
}
template<class StringType1,class StringType2> inline
void g( StringType1 const &s1, StringType2 const &s2 = "" ) {
f( s1.c_str(), s2.c_str() );
}
template<class StringType> inline
void h( StringType const &s1, StringType const &s2 = "" ) {
f( s1.c... | The compiler has no idea what StringType2 is supposed to be. You would need to call it with something like:
g<std::string, std::string>( s );
to get it to work correctly.
|
4,749,863 | 4,750,139 | Variadic templates and copy construction via assignment | Consider this minimal example:
template <typename T, typename U>
struct foo {};
template <template <typename...> class Bar>
struct converter
{
template <typename... Args>
converter(const Bar<Args...> &);
};
int main()
{
converter<foo> c(foo<int,double>()); // This works.
// converter<foo> c = foo<in... | Yes, this is supposed to work. It's a GCC error. GCC doesn't support C++0x variadic templates to the fullest yet (and to be fair, the specification is still constantly changing in details).
What you say "This works" is really declaring a function; it doesn't initialize an object, which was what you intended.
For what ... |
4,749,975 | 4,750,127 | Returning C++ polymorphic objects (interfaces) | I'd like to know what is considered nowadays the best practice when returning a pointer to a polymorphic object from a function, for example when using factories. If I transfer the ownership, should I return boost::unique_ptr<Interface>? What should I return if I don't transfer the ownership (e.g. returning a reference... | Use ::std::auto_ptr for now, and when C++0x is available, then switch to ::std::unique_ptr. At least in the factory case where you are handing ownership back to the caller.
Yes ::std::auto_ptr has problems and is ugly. Yes, it's deprecated in C++0x. But that is the recommended way to do it. I haven't examined ::boo... |
4,750,048 | 4,750,488 | Find out png color type using png++ | I'm using png++, which is working ok, but you need to set the pixel type as a template parameter:
png::image< png::rgb_pixel > image("input.png");
The problem is I don't know at compile time whether it is rgb, rgba etc. Can't seem to find a way to get png++ to tell me what info is actually in the png.
Any ideas?
Than... | Try using a reader. Then check out the member functions of it's base class, io_base. I think it has what you're looking for.
|
4,750,125 | 4,750,155 | when declaring an object how do you specify the no name if it's ambigous | I have an ambigous variable delcaration, e.g.:
Class myClass;
blah.h : error C2872: 'Class ' : ambiguous symbol
could be 'foo.h(30) : Class '
or 'foo2.h(106) : MyNamespace::Class '
How do I specifically declare the variable myClass to be of the former class declared in foo.h with no namespace?
Thanks in adva... | You can use the fully qualified class name which always starts with ::
::Class myClass;
|
4,750,293 | 4,774,722 | Problems with cudaMalloc and "out of memory" error | Are there any restrictions for allocating device memory despite not exceeding available memory?
I get following error after trying to allocate 64MB:
cudaSafeCall() Runtime API error : out of memory.
However, according to cuMemGetInfo there is over 200MB left.
Here is scenario:
size_t size = 4096 * 4096 * sizeof (float... | As Thomas pointed out the problem is memory fragmentation. (Confirmed by experiment. I didn't find reliable source to link)
|
4,750,515 | 4,750,556 | Error 2027 when trying to use QT's Network Library | I used the advice from How can i get content of web-page to download a page using QT QNetworkAccessManager. Here is the code I have:
Header:
class WebAccessor : public QObject{
Q_OBJECT
public:
WebAccessor();
void fetch(const QString &url);
public slots:
void replyFinished(QNetworkReply *reply);
private:
QNetwork... | What about:
#include <QNetworkReply>
|
4,750,549 | 4,750,662 | OpenGL Render To Texture Transparency Problem | I build a "postprocessing pipeline" which collects rendercalls and puts them into a texture. After all postprocessing effects are rendered, I put all the results together. And here is my problem:
At the beginning, I clear the buffer with glClearColor(0,0,0,0). Then I call the draw calls. The comes when an object has a ... | You could try using premultiplied alpha when drawing. Basically, ensure that all your colour values are already multiplied by the alpha value. Then, instead of
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
you would use
glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
The pixel of the texture would then be 0.25, 0.2... |
4,750,672 | 4,751,542 | any C/C++ open-source RTMP streaming server? | do you know any C/C++ open-source RTMP streaming server?
| Yes.
http://www.rtmpd.com/
Excellent project.
|
4,750,710 | 4,750,886 | Operator priority on overloading | I am trying to make a C++ compiled model for simple SQL commands. For example this could be a part of my main function which i must be able to handle :
CREATE_TABLE(books) [ // create("books");ovr[
COLUMN(c1) TYPE(string), // "title string",
COLUMN(c2) TYPE(string), // "author string",
... | Your expression would be compiled to something like the following, which might explain the evaluation order:
CREATE_TABLE(books).operator[](
COLUMN(c1) TYPE(string).operator,(
COLUMN(c2) TYPE(string).operator,(
COLUMN(num1) TYPE(int)
)
)
);
or
CREATE_TABLE(books).operator[](
op... |
4,750,783 | 4,750,816 | Strange memory management issues in C++ (from a beginner, at least) | I'm new to C++, I have lots of Objective-C experience.
I'm trying to have an array of c-strings (that is char **) as an instance variable in my class, which gets allocated and filled in my constructor, and then in another member function I want to print out the whole "grid".
The allocation works, I fill up my array wit... | Red flag:
_bitmap = (char **)malloc(sizeof(char) * height);
should be
_bitmap = (char **)malloc(sizeof(char*) * height);
You want a pointer to a char*, not a pointer to a char.
|
4,750,789 | 4,778,161 | MFC Menu Drop Down (Screenshot included) | I'm having difficulties with an MFC application menu drop down. I want the drop down to display all items when it is clicked. Instead it displays arrows which the user must click in order to show the drop down items.
See the pic below. Any help would be appreciated. Thanks!
| I believe this is a feature of the MFC feature pack where the menu will hide rarely used items. You should be able to disable this feature using the CMFCMenuBar::SetShowAllCommands method.
|
4,750,880 | 4,750,937 | Can I treat a specific warning as an error? | The following is a simplified version of a pattern I sometimes see in my students' code:
bool foobar(int a, int b)
{
if (a < b) return true;
}
The real code is more complicated, of course. Visual Studio reports a warning C4715 (not all control paths return a value), and I would like to treat all warnings C4715 as ... | This should do the trick: #pragma warning (error: 4715).
Or the /we4715 command line option (see /w, /W0, /W1, /W2, /W3, /W4, /w1, /w2, /w3, /w4, /Wall, /wd, /we, /wo, /Wv, /WX (Warning Level) (courtesy of Tom Sigerdas)).
|
4,750,897 | 4,751,229 | Get file handle to running executable | I am trying to call GetFileInformationByHandle on the executable of my own running program. This means I'll need to get a file handle to the .exe that started my program. Is there any way to do this?
Failing that, is there any way to get the nFileIndexHigh and nFileIndexLow for a running executable?
| Here it is a way to do this. I hope this helps:
#include <Windows.h>
#include <iostream>
using namespace std;
//declare a BY_HANDLE_FILE_INFORMATION structure
BY_HANDLE_FILE_INFORMATION fileinfo;
int main()
{
// clear everything in the structure, this is optional
ZeroMemory(&fileinfo, sizeof(BY_HANDLE_FILE_IN... |
4,751,091 | 4,783,797 | How to go about searching for a player models in COD with OpenCV | I am attempting to create a program that can find human figures in video of game play of call of duty. I have compiled a list of ~2200 separate images from this video that either contain a human figure or do not. I have then attempted to train a neural network to tell the difference between the two sets of images.
Then... |
Using the raw intensities as the feature vector is not going to work1. There is too much variation induced by lighting etc.
A good feature to look at as a first step would be HOG. opencv 2.2 has a GPU (cuda) version of a detector it that is fast.
Neural networks are maybe not the best way to go. Usually you'd use a SV... |
4,751,411 | 4,751,540 | Can You Prevent istream or stringstream From Swallowing Newlines? | For my homework project, I had to read in a book and then parse it word for word, listing occurrences of each word and the respective line it was found at. I'm done with the project now and looking to optimize my code by reading other people's use of the STL (we are supposed to rely heavily on the STL for this assignme... | You can parse the words line by line:
std::string line;
vector<string> words;
while(std::getline(ifs, line))
{
std::stringstream linestream(line);
copy(std::istream_iterator<std::string>(linestream),
std::istream_iterator<std::string>(),
std::back_inserter(words));
++lineCount;
}
|
4,751,446 | 4,751,467 | Alternative of strcpy in c++ | In C i used strcpy to make a deep copy of a string, but is it still 'fine' to use strcpy in C++ or are there better alternatives which i should use instead ?
| In C++ the easiest way is usually to use the std::string class instead of char*.
#include <string>
...
std::string a = "Hello.";
std::string b;
b = a;
The line "b = a;" does the same thing you would usually do with strcpy.
|
4,751,510 | 4,751,786 | G++ 4.4 "uninitialized" variables | I am using g++ on Ubuntu 10.10(64-bit) if the OS is at all relevant for the matter.
I saw something strange so i decided to check and for some reason this code
#include <iostream>
int main()
{
int a;
std::cout << a << std::endl;
return 0;
}
always prints 0. Obviously g++ does auto initialization of unin... | GCC does not initialize uninitialized variables to 0. It's just a case that a is 0.
If what you want to do is to receive warnings when you use uninitialized variables you could use GCC option -Wuninitialized (also included by -Wall).
However it can't statically spot any possible usage of uninitialized variables: you'll... |
4,751,574 | 4,751,655 | C++ Passing Struct Address | Im a little bit confused about passing structs into functions. I understand pointers and everything.
But for instance:
struct stuff
{
int one
int two
};
int main{
stuff fnc;
fnc.two = 2;
fnc.one = 1;
multiply(&fnc);
}
void multiply(const stuff * pm){
cout << pm->one * pm->two;
}
First of ... | Yes, your code is compilable other than the missing semicolons in the defintion of struct stuff. I'm not quite sure exactly what you're asking about passing the function and the actual function call, but I think you're wondering why the function call uses &fnc, but the parameter is stuff *pm? In that case, the fnc vari... |
4,751,606 | 4,751,673 | Can CString::Format() receive const std::string? | Can CString::Format() receive const std::string?
Example:
void some_func( const std::string a_string )
{
CString b_string("World");
CString c_string;
c_string.Format("%s %s!", a_string, b_string);
/* print c_string */
};
| No. You need to use the return value from a_string.c_str() (which is a const char* that CString can understand).
|
4,751,731 | 4,786,002 | Configuring .NET library from unmanaged C++ | I have a C# .NET library called Foo that produces a Foo.dll file. It is also configurable via a .config file which looks like this:
<?xml version="1.0"?>
<configuration>
<configSections>
<sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=4.0.0.0, Culture... | Well this is possible, but not a small amount of work. It's generally easier to create the appdomain and set configuration from the managed world and then create a small 'thunking' layer in managed code to wrap it all up for unmanaged clients. But since that isn't what you asked for, here is how you could accomplish ... |
4,751,774 | 4,784,594 | Running GCC through Visual studio | I have been writing an app that parses a Visual Studio 2010 solution and attempts to compile it using GCC.
As I built the app I have had it running in a standard console window and I have had no problems (provided you ignore my slight GCC incompatibilities ;)).
The problem comes that when I execute this application und... | I haven't tried this problem with visual studio and I am not sure if this solves your problem, but faced a similar issue when trying to compile a program with cygwin's gcc in windows with emacs. Siince cygwin's gcc.exe is not an executable, but a type of symlink to the actual executable (which is either gcc-3.exe or gc... |
4,751,930 | 4,753,707 | mutable keyword and thread-safety | I have an abstract base class
class Map {
public:
virtual Value get(Key const &) const;
};
a database class from an external library
class Database {
public:
// logically const and thread-safe
Value get(Key const &key);
};
and I started with an implementation like
class PersistentMap : public Map {
... | It depends entirely on whether Database::get is thread-safe or not. If it contains locks to prevent concurrent access, or is otherwise safe for concurrent access, then your code is fine with either the const_cast or the mutable. Using volatile is completely irrelevant.
|
4,751,953 | 4,753,346 | Send email with attachment using client's email application | I need my locally-installed, thick-client application (Qt / C++) to generate a ready-to-be-sent email message on the client's machine:
This message must contain the contents of a relatively small (15K - 200K) binary file.
Many of my users will be disconnected at the time this message is generated, so it is possible th... | You could create an .eml file and open it which should give you the effect you want as long as there is any email client registered in the system to handle files with this extension. I'm sure this is not as universal as the mailto: scheme but if mailto: does not work for you I think this could be the second best option... |
4,751,972 | 4,752,030 | endl and flushing the buffer | In the C++ primer book, in chapter (1), it mentions the following:
endl is a special value, called a manipulator, that when written to an
output stream has the effect of writing a newline to the output and
flushing the buffer associated with that device. By flushing the buffer, we ensure that the user will see the o... | Output is generally buffered before it's written to the intended device. That way, when writing to slow to access devices(like files), it doesn't have to access the device after every single character.
Flushing means emptying the buffer and actually writing it to the device.
|
4,752,028 | 4,752,466 | What's wrong with this Interpolation search implementation? | This is a common C/C++ implementation of the Interpolation Search algorithm found around the Internet. However, when used with a sorted array of some 100000 integers, the mid-variable starts generating negative array-indexes, causing a Segmentation Fault. What could the problem be?
#include <stdlib.h>
#include <stdio.h... | The sub-expression: ((toFind - sortedArray[low]) * (high - low))
... can easily evaluate to something like: ((99999-0) * (99999-0)) == 99999^2
... which is much larger than 2^31 (== the range of 32-bit signed integers).
Once it exceeds 2^31-1, the integer will overflow into negative numbers, hence your negative indice... |
4,752,264 | 4,752,406 | Downloader doesnt get all the data | So i am trying to make a downloader based on http protocol. It works ok on small txt files, but if i try downloading something bigger, lets say a picture, it doesnt get all of the data.
void accel::getfile(int from, int to){
//send GET message
string msg = msg_get(fpath, true, from, to);
int back = send(soc... | Your code appears to assume that recv always returns the maximum amount of data (ie. that it waits for n bytes to appear). recv may return early if a smaller amount of data is currently available.
Instead, you should continue until either disconnection (when recv returns 0, or an error such as WSAECONNRESET) or an expe... |
4,752,306 | 4,752,344 | n900 - maemo - timing | I am attempting to save a file every second within +- 100ms (10% error). The problem I am having is that my timing measurement is saying that execution took 1150 ms, but in reality it appears to be 3 or 4 seconds.
What's going on?
If I issue the command, sleep(1), it appears to be very accurate. However, when I measu... | Your problem is that clock() reports you CPU time used by your process and it is usually different from the "real" time used.
For example following code:
#include <time.h>
#include <iostream>
#include <unistd.h>
using namespace std;
int main()
{
clock_t scl = clock();
sleep(1);
cout << "CPU cl... |
4,752,457 | 4,752,897 | Creating a file of arbitrary size using Windows C++ API | I would like to create a file of arbitrary size using the Windows C/C++ API. I am using Windows XP service pack 2 with a 32 bit virtual address memory space. I am familiar with CreateFile.
However CreateFile does not have a size arument, The reason I want to pass in a size argument is to allow me to create memory map... | To do this on UNIX, seek to (RequiredFileSize - 1) and then write a byte. The value of the byte can be anything, but zero is the obvious choice.
|
4,752,472 | 4,752,531 | big endian little endian conversion | I saw a question on stack overflow how to convert from one endian to another. And the solution was like this:
template <typename T>
void swap_endian(T& pX)
{
char& raw = reinterpret_cast<char&>(pX);
std::reverse(&raw, &raw + sizeof(T));
}
My question is. Will this solution swap the bits correctly? It will swap... | Yes it will, because there is no need to swap the bits.
Edit:
Endianness has effect on the order in which the bytes are written for values of 2 bytes or more. Little endian means the least significant byte comes first, big-endian the other way around.
If you receive a big-eindian stream of bytes written by a little e... |
4,752,475 | 4,752,528 | What's the most performant way to construct a left-padded with NULL fixed length character array in C++? | If you have something like:
char buf[10];
and need to create a function like:
void pad(char* dest, const char* src, size_t destlen, size_t srclen);
so pad(dest, "hello", 10, 5) will result in "hello\0\0\0\0\0"
I'm not sure what the most efficient way of doing this is using gcc 4.x:
snprintf then bzero?
operator<< wit... | You can use memcpy and memset like
void pad(char* dest, const char* src, size_t destlen, size_t srclen)
{
memcpy(dest, src, srclen);
memset(dest+srclen, '\0', dstlen - srclen);
}
of course you should also check that you can fit src into dst
|
4,752,514 | 4,753,022 | Direct2D - Nothing is being drawn to the screen, something wrong in the way I'm handling arrays in C++ | Hello everyone and thank you for looking. This is a follow up to the original question posted here.
I have a base class that I define thusly:
class DrawableShape
{
public:
virtual HRESULT DrawShape(ID2D1HwndRenderTarget* m_pRenderTarget)
{
return S_OK;
}
};
I have two classes that extend this class... | shapes is an array of MyShape instances. When you say shapes[i] = ellipse1; or shapes[i] = rect1;, you are losing the subclass data as part of this assignment, which is known as slicing in C++.
As such, each call to shapes[i].DrawMyShape(m_pRenderTarget); is just returning S_OK as defined in MyShape.
In order to prope... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.