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 |
|---|---|---|---|---|
3,553,049 | 3,553,101 | converting from strings to ints | I would like to know what is the easiest way to convert an int to C++ style string and from C++ style string to int.
edit
Thank you very much. When converting form string to int what happens if I pass a char string ? (ex: "abce").
Thanks & Regards,
Mousey
| This is to convert string to number.
#include "stdafx.h"
#include <iostream>
#include <string>
#include <sstream>
int convert_string_to_number(const std::string& st)
{
std::istringstream stringinfo(st);
int num = 0;
stringinfo >> num;
return num;
}
int main()
{
int number = 0;
std::string ... |
3,553,265 | 3,553,277 | How can a declaration conflict with itself? | This is the error I'm getting when trying to compile some code that uses taucs (not my code):
.../taucs/src/taucs.h:554: error: conflicting declaration ‘typedef struct taucs_ccs_matrix taucs_ccs_matrix’
.../taucs/src/taucs.h:554: error: ‘taucs_ccs_matrix’ has a previous declaration as ‘typedef struct taucs_ccs_matrix t... | Could it be that your header file (.../taucs/src/taucs.h), which contains the declaration, is (directly or indirectly) included twice by two separate #include directives?
|
3,553,386 | 3,553,535 | C++ const reference declaration | how can the following declaration be expressed with const first (without typedef)?
double* const (&data)[6]
// ?? const double* (&data)[6] // incorrect, elements, not reference, are const
thank you
| You can't do it.
According to the C++ Standard 8.3.2/1:
Cv-qualified references are ill-formed except
when the cv-qualifiers are introduced through the use of a typedef (7.1.3) or of a template type argument
(14.3), in which case the cv-qualifiers are ignored.
|
3,553,428 | 3,604,127 | How can I prevent Gnome from showing two windows when doing alt-tab? (c++ qt app) | (see edits)
I'm developing a QT/c++ application under gnome.
The application a main window and QListBox child window.
Both of these windows show up as separate main windows when I alt-tab away from the application.
How can I make it so that only one window is shown when I (or later the user) uses alt-tab?
I am guess... | When creating a window for your QListBox window set a Qt::Tool window flag in its constructor or later with setWindowFlags function call. Here is some code snippet(I omitted the headers):
int main(int argc, char** argv)
{
QApplication app(argc, argv);
QMainWindow mw;
mw.show();
QWidget toolWindow(&mw, ... |
3,553,630 | 7,936,209 | gcc 4.5.1 configure options for C++0x thread support | I am trying to compile gcc 4.5.1 for cygwin with support for C++0x threads.
However, the resulting gcc does not recognize the -pthread option.
My configure command is:
./configure --enable-bootstrap --enable-shared --enable-shared-libgcc
--with-gnu-ld --enable-languages=c,c++ --enable-libgomp
-... | As you see in the error message, the problem is not with your configuration, but with your g++ option. Use
g++ -lpthread
for pthreads (POSIX threads) and
g++ -lboost_thread
for boost threads. (-pthread is wrong.)
see the manual of g++
man gcc
|
3,553,837 | 3,553,868 | c++ set a cursor using SetCursor | ok im setting a cursor in a loop it works but when i move the cursor it just changes back to the way it was. im using win32 api and i used
SetCursor(LoadCursor(hInstance, MAKEINTRESOURCE(IDC_PROTECTED)));
any idea
| IIRC, you want to call SetCursor in response to WM_SETCURSOR. If memory serves, the cursor will also stay what you've set if the cursor member of the window class is set to NULL.
|
3,553,855 | 3,553,908 | What is the equivalent of UpdateWindow() in wxWidgets? | I am new to wxWidgets and trying to find out how to force the painting of a window.
| Use wxWindow::Refresh or wxWindow::Update
|
3,553,905 | 3,556,024 | Is it possible to generate a parser for a language using the Reverse Polish notation with bison/yacc? | Is it possible to generate a parser for a scripting language that uses the Reverse Polish notation (and a Postscript-like syntax) using bison/yacc?
The parser should be able to parse code similar to the following one:
/fib
{
dup dup 1 eq exch 0 eq or not
{
dup 1 sub fib
exch 2 sub fib
add
} if
} def
| Given the short description above and the notes on Wikipedia:
http://en.wikipedia.org/wiki/Stack-oriented_programming_language#PostScript_stacks
A simple bison grammer for the above could be:
%token ADD
%token DUP
%token DEF
%token EQ
%token EXCH
%token IF
%token ... |
3,554,205 | 3,554,238 | C++ multi-dimensional array initialization | in C++ I want to initialize a double matrix (2-dimensional double array) like I would normally do without pointers like so:
double data[4][4] = {
1,0,0,0,
0,1,0,0,
0,0,1,0,
0,0,0,1
};
However, since I want to return and pass it to functions, I need it as a double** pointer. So, basically I need to ... | Unless you are particular about pointers, I would prefer a reference here
void init( double (&r)[4][4]){
// do assignment
r[0][0] = 1;
}
int main(){
double data[4][4] = {
1,0,0,0,
0,1,0,0,
0,0,1,0,
0,0,0,1
};
init(data);
}
By the way, if you pass it to a function i... |
3,554,253 | 3,554,322 | what is the execution order of a threaded and non-threaded function call? | i have written a simple console application just to try boost::thread, i am a multithreading newbie by the way. here is the code
#include <iostream>
#include <boost/thread/thread.hpp>
#include <windows.h>
using namespace std;
void Avg(double * Src, double *Dst, int Per, int Len, string& s )
{
LARGE_INTEGER s1,s2,... | In the first case, order may be both N T and T N, because both functions are executed in parallel. In the second case, output can be only T N, because the first function (T) must finish before the second (N) starts. bAvg.join means "Wait for thread function to exit".
|
3,554,286 | 3,554,297 | how do i compile a C++program to work in the windows operating system using g++ for linux? | I am new to writing programs in c++ and i want to know if there is a way to export it to a windows format. Also what is a good way to learn objective-c, is it very different from c++? Thank you in advance.
| Using mingw32 you can cross compile for windows. See http://www.mingw.org/wiki/LinuxCrossMinGW
|
3,554,356 | 3,554,371 | Are Preprocessor Definitions compiled into a library? | Are they (preprocessor definitions) compiled into a static/dynamic library? For example, the FBX SDK needs KFBX_DLLINFO. A library that makes use of FBX SDK must include that. Now the client application, as far as I can tell from my limited experimentation, does not need to declare the definition again.
Now I can't th... | In short: no.
In long:
For the most part, you can think of preprocessor definitions as a textual substitution mechanism. They are processed before compilation occurs (pre-compilation), so they transform the source code just before the compiler translates it to machine code, intermediate files, or whatever its target i... |
3,554,464 | 3,594,999 | Firefox Plugin Domain Restriction - Similar to IE's SiteLock | I would like to know if there is any functionality in the Gecko SDK/NPAPI that would allow me to restrict a plugin-usage to restricted domains only. Exactly like SiteLock for IE does with ActiveX components.
Any similar implementation in NPAPI, for example?
| Looks like I have to do it manually using NPAPI's GetIdentifier methods to read the url from the DOM tree and act upon it. Ergo just get the page URL using whatever NPAPI method you want to use (NewStream or GetIdentifier) and then compare it to a list of allowed or disallowed domains.
|
3,554,608 | 3,554,644 | Closest point implementation | I am trying to implement a closest point program. Here is the code:
#include <iostream>
#include <cstdlib>
#include <math.h>
using namespace std;
float randfloat(){
return 1.0*rand()/RAND_MAX;
}
class point
{
public :
float x,y;
float distance(point& a){
float dx=x-a.x;
float dy=y-a.y... | I believe that you are using the wrong distance() function. I believe you meant
a[i].distance(a[j])
instead of
distance(a[i],a[j])
|
3,554,909 | 3,555,290 | What is a vtable in C++ |
Possible Duplicate:
why do I need virtual table?
What is a vtable in C++?
So far I know that vtable is a virtual table which has an array of pointers to virtual functions. Is there an article I can read with an example of a practical implementation? (Any walk through will be appreciated.)
| V-tables (or virtual tables) are how most C++ implementations do polymorphism. For each concrete implementation of a class, there is a table of function pointers to all the virtual methods. A pointer to this table (called the virtual table) exists as a data member in all the objects. When one calls a virtual method, we... |
3,554,953 | 3,556,217 | 3d rendering of a surface from a depthmap | Using stereovision, I am producing depthmaps representing the 3d environment as viewed from a camera. There is one depthmap per "keyframe" associated with a camera position. The goal is to translate those 2d depthmaps into the 3d space (and later merge them to reconstruct the whole environment).
What would be the best ... | Not clear what you want to do "merge depahtmap with envirronement" ?
Anyway, in your case, you seems stuck to make them 3d using terrain heightmap techniques.
In you case, as the depthmap is screen aligned, use a screen space simple raycasting technique. So you must do a compositor in ogre3D that takes that depth map a... |
3,554,976 | 3,555,271 | What does the compiler do to perform a cast operation in C++? |
Possible Duplicate:
How do C/C++ compilers handle type casting between types with different value ranges?
What does the compiler do to perform a cast operation in C++?
Explain with some sample C++ code.
| Standard sections
5.2.7, 5.2.8, 5.2.9, 5.2.10 and 5.2.11
give a good idea on how these casts work (which is what compiler and/or runtime implement).
reinterpret_cast is the only one whose behavior is kind of implementation defined.
|
3,555,007 | 3,555,989 | How essential is polymorphism for writing a text editor? | Many years ago when I didn't know much about object oriented design I heard one guy said something like "How can you write a text editor without polymorphism?" I didn't know much about OOP and so I couldn't judge how wise that though was or ask any specific questions at that time.
Now, after many years of software deve... | The other points about polymorphism as being just a tool are spot on.
However if "the guy" did have some experience with writing text editors he may well have been talking about using polymorphism in the implementation of a document composition hierarchy.
Basically this is just a tree of objects that represent the stru... |
3,555,083 | 4,745,127 | How do I tell gcov to ignore un-hittable lines of C++ code? | I'm using gcov to measure coverage in my C++ code. I'd like to get to 100% coverage, but am hampered by the fact that there are some lines of code that are theoretically un-hittable (methods that are required to be implemented but which are never called, default branches of switch statements, etc.). Each of these bra... | Please use lcov. It hides gcov's complexity, produces nice output, allows detailed output per test, features easy file filtering and - ta-taa - line markers for already reviewed lines:
From geninfo(1):
The following markers are recognized by geninfo:
LCOV_EXCL_LINE
Lines containing this marker will be excluded.
L... |
3,555,197 | 3,555,423 | Boost.Thread or just::thread? | I am not yet a Boost user. I am however planning to go into it as soon as possible.
However I am little concerned about Boost, and the likely future name collisions or differences with the forthcoming C++0x. (Maybe it is not a real issue, but for example I find the boost lambdas syntax pretty ugly, BOOST_FOREACH aggres... | At the present time I am experimenting, on Linux, with the boost, just::thread libraries and the so-called 'experimental' C++Ox features of the gcc g++ 4.5 compiler. With regard to threading I have up to press I have found the code that I have written for just::thread and the g++ compiler to be 100% compatible. The boo... |
3,555,434 | 3,555,509 | C# COM Interop: How to translate instructions from C++? | I am trying to translate the COM Interop instructions given by my camera manufacturer for C++ to C#.
They write:
To obtain the interface, you use the normal COM functions to ask for the specific interface you need from the capture filter.
For example:
IBaseFilter* pSourceFilter;
...
CComQIPtr<IManufacturersInterfa... | The easiest way to do com interop is to let Visual Studio create the interop for you - I used it with many different com objects and never had any issues with it. To get started, in your C# project select Add Reference and select the tab COM, find the camera manufacturer's object in the list and you should be done. You... |
3,555,635 | 3,555,695 | Sending TCHAR buffer with send(sock, wszBuffer, ...)? | I have a wide-character XML message that I need to send over a Win32 socket in C++.
TCHAR wszBuffer[1024];
Should I sprintf(szSendBuffer, "%S", wszBuffer) the wide character buffer to a char array before sending it?
What is the correct way to send this?
| Pass wszBuffer directly to the socket function, casting it to char*, with length = sizeof(wszBuffer), or 1024 * sizeof(TCHAR). In this case the buffer will be send as is.
If you want to send this text as ANSI string, convert it by any string convertion function. sprintf is OK, another way is W2A. But some information m... |
3,555,642 | 3,555,897 | How to create textured wall which continuously updated while player is moving up in opengl? | I was wondering how to create wall in opengl and it is continuously appears from up and disappers at down screen. I am able to construct wall by GL_QUADS with texture mapping. but do not know how to generate it dynamically whenever player climbs up.
| You have several possibilities.
Create one quad for, say, one meter. Render it 100 times, from floor(playerPos.z) to 100 meters ahead. Repeat for the opposite wall
Create one quad for 100 meters. Set the U texture coordinate of the quad to playerPos.z and playerPos.z + 100. Set the texture mapping to GL_REPEAT.
The s... |
3,555,715 | 3,555,952 | How to read formatted data in C++? | I have formatted data like the following:
Words 5
AnotherWord 4
SomeWord 6
It's in a text file and I'm using ifstream to read it, but how do I separate the number and the word? The word will only consist of alphabets and there will be certain spaces or tabs between the word and the number, not sure of... | Assuming there will not be any whitespace within the "word" (then it will not be actually 1 word), here is a sample of how to read upto end of the file:
std::ifstream file("file.txt");
std::string str;
int i;
while(file >> str >> i)
std::cout << str << ' ' << i << std::endl;
|
3,555,753 | 3,556,049 | Ambiguous call if class inherits from 2 templated parent classes. Why? | I have a templated class that performs an action on the class that is given as template argument. For some of my classes I want to 'group' the functionality in one class, to make it easier for the caller. In fact the code looks something like this (names were changed):
template<typename T>
class DoSomeProcessing
{
pu... | This is by design. The compiler is not trying to resolve overloaded
functions because these are not overloaded
functions. The standard is really clear on that
(see 10.2.2). If the same name is found in two
different bases, it's an ambiguity, even if they
could be resolved correctly with the call (i.e. in
your case). Sa... |
3,555,791 | 3,555,936 | Why does printf not print out just one byte when printing hex? | pixel_data is a vector of char.
When I do printf(" 0x%1x ", pixel_data[0] ) I'm expecting to see 0xf5.
But I get 0xfffffff5 as though I was printing out a 4 byte integer instead of 1 byte.
Why is this? I have given printf a char to print out - it's only 1 byte, so why is printf printing 4?
NB. the printf implementatio... | You're probably getting a benign form of undefined behaviour because the %x modifier expects an unsigned int parameter and a char will usually be promoted to an int when passed to a varargs function.
You should explicitly cast the char to an unsigned int to get predictable results:
printf(" 0x%1x ", (unsigned)pixel_dat... |
3,555,938 | 3,556,108 | Going from Dev-C++ to VC++ | Yes, it's a noob question...
I have been using Dev-C++ for all my projects so far, but it is incredibly outdated, and so where the libraries. So I opened up my copy of Visual C++ and copied the code. When I compile, a million errors pop up, as if every second line of my code is shit. I would hate to start the project a... | This will not answer everything, but it might help.
By default, VC++ uses unicode while MinGW (on which DevCpp is based I believe) uses ansi.
This might explain your issues regarding strings: you're basically passing char* strings where most of the functions require something like wchar*.
I suggest that either you fix... |
3,555,974 | 3,556,033 | How to draw a character at a random place on the screen - c++ | Sorry about the dumb question, but is there a way to draw a character at a random place on the screen without using any "heavy" graphics libraries?
Thanks,
Li
| Try writing directly to video RAM at address B800:0000 (see Bios Memory Map).
|
3,556,048 | 3,556,192 | How to detect win32 process creation/termination in c++ | I know that to receive notifications about Win32 process creation or termination we might implement a NT kernel-mode driver using the APIs PsSetCreateProcessNotifyRoutine() that offers the ability to register system-wide callback function which is called by OS each time when a new process starts, exits or is terminated... | The only thing I could think of is WMI, not sure if it provides a process creation callback, but it might be worth looking into.
|
3,556,089 | 3,556,118 | Is there any way to have ASYNC MessageBox? | Or do I have to use threads? (C++)
| No there isn't. Alternatively, you can create a "modeless dialog box".
|
3,556,241 | 3,556,293 | What's the easiest go to use dynamic array in c/c++ in windows xp? | I need to save instances of type HANDLE to an array container and iterate over it, finally remove some of them when necessary,
Which container should I use for the purpose of easiness?
| The best one will depend on how your going to access it and where you're going to remove elements from.
std::vector should usually be your default choice. Here you can iterate over the HANDLE elements and storage is efficient. The issue with vector may arise when you're erasing. If you are removing elements from the... |
3,556,421 | 3,556,525 | Blocked waiting for a asynchronous Qt signal | I know, there are some similar questions to the following out there, but I couldn't find a concrete answer that helps me. So here's my problem:
I work on an application that does some gui-initialisations on start up. One of the things I have to do, is calling
NetworkConfigurationManager::updateConfigurations ()
This i... | The way to do this is to use nested event loops. You simply create your own QEventLoop, connect whatever signal you want to wait for to the loop's quit() slot, then exec() the loop. This way, once the signal is called, it will trigger the QEventLoop's quit() slot, therefore exiting the loop's exec().
MyApp::MyApp(QWidg... |
3,556,653 | 3,556,785 | Is Websphere written in Java? Does it run so fast in JVM? | As I know many Java EE application servers are written in Java. (JBoss, Tomcat...)
Is Websphere also written in Java?
I found that Websphere's performance is dramatic high, I guess that Websphere is written in C++. I couldn't imagine that the 'heavy' server is able to run so fast in JVM.
Is it true?
| Yes, WebSphere is written in Java. Typically application servers used to have components orineted towards high performance (like the HTTP listeners) written in C/C++, and compiled against the various supported platforms. Nowadays, fewer application servers employ this approach and are almost always written entirely in ... |
3,556,687 | 3,556,745 | Prevent Firing Signals in Qt | We have a QCheckBox object, when user checks it or removes check we want to call a function so we connect our function to stateChanged ( int state ) signal. On the other hand, according to some condition we also change the state of QCheckBox object inside code, and this causes the unwanted signal.
Is there any way to ... | You can use the clicked signal because it is only emitted when the user actually clicked the check box, not when you manually check it using setChecked.
If you just don't want the signal to be emitted at one specific time, you can use QObject::blockSignals like this:
bool oldState = checkBox->blockSignals(true);
checkB... |
3,556,976 | 3,556,995 | Return char* to string literal | Can you do this?
char* func()
{
char * c = "String";
return c;
}
is "String" here a globally allocated data by compiler?
| You can do that. But it would be even more correct to say:
const char* func(){
return "String";
}
The c++ spec says that string literals are given static storage duration. I can't link to it because there are precious few versions of the c++ spec online.
This page on const correctness is the best reference I can fin... |
3,557,030 | 3,557,176 | constructors and destructors - c++ | I need to write a program that prints 100 stars on the screen (at random places), and then the stars disappear slowly - one after another. I'm not allowed to use loops nor recursions.
I've tried to play with the constructors and the destructors but I can't get the stars to disappear one after another (and not all toget... | Seems the only way possible without loops/recursion is something like this:
class Star
{
Star()
{
//constructor shows star in a a random place
}
~Star()
{
//destructor removes star and sleeps for a random amount of time
}
};
int main()
{
Star S[100];
}
This is really just a dumb trick becau... |
3,557,115 | 3,557,162 | iostream - reading string with embedded blanks | I have a file with records that looks like this
123 Tag Now is the time for all good men to come to the aid
There always a number and some tag followed by a series of words. I want to extract the number as integer, tag as string, and sentence as string. I've done this using getline and scan plus some substring foolis... | You should be able to do it in two steps:
istringstream iss ("123 Tag Now is the time for all good men to come to the");
int i;
std::string tag, sentence;
iss >> i >> tag >> ws;
std::getline(iss, sentence);
|
3,557,398 | 3,557,545 | Using C/C++ DLL in Delphi 2010 | I want to use dll from ssdeep (http://ssdeep.sourceforge.net/). The API is:
int fuzzy_hash_buf(unsigned char *buf, uint32_t buf_len, char *result);
then in Delphi, i write it like this:
function fuzzy_hash_buf(buf : Pbyte; buf_len : Cardinal; result : PAnsiChar): integer; stdcall; external 'fuzzy.dll' name 'fuzzy_hash_... | If fuzzy.dll exports a function fuzzy_hash_buf with the C declaration
int fuzzy_hash_buf(unsigned char *buf, uint32_t buf_len, char *result);
then you are right that the Delphi declaration would be
function fuzzy_hash_buf(buf: PAnsiChar; buf_len: cardinal; result: PAnsiChar):
integer;
To use this in Delphi, in the ... |
3,557,489 | 3,557,525 | rate ++a,a++,a=a+1 and a+=1 in terms of execution efficiency in C.Assume gcc to be the compiler |
Possible Duplicate:
Is there a performance difference between i++ and ++i in C++?
In terms of usage of the following, please rate in terms of execution time in C.
In some interviews i was asked which shall i use among these variations and why.
a++
++a
a=a+1
a+=1
| Here is what g++ -S produces:
void irrelevant_low_level_worries()
{
int a = 0;
// movl $0, -4(%ebp)
a++;
// incl -4(%ebp)
++a;
// incl -4(%ebp)
a = a + 1;
// incl -4(%ebp)
a += 1;
// incl -4(%ebp)
}
So even without any optimizer switches, all four statements compile to the e... |
3,557,523 | 3,558,190 | Serializing binary struct gcc vs cl | Full disclosure - this is homework, although completed and fully working, I'm searching for a nicer solution.
I have a binary file, which was created by a program compiled within Visual Studio (I believe). The structure looks something like this.
struct Record {
char c;
double d;
time_t t;
};
The size of ... | The difference stems from whether we 32bit align doubles by default or 64bit align doubles by default. On a 32 bit machine, having a double on a 64 bit boundary may have some benefits but is probably not huge. VC is then probably more careful about this than gcc.
The botton line is that if you are using structs for ser... |
3,557,569 | 3,560,203 | Qt C++ destructor taking a long time to return | I'm working on a pretty standard Qt mobile app (written in C++, targeted at Symbian devices), and am finding that sometimes when the app is closed (i.e. via a call to QApplication::quit), the final destructor in the app can take a long time to return (30 seconds plus). By this I mean, all clean up operations in the des... | If your final destructor is for a class than inherits QObject then the QObject destructor will be called immediately following the destructor of your final object. Presumably this object is the root of a possibly large object tree which will trigger a number of actions to occur including calling the destructor of all ... |
3,557,591 | 3,557,610 | std::string and its automatic memory resizing | I'm pretty new to C++, but I know you can't just use memory willy nilly like the std::string class seems to let you do. For instance:
std::string f = "asdf";
f += "fdsa";
How does the string class handle getting larger and smaller? I assume it allocates a default amount of memory and if it needs more, it news a larger... | Usually, there's a doubling algorithm. In other words, when it fills the current buffer, it allocates a new buffer that's twice as big, and then copies the current data over. This results in fewer allocate/copy operations than the alternative of growing by a single allocation block.
|
3,557,639 | 3,568,633 | Silencing false positives in Coverity Prevent | I am using Coverity Prevent on a C++ project. Is there some way of flagging false positives directly in the source code?
| Coverity Static Analysis supports source code annotations. They are described in the manual - since I don't know what version you're using I can't tell you exactly what section but it's in the book called "Checker Reference" in a section on "Models and Annotations."
|
3,557,691 | 3,565,282 | Increase stack size when compiling with mingw? | I'm writing a recursive flood-fill algorithm to find connected components in an image, my code compiles and runs well with MSVC 2008 compiler; but the mingw-compiled binary crashed at runtime.
After I converted the algorithm to non-recursive with std::stack, everything goes well.
But what if I must use recursive algori... | Use
gcc -Wl,--stack,N
where N is stack size. E.g. gcc -Wl,--stack,4194304
|
3,557,907 | 3,557,929 | Typedef a container of function pointers | Simple question; right now I have something like this:
typedef void(*MyFunctionPointer)(int);
typedef std::vector < MyFunctionPointer > MyFunctionPointerContainer;
However, I want to typedef this container in one row, skipping the first typedef, how can I do this?
| typedef std::vector < void(*)(int) > MyFunctionPointerContainer;
|
3,557,999 | 3,558,041 | How to insulate a job/thread from crashes | I'm working on a library where I'm farming various tasks out to some third-party libraries that do some relatively sketchy or dangerous platform-specific work. (In specific, I'm writing a mathematical function parser that calls JIT-compilers, like LLVM or libjit, to build machine code.) In practice, these third-party... | Spawn a new process.
|
3,558,095 | 3,559,876 | Using boost to create a lambda function which always returns true | Suppose I have a function which takes some form of predicate:
void Foo( boost::function<bool(int,int,int)> predicate );
If I want to call it with a predicate that always returns true, I can define a helper function:
bool AlwaysTrue( int, int, int ) { return true; }
...
Foo( boost::bind( AlwaysTrue ) );
But is there a... | UncleBens commented on this in Scharron's answer, but I think it is actually the best answer so I'm stealing it (sorry UncleBens). Simply use
Foo(boost::lambda::constant(true));
As described in the documentation for Boost.Lambda, only the minimum arity of the functor is zero, the maximum arity is unlimited. So any in... |
3,558,339 | 3,573,959 | How to get values of child nodes with QDomDocument? | A recieve a string like this:
<invoke name="CanClose" returntype="xml">
<arguments>
<string># 998.40</string>
<number>49920</number>
</arguments>
</invoke>
I'd like to use QDomDocument to get the values of arguments' child nodes by their index (I would like to extract the strings "# 998.40" and "49... | So apparently the text inside a node is a node itself, too. This is how it works:
QString argument(int index)
{
QDomNode arg = xml->firstChild().namedItem("arguments");
return arg.childNodes().at(index).firstChild().nodeValue();
}
|
3,558,445 | 3,558,488 | What is the C++ equivalent of PHP's is_dir()? | What is the C++ equivalent of PHP's is_dir() ?
http://www.php.net/manual/en/function.is-dir.php
bool is_dir ( string $filename )
Tells whether the given filename is a directory.
Working on a Linux platform only, what library would you use?
And what if cross-platform support mattered, what method would you use?
| The POSIX function lstat (and its less secure friend stat) returns a struct that you can query for that information. A convenience macro is provided: S_ISDIR() man 2 lstat for usage information.
Boost also provides the filesystem library, which provides an easy-to-use set of functions, including the free function is_di... |
3,558,535 | 3,559,357 | How to make an auto-scrolling textbox in Qt? | In one of my projects, I would like to have an auto-scrolling textbox.
I'm not talking of a textbox that scrolls whenever someone adds a text line, but of something which is like a movie "closing credits" sequence.
The textbox would be fullfiled with text and down-scroll slowly without any user action.
Is there any exi... | The GraphicsView approach is the most flexible one I think, if you want something fancy.
An easier approach might be using the "Animation Framework", setting up a QPropertyAnimation and to connect it to the "value" property of a QTextBrowser's vertical scrollbar. (Have a look at the Animation Framework examples).
|
3,558,609 | 3,558,868 | template specialized on a namespace | Given:
namespace A {
class Foo;
class Bar;
}
namespace B {
class Foo;
class Bar;
}
I want to template a class on the namespace A or B such that the following works:
template<name> class C {
name::Foo* foo;
name::Bar* bar;
}
Can this be done directly or do I need to create a pair of struct types with type... | You can't template on a namespace. If you're able to use a class (with most likely public attributes/static methods) then you can template on the class as a semi-workaround.
|
3,558,669 | 3,558,740 | C++ append to string and write to file | Why does the following code not work
#include <iostream>
#include <fstream>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
using namespace std;
int main(){
string data;
int i=0;
while(i <= 5){
i++;
data += i;
data += "\n";
}
ofstream myfile;
myfile.open ("data.tx... | Why do you not use operator<<?
ofstream myfile;
myfile.open ("data.txt");
for ( int i = 1; i <= 5; ++i )
myfile << i << "\n";
myfile.close();
|
3,558,684 | 3,562,373 | avoiding abort in libgmp | I have some code that uses libgmp. At some point the user may request a factorial of a very large number. Unfortunately, this results in libgmp raising an abort signal.
For example the following code:
#include <cmath>
#include <gmp.h>
#include <iostream>
int main() {
mpz_t result;
mpz_init(result);
mpz_f... | The best way to handle these errors gracefully in your application is probably to fork off a helper process to perform the GMP calculations. If the helper process is killed by SIGABRT, your parent process can detect that and report an error to the user.
(The below is my original answer, which has "undefined results" ... |
3,558,786 | 3,558,826 | Setting a plain background color for a QGraphicsView widget | I'm trying to display a little square of solid color.
I've created a QGraphicsView widget myGraphicsView and call:
ui->myGraphicsView->setBackgroundBrush(QBrush(Qt::red, Qt::SolidPattern));
But it stays white. What am I doing wrong?
| You need to set the QGraphicsScene to the QGraphicsView before anything is drawn:
ui->myGraphicsView->setScene(myScene);
|
3,558,861 | 3,558,902 | Efficiency of explicit initialization | I have a class which has a constructor that takes a const char*. It is:
c::c(const char* str) {
a = 32;
f = 0;
data = new char[strlen(str)];
memcpy(data, str, strlen(str));
}
And a function which takes one of them:
int foo(c& cinst);
You can call this function either by passing it an instance of a c:
... | What will foo be doing with that const char*? If it's just going to make it own c object, then there's no point.
If it is going to use the char* directly (and the existing foo just pulled the char* out of the c object), then it would be better to write an overload.
|
3,558,961 | 3,559,032 | RSS feed and program updates in MFC app | My boss wants me to write a simple RSS feed for an C++ MFC app that will pull and display information from the company's website. It also must be able to grab program updates from the website, tell the user that there are updates and then install the updates. Are there any tutorials that follow these guide lines? How w... | RSS is not more than XML (Ref). Under Windows/MFC you can use MSXML directly or use this MSXML wraper class, tinyxml, or other any other XML library to handle XML.
Update:
To download RSS you can use CHttpFile.
|
3,559,210 | 3,572,806 | stl container end is redundant after find, so what is the shortcut | Let us assume we have a map class (unordered map, list, set, whatever will also do). We are looking for a specific element. After calling the find() member, we have to check with the end() member. But find() internally already knows whether it is returning a good iterator or the end iterator. Why should we need to call... | Alternatives are possible - for example, find() could return a std::pair or something akin to boost::optional - but there's little practical advantage and it requires an uglier, more error prone coding style. In languages (mainly interpreted) with an inbuilt None/null sentinel that's the ideal value for this, but C++ ... |
3,559,344 | 3,559,391 | error: no matching function for call to 'make_pair(int&, Quest*)' | I get this weird error in g++; it compiles fine in Visual Studio.
struct Quest
{
static map<int, Quest*> Cache;
};
Quest *Quest::LoadFromDb(BaseResult& result, int *id)
{
Quest *ret;
if(result.Error())
{
if(id)
Cache.insert(make_pair<int, Quest*>(*id, NULL)); // <--- Problematic lin... | Does it work with an explicit cast?
if (id)
Cache.insert(make_pair<int, Quest*>(int(*id), NULL));
Also, a cpp file with 9000 lines, really?
|
3,559,412 | 3,560,884 | How to store different data types in one list? (C++) | I need to store a list of various properties of an object. Property consists of a name and data, which can be of any datatype.
I know I can make a class "Property", and extend it with different PropertySubClasses which only differ with the datatype they are storing, but it does not feel right.
class Property
{
Pro... | C++ is a multi-paradigm language. It shines brightest and is most powerful where paradigms are mixed.
class Property
{
public:
Property(const std::string& name) //note: we don't lightly copy strings in C++
: m_name(name) {}
virtual ~Property() {}
private:
std::string m_name;
};
template< typename T ... |
3,559,620 | 3,559,643 | C++ concatenate string problem | Why does the following code not work?
#include <iostream>
#include <string>
int main(){
char filename[20];
cout << "Type in the filename: ";
cin >> filename;
strcat(filename, '.txt');
cout << filename;
}
It should concatenate ".txt" on the end of whatever filename is inputted
Also, when I try to co... | Use double quotes instead of single quotes.
strcat(filename, ".txt");
In C++, single quotes indicate a single character, double quotes indicate a sequence of characters (a string). Appending an L before the literal indicates that it uses the wide character set:
".txt" // <--- ordinary string literal, type "array of ... |
3,559,845 | 3,559,886 | STL algorithm all or any function? | Is there anything approximating Haskell's all or any functions as part of the STL? If not, is the below a good implementation (I noticed the sgi STL performed partial specialization if the iterators were random access, though I have not bothered with this)?
template <typename InputIterator, typename Predicate>
inline ... | There are not all or any algorithms in C++ currently, but C++0x adds std::all_of and std::any_of algorithms to the C++ standard library. Your implementation may support these already.
Since both of these algorithms need to test every element in the range (at least until they find a match or mismatch), there isn't any ... |
3,559,938 | 3,559,999 | memory leak unit test c++ | I have just resolved a memory leak in my application and now I want to write a unit test to ensure that this does not happen again.
I'm look for a way to detect the memory usage of the current application (working set), before and after some functions.
For example:
long mem_used= GetMemUsed();
/* Do some work */
/*... | Boost.Test will automatically tell you at the end of a test run if any of your unit tests leaked memory.
I don't know if any of the other C++ unit testing frameworks provide this kind of functionality.
|
3,559,968 | 3,559,993 | How to bound 2 variables in C++ one with other so when one changes changes another? | How to bound 2 variables in C++ one with other so when one changes changes another?
for example I created Int A and Int B bound one to another and than when I change A one using some function another one will automatically change to new value of A.
I am intrested in version for C++ .net 4th version.
| I don't know about the .Net version of C++, but you can use references in C++ to do what you want:
int A = 0;
int& B = A;
...
A = 10; // B == 10
B = 100; // A == 100
|
3,559,990 | 3,560,016 | Understanding CComBSTR assignment operators | Say I have the following:
BSTR myBSTR = SysAllocString( L"MYBSTR" );
CComBSTR myCComBSTR = myBSTR;
Does myCComBSTR take ownership of myBSTR and free it when it goes out of scope? Or does it make a copy of myBSTR and produce a memory leak if i dont free myBSTR?
If this produces a memory leak, what's the most efficient ... | In this case the CComBSTR instance creates an independent copy. You will need to manually free myBSTR to avoid a leak.
The simplest approach to fix this scenario is to skip the middle man SysAllocString function
CComBSTR myCComBSTR = L"MYBSTR";
On the other hand if you have a BSTR and want to have a CComBSTR take own... |
3,560,201 | 3,560,305 | C++ cursor changes to hour glass using WM_SETCURSOR | OK i have a game when person loses ill set a different cursor. i used the setcursro with loadcusor and WM_SETCURSOR. the problem is that my default cursor which i hae set it where i register my window, it changes to hour glass until the person loses than it changes to the cursor i have set it to. i found that when i us... | Generally if you're going to change cursors much, you want to do something like:
First we initialize the cursors we'll use:
HCURSOR cursors[3];
cursors[0] = LoadCursor(NULL, IDC_ARROW); // default cursor
cursors[1] = LoadCursor(NULL, IDC_CROSS); // other cursor
cursors[2] = LoadCursor(NULL, IDC_WAIT); // wai... |
3,560,234 | 3,565,098 | efficient algorithm for searching one of several strings in a text? | I need to search incoming not-very-long pieces of text for occurrences of given strings. The strings are constant for the whole session and are not many (~10). Additional simplification is that none of the strings is contained in any other.
I am currently using boost regex matching with str1 | str2 | .... The performan... | Look at this: http://www.boost.org/doc/libs/1_44_0/libs/regex/doc/html/boost_regex/configuration/algorithm.html
The existence of a recursive/non-recursive distinction is a pretty strong suggestion that BOOST is not necessarily a linear-time discrete finite-state machine. Therefore, there's a good chance you can do bett... |
3,560,494 | 4,067,242 | QList acting strange | I don't have much experience with Qt but somehow I think this is acting strange.
Compiled with VS2005:
class Entry
{
public:
Entry(const QString& aName, bool checked) :
name(aName), isChecked(checked)
{
// empty
};
Entry(const Entry& entry) :
name(entry.name), isChecked(entr... | I had this same problem, and came looking for anwsers.
I though my code was misbehaving, when it's not.
VS2005 debugger doesn't show you the things in QList correctly.
And as davmac suggested, when you print the stuff out, it works fine.
And davmac, please don't point out that he might have a memory corruption when th... |
3,560,710 | 3,561,375 | c++ set cursor size over 32 | im trying to set a cursor. the width and the height of the cursor is bigger than 32 px. but it just scale it down to 32px when i set it. any idea?
| If you're using the LoadCursor function, then I think you'll always get scaled to the standard size.
Try using LoadImage with IMAGE_CURSOR, a desired size of (0,0), and do not use the LR_DEFAULTSIZE flag.
|
3,560,786 | 3,560,947 | Why does this virtual destructor trigger an unresolved external? | Consider the following:
In X.h:
class X
{
X();
virtual ~X();
};
X.cpp:
#include "X.h"
X::X()
{}
Try to build this (I'm using a .dll target to avoid an error on the missing main, and I'm using Visual Studio 2010):
Error 1 error LNK2001: unresolved external symbol "private: virtual __thiscall X::~X(void)" ... | Situation 1:
You have the code for the constructor.
So it builds the constructor into the object file. The constructor needs the address of the destructor to put into the virtual table because it can not find it the constructor can not be built.
Situation 2: (inline constructor)
The compiler decides it does not need to... |
3,560,826 | 3,560,841 | In C++, why isn't the this keyword a reference? |
Possible Duplicate:
Why ‘this’ is a pointer and not a reference?
Is there a good reason that this is a pointer instead of a reference in C++?
| The this concept was introduced before the reference concept was. At the time, this had to be a pointer.Source
|
3,560,852 | 10,789,239 | Using Cairo on iPhone? | I'm doing some work on a potentially cross-platform C++ application and for Windows and OS X it seems that Cairo will meet most of my needs for 2D graphics and allow me to share a lot of code between platforms. In an ideal world I'd really like to be able to use the same (or very similar) drawing code in iPhone/iPad a... | To update this for anyone who happens to try going down the same route as I did, I never did get it to compile (I didn't get much response from the Cairo mailing list when I asked for suggestions). It seems that Cairo isn't really a very good idea for iOS or OSX. I've recently come across this post which pretty clearly... |
3,561,022 | 3,561,045 | What's the simplest way to write portable dynamically loadable libraries in C++? | I'm working on a project which has multiple similar code paths which I'd like to separate from the main project into plugins. The project must remain cross-platform compatible, and all of the dynamic library loading APIs I've looked into are platform specific.
What's the simplest way to create a dynamic library loading... | You will have to use platform dependent code for the loading system. It's different loading a DLL on Windows than loading a shared object in Unix. But, with a couple of #ifdef you will be able to have mostly the same code base in the loader.
Having said that, I think you can make your plugins platform independent. Of c... |
3,561,234 | 3,561,268 | Where can I start with programmable Hardware? | I've had a desire to learn at least a tiny bit about programming hardware for quite some time now and thought I'd ask here to get some starting points. I am a reasonably accomplished programmer with Delphi and Objective-c experience but have never even listened to a device port / interupt (I dont even know the termino... | I like the Arduino, easy to use, open source and a great community!
Good to get started with, and uses a subset of C/C++.
Also, has alot of addon hardware available, like GPS, Bluetooth, Wifi etc
My experiences with Arduino have been nothing but good, from the point you get it out of it's box (and install the free comp... |
3,561,435 | 3,561,503 | i want a variable that will change from a char to a int and vice versa depending on the user entry | i have to define a variable that i am using in a program but i want the variable to change from int to char.
example
#include <iostream>
#include <cstdlib>
int main()
{
int l=rand();
char x;
std::cout<<"this program makes a random char or number enter n for a number or c if you want a letter\n";
std::... | The generic name for this kind of thing is a union.
You can use the union keyword to define a C-style union: a variable which may be treated as having one of several types. However, you need to do all the work to keep track of which type it is.
union {
char c;
int i;
} l;
bool l_is_int;
if ( x == 'c' ) {
... |
3,561,571 | 3,561,752 | Will C++ throw with no arguments work inside another frame to rethrow an exception? | If I have a code like the following:
try {
doSomething();
} catch (...) {
noteError();
}
void noteError() {
try {
throw;
} catch (std::exception &err) {
std::cerr << "Note known error here: " << err.what();
} catch (...) {
std::cerr << "Note unknown error here.";
}
throw;
}
Will the original... | The wording in the standard (§15.1/2) is (emphasis mine):
When an exception is thrown, control is transferred to the nearest handler with a matching type (15.3); “nearest” means the handler for which the compound-statement, ctor-initializer, or function-body following the try keyword was most recently entered by the t... |
3,561,648 | 3,562,096 | Why does C++ not allow inherited friendship? | Why is friendship not at least optionally inheritable in C++? I understand transitivity and reflexivity being forbidden for obvious reasons (I say this only to head off simple FAQ quote answers), but the lack of something along the lines of virtual friend class Foo; puzzles me. Does anyone know the historical backgro... | Because I may write Foo and its friend Bar (thus there is a trust relationship).
But do I trust the people who write classes that are derived from Bar?
Not really. So they should not inherit friendship.
Any change in the internal representation of a class will require a modification to anything that is dependent on th... |
3,561,659 | 3,562,024 | How can I abstract out a repeating try catch pattern in C++ | I have a pattern that repeats for several member functions that looks like this:
int myClass::abstract_one(int sig1)
{
try {
return _original->abstract_one(sig1);
} catch (std::exception& err) {
handleException(err);
} catch (...) {
handleException();
}
}
bool myClass::abstract_two(int sig2)
{
tr... | I asked a very similar conceptual question, see Is re-throwing an exception legal in a nested 'try'?.
Basically, you can move the various exception handlers to a separate function by catching all exceptions, calling the handler and rethrowing the active exception.
void handle() {
try {
throw;
} catch (std::exceptio... |
3,561,891 | 3,561,914 | supplying inputs to stdin programatically line by line? | I have a test program which prompts for input from user(stdin), and depending on inputs, it asks for other inputs, which also need to be entered.
is there a way I can have a script do all this work ?
| There's a program called expect that does pretty much exactly what you want -- you can script inputs and expected outputs and responses based on those outputs, as simple or complex as you need. See also the wikipedia entry for expect
|
3,562,051 | 3,562,075 | c++ repaint part of window | i know how to repaint the full window but i don't know how to repaint a pieace of window like i draw a squre using gdi+ than i want to change it's coordinates so i want to repaint the squre not the whole window
anyidea?
i also tried this
RECT rect2;
rect2.left=0;
rect2.top=100;
rect2.right=225;
rect2.bottom=300;
In... | One way to do this is to call InvalidateRect() with a rectangle that is large enough to cover both the old and new positions of the square you moved. Windows will then call your WM_PAINT handler to repaint the area of the screen that changed.
The UnionRect() function is helpful for calculating this repaint rectangle.
|
3,562,060 | 3,562,087 | Syntax for pointer to portion of multi-dimensional statically-allocated array | Okay, I have a multi-dimensional array which is statically-allocated. I'd very much like to get a pointer to a portion of it and use that pointer to access the rest of it. Basically, I'd like to be able to do something like this:
#include <stdio.h>
#include <string.h>
#define DIM1 4
#define DIM2 4
#define DIM3 8
#defi... | theArray[0][0] gets rid of the first two dimensions, so you have something of type char [DIM3][DIM4]. The first dimension will drop out when the array decays to a pointer, so the declaration you want is:
char (*ptr)[DIM4] = theArray[0][0];
For what it's worth, gcc also displays a warning for your array declaration: "w... |
3,562,086 | 3,562,194 | How to find the size of the hash table? | I've a hash table defined like this
typedef std::unordered_map<unsigned long long int,unsigned long long int> table_map;
and in the program, I read the contents of the a file into a buffer using fread like this:
fread(buffer, sizeof(long long int), 1024, file1);
I declare the hash table as
table_map c1;
Now i creat... | Multiply the container's size property by the size of a pair:
std::cout << c1.size() * sizeof(table_map::value_type) << "\n";
On my system, this prints out:
16384
This is not totally accurate, because the bookkeeping data isn't accounted for. You cannot account for it, because (as far as I know) the standard doesn'... |
3,562,300 | 3,562,357 | visual c++ 2010 debugging problem | When I debug the my game, it works. But if I open my game's exe file that is stored in my project debug file, it shows as being 3 days old. The file is not getting updated.
Any ideas why?
| Go to
Project->Properties->Linker->Command
Line
and check the value of
/OUT:
field. It probably should be different from the "debug" folder that you are checking.
Ensure that you are checking it appropriately for "Debug" and "Release" configurations
|
3,562,471 | 3,562,518 | How to release the memory of structures pointed by an pointer-array? | I have a pointer array defined as some_struct * t_ptr[1000] which points to a structure some_struct.And some points of the point array are evaluated.e.g
some_struct * wpaper1 = new some_struct(); //memory leaks detected in this line
wpaper1->tAnswer = useransw;
wpaper1->tKey = key;
t_ptr[100] = wpaper1;
//there'r... | Your delete[] t_ptr would only be correct if you've allocated t_ptr on the heap, ala:
some_struct* t_ptr = new tpr[1000];
Then, the delete[] statement releases the memory for those 1000 pointers, but does nothing about any memory that the pointers themselves may refer to. To release that, you need to first loop over... |
3,562,513 | 3,562,564 | How to open a file when file handle number is known? | I open a file in C# with FileStream, and I got the file handle number with this line:
IntPtr file_handle = fs.SafeFileHandle.DangerousGetHandle();
Now I want to pass this handle to C++ code and use this handle value to access the file. Is this possible? How to open a file with merely a file handle in C++?
Thanks.
Upda... | You can use win32 calls, the same way the filestream/file constructors do (via p/invoke).
Cracking it open in .NET Reflector, it looks like it is using this function:
[DllImport("kernel32.dll", CharSet=CharSet.Auto, SetLastError=true)]
private static extern SafeFileHandle CreateFile(
string lpFileName,
int dwDesire... |
3,562,588 | 3,562,622 | How do I send long PUT data in libcurl without using file pointers? | I'm trying to interface with the Google Contact API, and in order to update a contact on the remote side, I need to use a PUT request instead of POST.
Since the data I want to PUT is already in memory, I really don't want to deal with file pointers, which seems to be the default behavior of CURLOPT_READDATA. Thus, I un... | You will still want to use CURLOPT_READDATA, however if you use CURLOPT_READFUNCTION, it can be any user-specified pointer. You can create a simple structure like:
struct put_data
{
char *data;
size_t len;
};
where data is the PUT data and len is the length (remaining).
Then, set CURLOPT_READDATA to a pointer to... |
3,562,886 | 3,562,938 | What detectable differences are there between a class and its base-class? | Given the following template:
template <typename T>
class wrapper : public T {};
What visible differences in interface or behaviour are there between an object of type Foo and an object of type wrapper<Foo>?
I'm already aware of one:
wrapper<Foo> only has a nullary constructor, copy constructor and assignment operato... | A reference to an object is convertible (given access) to a reference to a base class subobject. There is syntactic sugar to invoke implicit conversions allowing you to treat the object as an instance of the base, but that's really what's going on. No more, no less.
So, the difference is not hard to detect at all. They... |
3,562,964 | 3,563,095 | How to initialize bitfields with a C++ Constructor? | First off, I’m not concerned with portability, and can safely assume that the endianness will not change. Assuming I read a hardware register value, I would like to overlay that register value over bitfields so that I can refer to the individual fields in the register without using bit masks.
EDIT: Fixed problems point... | don't do this
*this = *(reinterpret_cast<HW_Register*>(®isterValue));
the 'this' pointer shouldn't be fiddled with in that way:
HW_Register reg(val)
HW_Register *reg = new HW_Register(val)
here 'this' is in two different places in memory
instead have an internal union/struct to hold the value, that way its easy t... |
3,563,173 | 3,563,289 | Why am I getting vector subscript out of range error in the Merge Sort? | void merge(vector<int> dst,vector<int> first,vector<int> second)
{
int i=0,j=0;
while(i<first.size()&&j<second.size())
{
if(first[i]<second[j])
{
dst.push_back(first[i]);
i++;
}
else
{
dst.push_back(second[j]);
j++;
... | Your sub vectors are specified incorrectly.
Remember the iterators specify the beginning to one past the end.
So this will misses the middle element and the last element in the vector.
And is also undefined for really short vectors of length 2
vector<int> first(&a[0],&a[sz/2]);
vector<int> second(&a[(sz/2)+1],&... |
3,563,184 | 3,563,226 | Variadic macros with zero arguments, and commas | Consider this macro:
#define MAKE_TEMPLATE(...) template <typename T, __VA_ARGS__ >
When used with zero arguments it produces bad code since the compiler expects an identifier after the comma. Actually, VC's preprocessor is smart enough to remove the comma, but GCC's isn't.
Since macros can't be overloaded, it seems l... | No, because the macro invocation MAKE_TEMPLATE() does not have zero arguments at all; it has one argument comprising zero tokens.
Older preprocessors, apparently including GCC at the time this answer was originally written, sometimes interpreted an empty argument list as you'd hope, but the consensus has moved toward a... |
3,563,202 | 3,563,212 | C++: How to check if a file/directory is readable? (PHP equivalent: is_readable) | I am trying to validate a directory with C++.
http://php.net/manual/en/function.is-readable.php
bool is_readable ( string $filename )
Tells whether a file (or directroy) exists and is readable.
What would be the equivalent of the above in C++?
I am already using the boost/filesystem library to check that the directo... |
Since you've tagged the question "Linux", there is a POSIX function to check if the file is readable/writable/executable by the user of the current process. See man 2 access.
int access(const char *pathname, int mode);
For example,
if (-1 == access("/file", R_OK))
{
perror("/file is not readable");
}
Alternative... |
3,563,386 | 3,563,412 | What is IconnectionPoint and EventHandling | Trying to understand What is IConnectionPoint and how this is connected to IConnectionPointContainer,IEnumConnectionPoints,IEnumConnections and EventHandling.
Read the artcicles from MSDN and CodeProject which is explaining a about other methods like: QueryInterface() and otherthings.
I am unable to figure out how all... | Looks like you get the big picture wrong. Typically your client will receive events and the COM object will trigger those events. To achieve this the client requests (QueryInterface()) the IConnectionPointContainer interface, calls IConnectionPointContainer::FindConnectionPoint() and IConnectionPoint::Advise() and pass... |
3,563,396 | 3,563,453 | what should I do to get the new process using a new command prompt window? | I got two console applications that the first one runs the second one:
1_first console application:
#include <Tchar.h>
#include <windows.h>
#include <iostream>
using namespace std;
void main(){
PROCESS_INFORMATION obj1;
memset(&obj1,0,sizeof(PROCESS_INFORMATION));
STARTUPINFOW obj2;
memset(&obj2,0,sizeof(STARTUP... | Pass CREATE_NEW_CONSOLE in the process creation flags (sixth parameter) when you call CreateProcess.
CreateProcessW(L"c:\\runme.exe",L"hello what's up?",NULL,NULL,FALSE,CREATE_NEW_CONSOLE,NULL,NULL,&obj2,&obj1);
When you call CreateProcessW you do not want to use _TEXT on strings. CreateProcessW always takes wide stri... |
3,563,433 | 3,563,461 | Memory cleanup issue converting QString to char* for use with a 3rd party library, how to solve? | I am using a 3rd party library with Qt that requires char* strings. I am using the following code to convert my QString to a char*
char* toCharArray(const QString &string)
{
QByteArray bytes = string.toLocal8Bit();
char* data = new char[bytes.count() + 1];
strcpy(data, bytes.data());
return data;
}
// ... | Why not just use
QString s;
3rdPartyObject->3rdPartyMethod( s.toLocal8Bit().data() );
The destruction of the temporary QByteArray at the end of the statement will clean up all the resources.
|
3,563,591 | 3,564,383 | How should a size-limited stl-like container be implemented? | While refactoring, I wanted to change an array where entries are added to an std::vector, but for compatibility (persistency, downgrading,...), it still needs to have an upper limit.
What is the best way (elegant, stl-like, limited extra code) to have an stl-like container which is limited in size, so you know that ins... | A simple solution would be encapsulating a vector inside your own limited size container. You could use private composition or private inheritance --note that private inheritance models implemented in terms of and does not have some of the shortcomings of public inheritance.
EDIT: Sketch of the solution with private in... |
3,564,137 | 3,564,648 | analysis of core file | I'm using Linux redhat 3, can someone explain how is that possible that i am able to analyze
with gdb , a core dump generated in Linux redhat 5 ?
not that i complaint :) but i need to be sure this will always work... ?
EDIT: the shared libraries are the same version, so no worries about that, they are placed in a sh... | In my experience analysing core file, generated on other system, do not work, because standard library (and other libraries your program probably use) typically will be different, so addresses of the functions are different, so you cannot even get a sensible backtrace.
Don't do it, because even if it works sometimes, y... |
3,564,167 | 3,564,199 | Why is type_info::name() unspecified? | I'm fully aware that the return value of std::type_info::name() is implementation-defined.
From the C++ standard (ISO/IEC 14882:2003 §18.5.1.7):
Returns: an implementation-defined NTBS.
My question is: why? Wouldn't this member function be much more useful if the standard dictated what the return value should be?
| Basically, if an implementation decides that they can't or doesn't want to support RTTI, they can just return "";. If the standard forced it to return something, they'd possibly kill any ability to have a compliant compiler for an environment where the resources for RTTI don't exist or want to be disabled (a microchip,... |
3,564,415 | 3,564,440 | Using boost to create a lambda function which always throws | Is it possible to create an inline lambda using boost which always throws an exception?
(this question follows on from "Using boost to create a lambda function which always returns true").
Suppose I have a function which takes some form of predicate:
void Foo( boost::function<bool(int,int,int)> predicate );
If I want ... | There is a throw_exception function in Boost.Lambda.
For example:
#include <boost/lambda/lambda.hpp>
#include <boost/lambda/exceptions.hpp>
#include <boost/function.hpp>
#include <exception>
#include <iostream>
struct Bar {
private:
Bar() {}
};
void Foo(boost::function<Bar(int,int,int)> predicate) {
... |
3,564,436 | 3,564,577 | Print ascii table 0-127 | got a question regarding printing out the 128 first characters from the ascii table. I haven't gotten so far yet, because I already stumbled to a problem. The following code prints the correct value starting from 32-127. From 0 to 31 however it prints out some scrap values. I assume it is correct as well since I quick ... | If the character is smaller than 32 it is a special character and thus may not have a vueable glyph. So if the character is below 32 you should take this into account and put an appropriate character string in its place.
#include <iostream>
// An array of strings for all the special characters.
char const* data[] = {"... |
3,564,752 | 3,570,447 | What is .cfi and .LFE in assembly code produced by GCC from c++ program? | I have the following c++ code
int factorial(int n){
if(n==0){
return 1;
}
return n*factorial(n-1);
}
int main(void){
factorial(5);
return 0;
}
When I create an assembly file using g++ -S factorial.cpp I get the following:
.file "tail_call_opt.cpp"
.text
.globl _Z9factoriali
... | These directives tell gas to emit Dwarf Call Frame Information tags which are apparently used to reconstruct a stack backtrace when a frame pointer is missing. In your case the frame pointer is present, so I guess it could be used to perform unwinding during exception handling. Such mechanism has less overhead than the... |
3,564,842 | 3,564,883 | How to make tr1::array allocate aligned memory? | You can allocate a std::vector which allocates aligned heap memory by defining your own allocator.
You can allocate a c-style array on the stack using declspec align.
But can you declare a tr1::array which guarantees that the element at index zero will be aligned?
| tr1::array (and std::array and boost::array) are POD, so the memory occupied by the contents is coincident with the memory of the array. So, allocate the array however you need to, and construct it with placement new.
typedef std::tr1::array< MyClass, ary_sz > AryT;
void *array_storage = aligned_allocation( sizeof( Ary... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.