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 |
|---|---|---|---|---|
2,489,406 | 2,489,421 | Best Practice - Validating Input In Simple GUI Application? | I'm writing a GUI app with wxwidgets in C++ for one of my programming classes. We have to validate input and throw custom exceptions if it doesn't meet certain conditions. My question is, what is best practice when it comes to this? Should I write a seperate function that checks for errors, and have my event handler's ... | Throwing exceptions for this seems a little odd.
I've always felt that a GUI app should prevent invalid data from even being entered in a control, which can be done using event handlers. For data that is inconsistent between several controls on a form, that should be validated when OK is pressed or whatever, and if the... |
2,489,533 | 2,492,941 | What would be the safest way to store objects of classes derived from a common interface in a common container? | I'd like to manage a bunch of objects of classes derived from a shared interface class in a common container.
To illustrate the problem, let's say I'm building a game which will contain different actors. Let's call the interface IActor and derive Enemy and Civilian from it.
Now, the idea is to have my game main loop ... | As you have guessed you need to store the objects as pointers.
I prefer to use the boost pointer containers (rather than a normal container of smart pointers).
The reason for this is the boost ptr container access the objects as if they were objects (returning references) rather than pointers. This makes it easier to u... |
2,489,582 | 2,489,624 | implementing ioctl() commands in FreeBSD | I am adding some code to an existing FreeBSD device driver and I am trying to pass a char* from user space to the driver. I've implemented a custom ioctl() command using the _IOW macro like so: #define TIBLOOMFILTER _IOW(0,253,char*)
My call looks something like this:
int file_desc = open("/dev/ti0", O_RDWR);
ioctl(fi... | Did you register your ioctl handler with
.d_ioctl = ioctl_handler
in ?devsw (char/block device switch table)?
|
2,489,613 | 2,489,700 | How To Get System Folder Path(C:\Windows C:\Program Files) in Windows using C++? | I am programming in c++ MFC,
I want to get "C:\windows" "c:\program files" folder path.
Sometimes user may setup windows in other folder such as c:\windows0.
Is there any API to get absolute path of the windows and program files path?
Many thanks!
| Using Win32 API>
For the Windows folder:
TCHAR windir[MAX_PATH];
GetWindowsDirectory(windir, MAX_PATH);
For program files:
TCHAR pf[MAX_PATH];
SHGetSpecialFolderPath(
0,
pf,
CSIDL_PROGRAM_FILES,
FALSE );
Where MAX_PATH comes from the Windows headers and will guarantee the buffer is long enough for ... |
2,489,627 | 2,489,683 | Setting minimum number of decimal places for std::ostream precision | Is there a way to set the "minimum" number of decimal places that a std::ostream will output?
For example, say I have two unknown double variables that I want to print (values added here for the sake of illustration):
double a = 0;
double b = 0.123456789;
I can set my maximum decimal precision so that I output b exact... | I do not think there is a way to achieve what you are asking without turning the number into a string (with high precision), and stripping off the trailing zeros.
This is appropriate, because just because there are trailing zeros doesn't mean there isn't precision there, and the run-time can't tell that.
For example, i... |
2,489,833 | 2,489,885 | C++ : Math library that solve system of equations using back substitution algorithm | If I have this:
A * f = g;
A: upper triangular matrix (n x n)
f: (n x 1)
g: (n x 1)
Need to solve for f using back substitution algorithm. I would say that it not really that hard to write one myself, but oh well, if there is a library out there, then why not.
| Boost uBlas should work. At least if I understand your question correctly, you probably want to start by looking at lu_substitute() and inplace_solve().
|
2,489,914 | 2,489,922 | write application event information with Win32 API | .NET provides EventLog class that be able to write application event information to a particular log on the system. Is there simliar Win32 API that can be called with C++?
| I think you want Event Tracing for Windows:
http://msdn.microsoft.com/en-us/library/bb968803(VS.85).aspx
|
2,490,023 | 2,490,048 | How can I refactor this to use an inline function or template instead of a macro? | I have a useful macro here:
#include <algorithm>
#include <vector>
#include <string>
#include <boost/algorithm/string.hpp>
#include <Windows.h>
namespace Path {
bool Exists(const std::wstring& path)
{
DWORD result = GetFileAttributesW(path.c_str());
return result != INVALID_FILE_ATTRIBUTES;
}
// THIS IS THE ... | Pass the array by reference, using a template to infer the length. I'll go looking for an example, but basically:
template<size_t N>
bool func(const char (&a)[N], blah, blah) { ... }
EDIT: Someone explained it here:
http://heifner.blogspot.com/2008/04/c-array-size-determination.html
|
2,490,456 | 2,490,499 | How to use unnamed function arguments in C or C++ | How do I use function arguments declared like
void f(double)
{
/**/
}
if it is possible?
| I hope an example can provide some help:
// Declaration, saying there is a function f accepting a double.
void f(double);
// Declaration, saying there is a function g accepting a double.
void g(double);
// ... possibly other code making use of g() ...
// Implementation using the parameter - this is the "normal" way... |
2,490,526 | 2,490,607 | Calendar control GUI C++ library | Who knows a good component for a "calendar control" (NOT date/time picker)?
"Calendar control" means something like Mozilla Sunbird:
(source: mozilla.org)
Requirements to the control:
- C++;
- Day/Week/Month view;
- Support of several calendars;
- Without MFC dependences;
Nice to have:
- Open source;
- Cross plathf... | You are unlikely to find such a control ready made.
Even more unlikely to find one for C++ without MFC dependencies.
Your best bet is to implement it yourself.
|
2,490,573 | 2,490,585 | Strange behaviour with fputs and a loop | When running the following code I get no output but I cannot work out why.
# include <stdio.h>
int main()
{
fputs("hello", stdout);
while (1);
return 0;
}
Without the while loop it works perfectly but as soon as I add it in I get no output. Surely it should output before starting the loop? Is it just o... | You have to flush stdout. This happens automatically when you write a newline character. Change the fputs to:
fputs("hello\n", stdout);
Or to:
fputs("hello", stdout);
fflush(stdout);
|
2,490,583 | 2,490,696 | Discrete Curve evolution algorithm | i am trying to implement discrete curve evolution algorithm in c++ do any one help me with psudo code or c code or
some simple steps of your understanding
| I'm not exactly sure what you mean by Discrete Curve evolutionary algorithm, but if you mean a Symbolic regression algorithm, you can start by reading about symbolic regression (or genetic programming in general):
http://en.wikipedia.org/wiki/Symbolic_Regression
There's also some nice existing programs. The Eureqa one ... |
2,490,776 | 2,490,803 | How do I "unzip" a gzipped stream while reading it | My program is using HTTP to read gzipped files over the network.
I need my program to be able to unzip the content and parse it even when not all the gzipped file arrived yet.
Can it be done ?
If so, can it be done in C++ ? If so, how ?
| You could probably try out the gzstream library:
Gzstream is a small C++ library,
basically just a wrapper, that
provides the functionality of the zlib
C-library in a C++ iostream. It is
freely available under the LGPL
license.
|
2,490,804 | 2,542,440 | How to link Poco library(libraries) to our program in unix environment | I'm having trouble with Poco libraries. I need a simple solution to make the compilation easier. Is there any pkg-config file for Poco library to use it into our make files? Or any alternative solution?
Currently I use Ubuntu GNU/Linux.
I'm trying to use poco libraries in my app, but I don't know how to link Poco libra... | I don't think Poco comes with any pre-packaged ".pc" files but you should be able to create your own easily and stick them in the lib/pkgconfig directory on your system if you prefer that method.
I don't know exactly where you installed Poco on your system so you may have to do a "find" to locate your files. To compil... |
2,491,164 | 2,491,287 | Calling msi file in c from CreateProcess | Is there any option to call msi file from CreateProcess in c language in window OS.
| The Windows ShellExecute function will open a file of a registered type with the correct application, which I think is what you are asking about.
|
2,491,254 | 2,549,786 | "preprocess current file" addin for Visual Studio? (C++ ) | I realize that Visual Studio has the "/P" option to generate preprocessed files, but it's extremely inconvenient. I'm looking for an addin that allows you to right-click on a file and select "view preprocessed" - or any similar solution that would basically preprocess the currently-open file (with the appropriate optio... | There's no really elegant way of doing this using the External Tools menu, but here's a solution that will work:
Create a new configuration for your project. Call it something like "Debug-Preproc". In this configuration, set the /P switch for the compiler. (Preprocess, no compilation.)
Go to the External Tools setup m... |
2,491,379 | 2,491,411 | Function Pointer from base class | i need a Function Pointer from a base class. Here is the code:
class CActionObjectBase
{
...
void AddResultStateErrorMessage( const char* pcMessage , ULONG iResultStateCode);
...
}
CActionObjectCalibration( ): CActionObjectBase()
{
...
m_Calibration = new CCalibration(&CActionObjectBase::AddResultStateErrorMes... | You need to invoke m_AddErrorMessage on an object, something like:
(something->*m_AddErrorMessage)(...)
|
2,491,556 | 2,491,581 | Why does gcc think that I am trying to make a function call in my template function signature? | GCC seem to think that I am trying to make a function call in my template function signature. Can anyone please tell me what is wrong with the following?
227 template<class edgeDecor, class vertexDecor, bool dir>
228 vector<Vertex<edgeDecor,vertexDecor,dir>> Graph<edgeDecor,vertexDecor,dir>::vertices()
229 {
230 return... | You should put space between two >. >> is parsed as a bit-shift operator, not two closing brackets.
|
2,491,786 | 2,492,000 | copy constructor by address | I have two copy constructors
Foo(Foo &obj){
}
Foo(Foo *obj){
}
When will the second copy constructor will get called?
| Leaving aside that the second constructor isn't a copy constructor - you actually wanted to know when the second constructor will be called.
The Foo(Foo* obj); constructor is a single parameter constructor - because it hasn't been marked with the explicit keyword, it provides an implicit conversion from Foo* to Foo. It... |
2,492,020 | 2,492,341 | how to view contents of STL containers using GDB 7.x | I have been using the macro solution, as it is outlined here. However, there is a mention on how to view them without macros. I am referring to GDB version 7 and above.
Would someone illustrate how?
Thanks
| Get the python viewers from SVN
svn://gcc.gnu.org/svn/gcc/trunk/libstdc++-v3/python
Add the following to your ~/.gdbinit
python
import sys
sys.path.insert(0, '/path/to/pretty-printers/dir')
from libstdcxx.v6.printers import register_libstdcxx_printers
register_libstdcxx_printers (None)
end
Then print should just wor... |
2,492,318 | 2,492,395 | Is it undefined behavior in the case of the private functions call in the initializer list? | Consider the following code:
struct Calc
{
Calc(const Arg1 & arg1, const Arg2 & arg2, /* */ const ArgN & argn) :
arg1(arg1), arg2(arg2), /* */ argn(argn),
coef1(get_coef1()), coef2(get_coef2())
{
}
int Calc1();
int Calc2();
int Calc3();
private:
const Arg1 & arg1;
const Arg2 & arg2... |
12.6.2.8: Member functions (including virtual member functions, 10.3) can be called for an object under construction. Similarly,
an object under construction can be the operand of the typeid operator (5.2.8) or of a dynamic_cast (5.2.7). However,
if these operations are performed in a ctor-initializer (or in a fun... |
2,492,676 | 2,492,688 | error in C++, what to do ?: could not find an match for ostream::write(long *, unsigned int) | I am trying to write data stored in a binary file using turbo C++. But it shows me an error
could not find an match for ostream::write(long *, unsigned int)
I want to write a 4 byte long data into that file. When i tries to write data using char pointer. It runs successfully. But i want to store large value i.e. eg. ... | Cast it to a char*
long *lmem;
lmem=new long;
*lmem=Tsize;
fo.write(reinterpret_cast<char*>(lmem),sizeof(long));
delete lmem;
Or even better (as allocation on the stack is far faster and less error prone)
long lmem = Tsize;
fo.write(reinterpret_cast<char*>(&lmem),sizeof(long));
If Tsize is addressable and a long you ... |
2,492,775 | 2,493,977 | get local time with boost | I didn't find this in documentation: how to get local time (better formatted) with boost?
| Use posix_time to construct a time object from the system clock.
For example, this would output the current system time as an ISO-format string:
namespace pt = boost::posix_time;
pt::to_iso_string(pt::second_clock::local_time());
For formatting alternatives, see the “Conversion to String” section of the above-linked r... |
2,492,809 | 2,492,954 | #include headers in C/C++ | After reading several questions regarding problems with compilation (particularly C++) and noticing that in many cases the problem is a missing header #include. I couldn't help to wonder in my ignorance and ask myself (and now to you):
Why are missing headers not automatically checked and added or requested to the prog... | Remember the clash in Java between java.util.Date and java.sql.Date? If someone uses Date in their code, you can't tell whether they forgot import java.util.Date or import java.sql.Date.
In both Java and C++, it is not possible to tell with certainty what import/include statement is missing. So neither language tries. ... |
2,492,934 | 2,492,952 | C++ Reserve Memory Space | is there any way to reserve memory space to be used later by default Windows Memory Manager so that my application won't run out of memory if my program don't use space more than I have reserved at start of my program?
| There is no point in doing this kind of thing when you have virtual memory.
|
2,492,943 | 2,493,109 | boost::multi_array resize exception? | I'm trying to figure out if the boost::multi_array constructor or resize method can throw a bad_alloc exception (or some other exception indicating the allocation or resize failed). I can't find this information in the documentation anywhere.
Clarification (added from comment):
This is a scientific algorithm that can... | 1st: (answering the real question): As it uses dynamically allocated memory, yes, it can throw std::bad_alloc (I have never seen boost translation std::bad_alloc exceptions; it would be crazy to do so).
2nd: (comment on your clarification): You do need the information of available physical memory to optimize the perfor... |
2,492,966 | 2,492,979 | OpenGL: Disable texture colors? | Is it possible to disable texture colors, and use only white as the color? It would still read the texture, so i cant use glDisable(GL_TEXTURE_2D) because i want to render the alpha channels too.
All i can think of now is to make new texture where all color data is white, remaining alpha as it is.
I need to do this wit... | What about changing all texture color (except alpha) to white after they are loaded and before they are utilized in OpenGL? If you have them as bitmaps in memory at some point, it should be easy and you won't need separate texture files.
|
2,493,131 | 2,493,231 | Which type of design pattern should be used to create an emulator? | I have programmed an emulator, but I have some doubts about how to organizate it properly, because, I see that it has some problems about classes connection (CPU <-> Machine Board).
For example: I/O ports, interruptions, communication between two or more CPU, etc.
I need for the emulator to has the best performance an... | You have two closely-related things going on here.
The emulator is a collection of Command definitions. Each thing the emulator can do is a command. Some commands are nested sequences of commands.
The emulator has a number of internal State definitions. Each thing the emulator does updates one or more state objec... |
2,493,227 | 2,493,377 | Pitfalls when converting C++/CLI to C++ | I have a library written in C++/CLI and I want to open it up. I want it to be as cross-platform as possible and be able to write bindings to it for other languages to use (Java, Python, etc, etc). To do this, the library needs to be in plain C++ for maximum flexibility. I figure that the logical structures are already ... | It might be more trouble than it's worth. Here is what you might come across:
There is no garbage collection in C++. This is the big one. This may require a significant redesign of your library just to convert. If you are using at least C++ tr1, or the boost library, you can sort of get there by using shared_ptr, but ... |
2,493,229 | 2,493,273 | C++ is there a difference between assignment inside a pass by value and pass by reference function? | Is there a difference between foo and bar:
class A
{
Object __o;
void foo(Object& o)
{
__o = o;
}
void bar(Object o)
{
__o = o;
}
}
As I understand it, foo performs no copy operation on object o when it is called, and one copy operation for assignment. Bar performs one copy operation on obj... | It depends. For example, if the compiler decides to inline the function, obviously there will be no copy since there is no function call.
If you want to be sure, pass by const-reference:
void bar(const Object& o)
This makes no copies. Note your non-const version requires an lvalue, because the reference is mutable. fo... |
2,493,257 | 2,501,751 | Is there a way to use Qt's unit testing modules as part of a Code::Blocks project with the QtWorkbench plugin? | We're developing a Qt project using the Code::Blocks IDE with the QtWorkbench plugin. We'd like to take advantage of Qt's unit testing modules to test our code, but from what I've read online, the only way to do so is to use qmake to manually create a new "project" and makefile for each unit test and then to build and ... | http://www.archivum.info/qt-interest@trolltech.com/2008-09/00297/Re:-Usage-of-QTestLib.html
http://qtcreator.blogspot.com/2009/10/automatically-running-unit-tests.html
|
2,493,297 | 2,493,424 | Appending to QList of QList | I'm trying to append items to a QList at runtime, but I'm running on a error message. Basically what I'm trying to do is to make a QList of QLists and add a few customClass objects to each of the inner lists. Here's my code:
widget.h:
class Widget : public QWidget
{
Q_OBJECT
public:
Widget(QWidget *parent = 0)... | Qt Reference says:
const T & at ( int i ) const
but not:
T& at ( int i )
so there's no non-const version of at. You have to use operator[] instead.
So change it to:
mylist[z].append(co);
and it will work. I even tested it.
I think the foreach version doesn't work, because in foreach(QList<customClass> list, myli... |
2,493,372 | 2,495,250 | How to properly recreate BITMAP, that was previously shared by CreateFileMapping()? | Dear friends, I need your help.
I need to send .bmp file to another process (dialog box) and display it there, using MMF(Memory Mapped File)
But the problem is that image displays in reversed colors and upside down.
Here's source code:
In first application I open picture from HDD and link it to the named MMF "Gigabyte_... | pbData points to begin of bitmap data, which points to bitmap header.
Give SetBitmapBits pointer to raw data: pbData + header size + optional pallete.
|
2,493,431 | 2,493,450 | C++, array of objects without <vector> | I want to create in C++ an array of Objects without using STL.
How can I do this?
How could I create array of Object2, which has no argumentless constructor (default constructor)?
| If the type in question has an no arguments constructor, use new[]:
Object2* newArray = new Object2[numberOfObjects];
don't forget to call delete[] when you no longer need the array:
delete[] newArray;
If it doesn't have such a constructor use operator new to allocate memory, then call constructors in-place:
//do for... |
2,493,482 | 2,493,668 | Can I write functors using a private nested struct? | Given this class:
class C
{
private:
struct Foo
{
int key1, key2, value;
};
std::vector<Foo> fooList;
};
The idea here is that fooList can be indexed by either key1 or key2 of the Foo struct. I'm trying to write functors to pass to std::find_if so I can look up items in... | I'd do something like this.
Header:
class C
{
private:
struct Foo
{
int index;
Bar bar;
};
// Predicates used to find Notification instances.
struct EqualIndex;
struct EqualBar;
std::vector<Foo> fooList;
};
Source:
// Predicate for finding a Foo instance by index.
struct C... |
2,493,593 | 2,493,899 | QuantLib starter guide | Is there a good starter document on quantlib (http://quantlib.org)? The examples are not well documented, and the help does not give that much insight.
| Well there are
hundreds of unit tests,
a dozen or more examples
over 1000 pages of Doxygen-generated documentation
several introductory book chapters on the design drafted by Luigi (lead developer)
All this is complicated because the topic is complicated. The No Free Lunch theorem seems to hold for code too ;-)
Tha... |
2,493,600 | 2,493,610 | What is wrong with this C++ Code? | i am a beginner and i have a problem :
this code doesnt compile :
main.cpp:
#include <stdlib.h>
#include "readdir.h"
#include "mysql.h"
#include "readimage.h"
int main(int argc, char** argv) {
if (argc>1){
readdir(argv[1]);
// test();
return (EXIT_SUCCESS);
}
std::cout << "Bitte Pfad angeben !"... | In readimage.h, you are missing a semicolon after your readImage function declaration.
|
2,493,687 | 2,520,519 | Development environment to use/learn VTK with C++ | I am a newbie with VTK and C++ (but am well versed in the concepts/Java etc). I will eventually need to use both QT and VTK for my project. I would like to know if there is a development environment or editor for VTK (using C++) similar to VTK Designer? With VTK Designer I am very disappointed that there is no feature ... | I've been working with VTK/Qt for a while, and I doubt there is something like VTK Designer that will convert a pipeline to C++ code.
Everything will need to be hand coded in - and its fairly simple. If you are not sure about the exact C++ implementation of your pipeline, I recommend looking at the VTK samples / tests ... |
2,493,785 | 2,493,808 | How I can print the wchar_t values to console? | Example:
#include <iostream>
using namespace std;
int main()
{
wchar_t en[] = L"Hello";
wchar_t ru[] = L"Привет"; //Russian language
cout << ru
<< endl
<< en;
return 0;
}
This code only prints HEX-values like adress.
How to print the wchar_t string?
| Edit: This doesn’t work if you are trying to write text that cannot be represented in your default locale. :-(
Use std::wcout instead of std::cout.
wcout << ru << endl << en;
|
2,494,044 | 2,494,182 | Sorting a string array in C++ no matter of 'A' or 'a' and with å, ä ö? | How do you sort an array of strings in C++ that will make this happen in this order:
mr Anka
Mr broWn
mr Ceaser
mR donK
mr ålish
Mr Ätt
mr önD
//following not the way to get that order regardeless upper or lowercase and å, ä, ö
//in forloop...
string handle;
point1 = array1[j].find_first_of(' ');
string forename1(arra... | Tables and transformations.
I would first convert the string to either all uppercase or all lowercase:
#include <cctype>
#include <algorithm>
#include <string>
std::string test_string("mR BroWn");
std::transform(test_string.begin(), test_string.end(),
test_string.begin(),
std::tolower);... |
2,494,062 | 2,494,470 | Managed .NET Equivalent to CreateFile & WriteFile from WinBase (kernel32.dll) | I am working with a legacy file format.
The file is created using unmanaged C++ that utilizes the WinBase.h CreateFile() & WriteFile() functions (found in the kernel32.dll).
I have been using P/Invoke interop to access these native functions like so:
[DllImport("kernel32.dll")]
public static extern bool Write... | WriteFileEx only runs asynchronously, you must provide a SEPARATE instance of OVERLAPPED for each pending call, and you must setup the OVERLAPPED members, such as the file offset. Then you can't call CloseHandle until all the operations finish. And using a local variable for OVERLAPPED and letting it go out of scope?... |
2,494,391 | 2,494,591 | Is there a size limit on WritePrivateProfileStruct? | I'm trying to write an INI file using the WritePrivateProfileString and WritePrivateProfileStruct functions.
I found that when the byte count is relatively low, WritePrivateProfileStruct and GetPrivateProfileStruct work fine, but with a higher byte count (62554 bytes in my case), the Write function seems to work but t... | Yes, I repro. The largest buffer I can read back is 32766 bytes. Larger values produce ERROR_BAD_LENGTH. With the checksum and the terminating zero, looks to me that it uses an internal buffer that is (32766+2) * 2 = 65536 bytes long. Makes somewhat sense, this is a legacy 16-bit API.
You really ought to consider u... |
2,494,471 | 2,494,478 | C++, is it possible to call a constructor directly, without new? | Can I call constructor explicitly, without using new, if I already have a memory for object?
class Object1{
char *str;
public:
Object1(char*str1){
str=strdup(str1);
puts("ctor");
puts(str);
}
~Object1(){
puts("dtor");
puts(str);
free(str);
}
};
Object... | Sort of. You can use placement new to run the constructor using already-allocated memory:
#include <new>
Object1 ooo[2] = {Object1("I'm the first object"), Object1("I'm the 2nd")};
do_smth_useful(ooo);
ooo[0].~Object1(); // call destructor
new (&ooo[0]) Object1("I'm the 3rd object in place of first");
So, you'r... |
2,494,610 | 2,494,621 | C++ function call routes resolver | I'm looking for a tool that will tell/resolve for every function all the call paths (call it "routes") to it.
For example:
void deeper(int *pNumber)
{
*pNumber++;
}
void gateA(int *pNumber)
{
deeper(pNumber);
}
void gateB(int *pNumber)
{
gateA(pNumber);
}
void main()
{
int x = 123;
gateA(&x);
gateB(&x);
}
See?
... | Doxygen will do that for you. It'll draw you nice inheritance trees and show you everyone who is calling (and called by) your functions.
|
2,494,862 | 2,494,998 | Reading a stream in C++ | I have the following code:
ifstream initFile;
initFile.open("D:\\InitTLM.csv");
if(initFile.is_open())
{
// Process file
}
The file is not opening. The file does exist on the D: drive. Is there a way to find out exactly why this file cannot be found? Like an "errno"?
| You should be able to use your OS's underlying error reporting mechanism to get the reason (because the standard library is built on the OS primitives). The code won't be portable, but it should get you to the bottom of your issue.
Since you appear to be using Windows, you would use GetLastError to get the raw code an... |
2,495,000 | 2,579,699 | Optimal Eclipse CDT (C++) experience in March of 2010 | I am a student who will be using C++ next quarter. I really enjoyed using the Galileo release of Eclipse with Java and I would like to continue using Eclipse for for C++ development.
I am now experimenting with C++ development on Eclipse. I am running Eclipse 3.5 SR2 with CDT 6.02. My operating system is Windows 7 and ... | Here is what I ended up with for a C++ development environment on Windows 7.
Compiler & libraries
Nuwen MinGW Distro.
It includes the Boost libraries which are necessary for the unit testing framework.
A big thanks to Stephan T. Lavavej for making this distribution available.
Debugger
The GNU debugger as built for ... |
2,495,102 | 2,495,385 | Qt C++ XML, validating against a DTD? | Is there a way to validate an XML file against a DTD with Qt's XML handling? I've tried googling around but can't seem to get a straight answer. If Qt doesn't include support for validating an XML file, what might be the process of implementing validation myself? Any good reference to start with in regards to validatin... | You can validate your XML with this : http://qt.nokia.com/doc/4.6/qxmlschema.html
You can also find an example here : XML Schema Validation Example
Hope it helps a bit !
|
2,495,188 | 2,495,231 | How to add canvas in MFC Dialog? | I want to create an application which main window has canvas (or something where I can draw custom things) and some controls, like buttons and edit fields. But I got stuck about how to do it.
I tried to create MFC with SDI, but how to add control to CDC..?
I tried to create one dialog with buttons and edit fields, but ... | Its been a few years for me, but here goes:
I don't think that MFC has a specific canvas control. Instead, when I wanted a drawing surface, I added a group box to the form in design mode. I made the group box invisible, so it would not show up at runtime.
In the OnCreate handler for the form view, I created a CWnd, and... |
2,495,198 | 2,586,872 | Unable to run OpenMPI across more than two machines | When attempting to run the first example in the boost::mpi tutorial, I was unable to run across more than two machines. Specifically, this seemed to run fine:
mpirun -hostfile hostnames -np 4 boost1
with each hostname in hostnames as <node_name> slots=2 max_slots=2. But, when I increase the number of processes to 5,... | The answer turned out to be simple: open mpi authenticated via ssh and then opened up tcp/ip sockets between the nodes. The firewalls on the compute nodes were set up to only accept ssh connections from each other, not arbitrary connections. So, after updating iptables, hello world runs like a champ across all of th... |
2,495,254 | 2,499,817 | Qt send signal to main application window | I need a QDialog to send a signal to redraw the main window.
But connect needs an object to connect to.
So I must create each dialog with new and explicitly put a connect() every time.
What I really need is a way of just sending MainWindow::Redraw() from inside any function and having a single connect() inside Mainwind... | Let clients post CustomRedrawEvents to the QCoreApplication.
class CustomRedrawEvent : public QEvent
{
public:
static Type registeredEventType() {
static Type myType
= static_cast<QEvent::Type>(QEvent::registerEventType());
return myType;
}
CustomRedrawEvent() : QEvent(reg... |
2,495,262 | 2,495,408 | Unreachable breakpoint at execut(able/ing) code | I've got two DLLs, one in written in native C++ and the other in C++/CLI. The former is injected into a process, and at a later point in time, loads the latter. While debugging, I noticed that the native DLL's breakpoints were functioning correctly while the other's weren't, even though its code was being executed.
Th... | The reason for what you faced is that the PDBs ("PDB stands for Program Database, a proprietary file format (developed by Microsoft) for storing debugging information about a program) are not up-to-date.
Try to clean the solution (that contains the managed code DLL) and rebuild it again.
Tip: if you are referring to th... |
2,495,266 | 2,495,416 | Switching to Java from C++: What are the key points? | I'm an experienced developer, but most of my OO programming experience has been with C++ (and a little Delphi). I'm considering doing some Android work, hence Java.
Coming from the C++ background, what areas of Java are most likely to surprise/annoy/delight me?
I felt sure this would already have been asked, but my sea... | surprise:
Almost everything is on the heap
It can be as fast as C++, even faster in a few cases
The autoboxing of primitives will occasionally cause headaches
annoy:
no unsigned integer types
no preprocessor directives of any kind
no operator overloading
generics are castrated templates
delight:
blessedly quick c... |
2,495,316 | 2,495,334 | Choice for Socket Server Application: C/C++ or C# | What would be the most sensible choice for building a socket server application, assuming that you had the luxury of choosing between C/C++ or Csharp, and you intend to run multiple instances of the same server on both Windows and Linux servers?
| If you can get the service to run on .NET in Windows and Linux (via Mono), C# is probably the "easier" environment to work with in terms of development.
The C++ route may be a little trickier - you'll have to compile the code for both Linux and Windows, which can get tricky if you're doing low-level/platform-dependent ... |
2,495,348 | 2,495,754 | how can exec change the behavior of exec'ed program | I am trying to track down a very odd crash. What is so odd about it is a workaround that someone discovered and which I cannot explain.
The workaround is this small program which I'll refer to as 'runner':
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
int main(int argc, char *argv[])
{... | It's possible that the .so files loaded by the runner are causing the runee to work correctly. Try ldd'ing each of the binaries and see if any libraries are loading different versions/locations.
|
2,495,420 | 2,496,831 | Is there any LAME C++ wrapper\simplifier (working on Linux Mac and Win from pure code)? | I want to create simple pcm to mp3 C++ project. I want it to use LAME. I love LAME but it's really big. so I need some kind of OpenSource working from pure code with pure lame code workflow simplifier. So to say I give it File with PCM and DEST file. Call something like:
LameSimple.ToMP3(file with PCM, File with MP3 , ... | Lame really isn't difficult to use, although there are a lot of optional configuration functions if you need them. It takes slightly more than 4-5 lines to encode a file, but not much more. Here is a working example I knocked together (just the basic functionality, no error checking):
#include <stdio.h>
#include <lame/... |
2,495,460 | 2,522,873 | How to change a QMenu text from english to russian by clicking a button | Please consider we have a menu which has text set "MyMenu" and I want to change the menu text by clicking a button in the same widget from "MyMenu" to "МойМеню". Could you bring a code snippet please for that operation?
| int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QTextCodec::setCodecForTr(QTextCodec::codecForName("UTF-8"));//this is the solution
.............
}
And in the code you can dynamically change the strings if you set them from the begining by using tr() function [tr("your text")].
|
2,495,485 | 2,495,578 | Using new (this) to reuse constructors | This came up recently in a class for which I am a teaching assistant. We were teaching the students how to do copy constructors in c++, and the students who were originally taught java asked if you can call one constructor from another. I know the answer to this is no, as they are using the pedantic flag for their code... | C++0x will introduce syntax to allow constructors to call other constructors.
Until then, new(this) works in some cases, but not all. In particular, once in the constructor, your base class(es) are already fully constructed. Reconstructing via new(this) re-calls the base constructors without calling the base destructo... |
2,495,503 | 2,496,328 | Using Fortran to call C++ Functions | I'm trying to get some FORTRAN code to call a couple c++ functions that I wrote (c_tabs_ being one of them). Linking and everything works just fine, as long as I'm calling functions that don't belong to a class.
My problem is that the functions I want the FORTRAN code to call belong to a class. I looked at the symbol t... | If you make the C++ routine have a C-style interface (as described already), then you can use the ISO C Binding feature of Fortran 2003 to call it. With the ISO C Binding, you can specify the name of the routine and (within limits) the C-types and calling conventions (reference, by value) of the arguments and functio... |
2,496,338 | 2,496,366 | Are C files renamed to C++ are going to be compilable with C++ compilers after renaming? | C files renamed to C++ are going to be compilable with C++ compilers after renaming?
So I have 25 C files and 1 C++ file I do not want to create Make files or anething like that. I want to turn all that C files into C++ so will simple renaming work or what shall I do?
| In general, yes. You will have to worry about variables named class and such, the sizeof a character literal, and name mangling, and some other rarely encountered issues. If you're converting C99 to C++, you'll have to drop some C99 features.
With regards to name mangling, reference any C symbols by using extern "C".... |
2,496,471 | 2,496,647 | Extracting pair member in lambda expressions and template typedef idiom | I have some complex types here so I decided to use nifty trick to have typedef on templated types. Then I have a class some_container that has a container as a member. Container is a vector of pairs composed of element and vector. I want to write std::find_if algorithm with lambda expression to find element that have c... | Two issues.
The thing that you are going after (element<T>::value) is not a typename.
However, firstly you'll need nested binds: one to access _1.first and another one to access the value of the previous.
Without the typedefs:
std::find_if(
container.begin(), container.end(),
bind(
&element<T>::value,
... |
2,496,631 | 2,534,987 | Can you get access to the NumberFormatter used by ICU MessageFormat | This may be a niche question but I'm working with ICU to format currency strings. I've bumped into a situation that I don't quite understand.
When using the MesssageFormat class, is it possible to get access to the NumberFormat object it uses to format currency strings. When you create a NumberFormat instance yourself,... | I've determined that gaining access to the internal formatter used is not possible. I've opened a ticket with the ICU project. http://bugs.icu-project.org/trac/ticket/7571#preview
|
2,496,689 | 2,496,728 | not so obvious pointers | I have a class :
class X{
public :
void f ( int ) ;
int a ;
} ;
And the task is "Inside the code provide declarations for :
pointer to int variable of class X
pointer to function void(int) defined inside class X
pointer to double variable of class X"
Ok so pointer to int a will be just int *x = &a, right ? If the... | These are called pointers to members. They are not regular pointers, i.e. not addresses, but "sort-of" offsets into an instance of the class (it gets a bit tricky with virtual functions.) So:
int X::*ptr_to_int_member;
void (X::*ptr_to_member_func)( int );
double X::*ptr_to_double_member;
|
2,496,742 | 2,496,757 | Why won't C++ allow this default value? | Why won't GCC allow a default parameter here?
template<class edgeDecor, class vertexDecor, bool dir>
Graph<edgeDecor,int,dir> Graph<edgeDecor,vertexDecor,dir>::Dijkstra(vertex s, bool print = false) const
{
This is the output I get:
graph.h:82: error: default argument given for parameter 2 of ‘Graph<edgeDecor, int,... | You seem to already have declared the function (including the default parameter) in graph.h, line 36. Don't repeat the default value in the function implementation, specifying it one time in the declaration is enough.
|
2,496,902 | 2,496,909 | An interesting case of delete and destructor (C++) | I have a piece of code where I can call the destructor multiple times and access member functions even the destructor was called with member variables' values preserved. I was still able to access member functions after I called delete but the member variables were nullified (all to 0). And I can't double delete. Pleas... | This is an exhibit of undefined behavior. Call a member function through a pointer that's been deleted and anything goes - the compiler and runtime aren't required to check for this error, but you certainly can't count on this working.
This falls into a similar category as using memory that's been freed - you might fi... |
2,496,950 | 2,496,978 | setting library include paths in c++ | I just installed gd2 using mac ports (sudo install gd2), which installed libraries in the following places:
/opt/local/include/gd.h
/opt/local/lib/libgd.dylib (link)
/opt/local/lib/libgd.la
/opt/local/lib/libgd.a
Here is my make file also:
dev: main.o
g++ -L/opt/local/lib -I/opt/local/include -lgd -lpng -lz -ljpeg... | Rather than invoke g++ directly, I strongly advise you to use CMake (watch the CMake Google Techtalk if you'd like to learn more) as it will make your life way easier and greatly simplifies locating and linking against a variety of libraries. That said, I believe the problem with your invocation is that you have not sp... |
2,497,151 | 2,497,191 | Can the C++ `new` operator ever throw an exception in real life? | Can the new operator throw an exception in real life?
And if so, do I have any options for handling such an exception apart from killing my application?
Update:
Do any real-world, new-heavy applications check for failure and recover when there is no memory?
See also:
How often do you check for an exception in a C++ n... | The new operator, and new[] operator should throw std::bad_alloc, but this is not always the case as the behavior can be sometimes overridden.
One can use std::set_new_handler and suddenly something entirely different can happen than throwing std::bad_alloc. Although the standard requires that the user either make me... |
2,497,211 | 2,498,022 | How to profile multi-threaded C++ application on Linux? | I used to do all my Linux profiling with gprof.
However, with my multi-threaded application, it's output appears to be inconsistent.
Now, I dug this up:
http://sam.zoy.org/writings/programming/gprof.html
However, it's from a long time ago and in my gprof output, it appears my gprof is listing functions used by non-main... | Edit: added another answer on poor man's profiler, which IMHO is better for multithreaded apps.
Have a look at oprofile. The profiling overhead of this tool is negligible and it supports multithreaded applications---as long as you don't want to profile mutex contention (which is a very important part of profiling multi... |
2,497,248 | 2,497,260 | How does one obtain the Windows installation date, without using WMI? | Not much to say about this question...
| It's stored in the registry under HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion in the InstallDate key. The value is an integer number of seconds since 1/1/1970 (i.e. "Unix" time)
|
2,497,541 | 2,497,564 | C++ best practice: Returning reference vs. object | I'm trying to learn C++, and trying to understand returning objects. I seem to see 2 ways of doing this, and need to understand what is the best practice.
Option 1:
QList<Weight *> ret;
Weight *weight = new Weight(cname, "Weight");
ret.append(weight);
ret.append(c);
return &ret;
Option 2:
QList<Weight *> *ret = new Q... | Option 1 is defective. When you declare an object
QList<Weight *> ret;
it only lives in the local scope. It is destroyed when the function exits. However, you can make this work with
return ret; // no "&"
Now, although ret is destroyed, a copy is made first and passed back to the caller.
This is the generally preferr... |
2,497,726 | 2,497,816 | What makes this "declarator invalid"? C++ | I have Vertex template in vertex.h. From my graph.h:
20 template<class edgeDecor, class vertexDecor, bool dir>
21 class Vertex;
which I use in my Graph template.
I've used the Vertex template successfully throughout my Graph, return pointers to Vertices, etc. Now for the first time I am trying to declare and instantia... | Igor is right. As for the following error:
graph.h:88: error: expected type-specifier before ‘Vertex’
... you probably need to say:
Vertex<edgeDecor,int,dir> v = new Vertex<edgeDecor,int,dir>(INT_MAX);
|
2,497,753 | 2,497,770 | C++ Variable declarable in function body, but not class member? | I want to create a C++ class with the following type:
It can be declared inside of a function.
It can be declared inside of a member function.
It can not be declared as a class member.
The use of this: think "Root" objects for a GC.
Is this possible in C++? In particular, I'm using g++. Willing to switch to clang. Ei... | You could do it with a macro, perhaps:
#define MY_TYPE \
do { } while(0); \
RealType
void foo() {
MY_TYPE myvar;
myvar.Whatever();
}
This would only compile inside a function (because of the "do ... while" bit - though you'd get a really weird error message). It seems like one of those "evil" uses of ... |
2,497,943 | 2,498,084 | Tips Unit testing modal class in passive view pattern | I am new to unit testing. I have done unit testing on controller classes but have never tested modal class. I am using passive view pattern for my application.
I am using Cpp Unit test framework.
Any tips would be highly appreciated.
Thanks
Rahul
| You can create a base class that will be an interface for your modal class. Your modal class will inherit from this base class. The class(es) using the modal class will only know that base class.
For the unit tests, you implement another class, dedicated solely to unit testing, based on the base class (interface) and ... |
2,498,008 | 2,498,053 | In a C++ template, is it allowed to return an object with specific type parameters? | When I've got a template with certain type parameters, is it allowed for a function to return an object of this same template, but with different types? In other words, is the following allowed?
template<class edgeDecor, class vertexDecor, bool dir>
Graph<edgeDecor,int,dir> Graph<edgeDecor,vertexDecor,dir>::Dijkstra(ve... | Allowed. Some corrections to your code sample:
template<class edgeDecor, class vertexDecor, bool dir>
Graph<edgeDecor,int,dir> *Graph<edgeDecor,vertexDecor,dir>::Dijkstra(vertex s, bool
print = false) const
{
/* Construct new Graph with apropriate decorators */
Graph<edgeDecor,int,dir> *span = new Graph<edgeDe... |
2,498,009 | 2,498,054 | Best way to encrypt a directory of files? | I need to programatically encrypt a directory of files, like in a .zip or whatever. Preferably password protected obviously.
How can I accomplish this, and WHAT IS the BEST encryption way to do it, if applicable?
Programming language doesn't matter. I am dictioned in all syntax.
|
How can I accomplish this, and WHAT IS
the BEST encryption way to do it, if
applicable?
tar and gzip the directory.
Generate a random bit stream of equal size to the file
Run bitwise XOR on the streams
Only truly secure method is a truly random one time pad.
|
2,498,072 | 2,498,357 | how to print correctly the handling thread on Windows? | Could someone please tell us on how to print correctly the handling thread in windows? Actually I tried several ways but it doesn't return the right number as in Unix-variant, as such e.g.:
cout << " with thread " << pthread_self << endl;
cout << " with thread " << pthread_self().p << endl;
Thanks for your replies:
| GetCurrentThread returns a "pseudohandle", not a valid thread handle. You should use "GetCurrentThreadId" instead (or ::GetCurrentThreadId()), and include windows.h, of course.
|
2,498,119 | 2,498,129 | How do I get a part of the a string in C++? | How do I get a part of a string in C++? I want to know what are the elements from 0 to i.
| You want to use std::string::substr. Here's an example, shamelessly copied from http://www.cplusplus.com/reference/string/string/substr/
// string::substr
#include <iostream>
#include <string>
using namespace std;
int main ()
{
string str="We think in generalities, but we live in details.";
... |
2,498,183 | 2,498,200 | Which to use - "operator new" or "operator new[]" - to allocate a block of raw memory in C++? | My C++ program needs a block of uninitialized memory and a void* pointer to that block so that I can give it to a third party library. I want to pass control of the block lifetime to the library, so I don't want to use std::vector. When the library is done with the block it will call a callback that I have to supply an... | Use new with a single object and new[] with an array of objects. So, for example:
int* x = new int; // Allocates single int
int* y = new int[5]; // Allocates an array of integers
*x = 10; // Assignment to single value
y[0] = 8; // Assignment to element of the array
If all you are doing is allocating a memory buffer,... |
2,498,435 | 2,499,924 | Declaration of template class member specialization | When I specialize a (static) member function/constant in a template class, I'm confused as to where the declaration is meant to go.
Here's an example of what I what to do - yoinked directly from IBM's reference on template specialization:
===IBM Member Specialization Example===
template<class T> class X {
public:
s... | Usually you'd just define the specializations inline in the header as dirkgently said.
You can define specializations in seperate translation units though if you are worried about compilation times or code bloat:
// x.h:
template<class T> struct X {
void f() {}
}
// declare specialization X<int>::f() to exist some... |
2,498,443 | 2,499,701 | Login to a remote machine & accessing network resources | I want to access a file on remote machine(win2k3, 10.10.20.30), but i couldn't understand how to login to that machine in my program. is there any simple win api that takes network path, credentials and returns the handle?
i just want to access \10.10.20.30\c$\test.txt,
WNetAddConnection2, WNetAddConnection3 are littl... | If you have administrator rights, the solution is fairly simple. The C$ administrative share is available. You can call WNetAddConnection2 to create a local driveletter pointing to it. NETRESOURCE.dwType = RESOURCETYPE_DISK of course, .lpLocalName = NULL as you don't need it, .lpRemoteName = _T("\\\\10.10.20.30\\c$") (... |
2,498,755 | 2,498,930 | How do I send floats in window messages | What is the best way to send a float in a windows message using c++ casting operators?
The reason I ask is that the approach which first occurred to me did not work. For the record I'm using the standard win32 function to send messages:
PostWindowMessage(UINT nMsg, WPARAM wParam, LPARAM lParam)
What does not work:
... | Use reinterpret_cast< WPARAM &>(f). This cast is not restricted to pointers, it also works with references.
|
2,498,906 | 2,498,946 | Imbricated C++ template | I have the following pattern:
template <int a, int b>
class MyClass
{
public:
template <int c>
MyClass<a, c> operator*(MyClass<b, c> const &other) const;
};
// ../..
template <int a, int b> template <int c>
MyClass<a, c> MyClass<a, b>::operator*(MyClass<b, c> const &other) const //< error here
{
MyClass<a, c> r... | The following code compiles fine for me (as it should).
template <int a, int b>
struct MyClass
{
template <int c>
MyClass<a, c> operator*(MyClass<c, b> const &other) const;
};
template <int a, int b> template <int c>
MyClass<a, c> MyClass<a, b>::operator*(MyClass<c, b> const &other) const
{
MyClass<a, c> r... |
2,498,912 | 2,499,451 | C/C++ method parameter hints in Eclipse | is there any way how to enable Eclipse to show hints for parameters of C/C++ functions.
When I press Ctrl + Shift + Space it shows only types of parameters but not the names.
And is there also any way Eclipse can show parameter hints automatically when ( is pressed?
Thanks for any advice.
| Are you using the CDT plugin? If so which version? The following applies to Eclipse 3.5 (Galileo) with the CDT plugin. If your setup is different then the rest of this answer may not be accurate.
Ctrl + Space brings up the type and names of parameters for me.
Looking through the preferences (Window -> Preferences ->... |
2,498,978 | 2,499,421 | Loading and storing encryption keys from a config source | I am writing an application which has an authenticity mechanism, using HMAC-sha1, plus a CBC-blowfish pass over the data for good measure. This requires 2 keys and one ivec.
I have looked at Crypto++ but the documentation is very poor (for example the HMAC documentation). So I am going oldschool and use Openssl. Whats... | This is the solution I am going for atm. Unless of course someone comes up with a better one, or one that solves my specific problem.
I will put three files in /etc/acme/auth/file1 file2 and file3, binary files with randomly generates numbers for the 2 keys and the ivec, and do the same in windows but under c:\etc\acme... |
2,499,108 | 2,499,174 | List login sessions on a mac | I'm writing an application that runs as a system daemon (root session) for Mac OSX 10.6. As part of this application, I need to list all the active graphical login sessions.
There is an (undocumented, but public) function called SessionGetInfo which will give me more information about a session with a known session Id,... | If you're on Mac OSX 10.5+, according to this document from Apple you could use the utmpx API.
Some example code can be found here.
Hope this is helpful.
|
2,499,122 | 2,499,164 | Whats going on here can't you compare if(mychar1 == 'ä' || mychar2 == 'Ä') in C++? | Im trying to compare these two chars but on win 32 Visual Studio 2008:
if(mychar1 == 'ä' || mychar2 == 'Ä')
Erromess:
Debug Assertion Failed!
File:f\dd\vctools\crt_bld\self_x86\crt\src\xstring
Line 1575
Expression: string subscript out of range
| Works on my machine:
#include <iostream>
int main()
{
char mychar1, mychar2;
std::cin >> mychar1 >> mychar2;
if(!std::cin)
return 2;
if(mychar1 == 'ä' || mychar2 == 'Ä' )
return 1;
std::cout << "No!\n";
return 0;
}
Note that the error you quote ("string subscript out of range")... |
2,499,216 | 2,499,258 | What are the differences between break and exit? | Even I used break() and exit() statements many times, I am bit confused between them. I need to know exact meaning of both, when we should use them. Please explain with small example.
Thank you.
| break is a keyword that exits the current construct like loops. exit is a non-returning function that returns the control to the operating system. For example:
// some code (1)
while(true)
{
...
if(something)
break;
}
// some code (2)
In the above code, break exits the current loop which is the while loop. ... |
2,499,674 | 2,499,702 | c++: Is it possible to #include inside a function body? | I want to include a header file only if a certain function body is called?
Is this possible or recommended in C++?
| No.
You've got it a bit wrong; #include is not processed at run-time, at all. It's not possible to #include a file based on a program's execution characteristics; once the program executes its source is fixed (since it's already compiled).
|
2,499,842 | 2,499,968 | How to get statistical distributions out of C++ Code? | I want some help in programming a random generator for different types of distribution using C++ language. for the following:
Geometric distribution
Hypergeometric distribution
Weibull distribution
Rayleigh distribution
Erlang distribution
Gamma distribution
Poisson distribution
Thanks.
| The Boost Random Number library is very good. There's a simple example of how its distributions work at Boost random number generator.
|
2,499,895 | 2,500,544 | What's the purpose of having a separate "operator new[]"? | Looks like operator new and operator new[] have exactly the same signature:
void* operator new( size_t size );
void* operator new[]( size_t size );
and do exactly the same: either return a pointer to a big enough block of raw (not initialized in any way) memory or throw an exception.
Also operator new is called intern... | In Design and Evolution of C++ (section 10.3), Stroustrup mentions that if the new operator for object X was itself used for allocating an array of object X, then the writer of X::operator new() would have to deal with array allocation too, which is not the common usage for new() and add complexity. So, it was not cons... |
2,500,109 | 2,578,467 | C++ printf std::vector | How I can do something like this in C++:
void my_print(format_string) {
vector<string> data;
//Fills vector
printf(format_string, data);
}
my_print("%1$s - %2$s - %3$s");
my_print("%3$s - %2$s);
I have not explained well before. The format string is entered by the application user.
In C# this works:
void my... | I have temporarly solved with this function:
string format_vector(string format, vector<string> &items)
{
int counter = 1;
replace_string(format,"\\n","\n");
replace_string(format,"\\t","\t");
for(vector<string>::iterator it = items.begin(); it != items.end(); ++it) {
ostringstream stm; stm << ... |
2,500,410 | 2,501,119 | Doxygen/C++: Global namespace in namespace list | Can I show the global namespace in the namespace list of the documentation generated with Doxygen? I have some functions which are extern "C", they appear in the documentation of the header file that declares them, but not in the namespace list and it gives the impression that they are not really there...
| As far as i know, this feature is still missing from Doxygen. One work-around that is not overly verbose is to use @defgroup MyGlobals and put the extern "C" functions in that group:
/*! @ingroup MyGlobals
* @{ */
// ... functions
/*! @} */
This adds the functions in an entry called MyGlobals on the tab Modules.
Th... |
2,500,521 | 2,500,691 | Getting libstdc++-v3/python | I am trying to download libstdc++-v3/python to enable pretty printing of stl containers. However, my provider returns: svn: Unknown hostname 'gcc.gnu.org' error. This is the command:
svn co svn://gcc.gnu.org/svn/gcc/trunk/libstdc++-v3/python
Is there an alternative way to get this package?
| try http:// instead of svn://
that would be :
svn co http://gcc.gnu.org/svn/gcc/trunk/libstdc++-v3/python
|
2,500,525 | 2,501,380 | C++ app fails to initialize (0xc0000005), when using C# dll | I have a C# DLL, which I call from a native C++ programm.
As I use Qt and /clr compiler option did not work I followed this tutorial for a bridge.
So I have a VS2008 project (compiled with /clr), which links to the C# DLL and contains the bridge class and the native class, which exposes interfaces to my C++ programm. A... | The project, which called the native class was linked statically to my exe and this did not worked. I changed it to a DLL and now it seems to work.
I'll investigate a little more.
|
2,500,664 | 32,200,655 | What's the simplest way of defining lexicographic comparison for elements of a class? | If I have a class that I want to be able to sort (ie support a less-than concept), and it has several data items such that I need to do lexicographic ordering then I need something like this:
struct MyData {
string surname;
string forename;
bool operator<(const MyData& other) const {
return surname < other.... | With the advent of C++11 there's a new and concise way to achieve this using std::tie:
bool operator<(const MyData& other) const {
return std::tie(surname, forename) < std::tie(other.surname, other.forename);
}
|
2,500,670 | 2,501,004 | Why this friend function can't access a private member of the class? | I am getting the following error when I try to access bins private member of the GHistogram class from within the extractHistogram() implementation:
error: 'QVector<double> MyNamespace::GHistogram::bins' is private
error: within this context
Where the 'within this context' error points to the extractHistogram() implem... | According to my GCC the above code does not compile because the declaration of extractHistogram() appears after the class definition in which it is friended. The compiler chokes on the friend statement, saying that extractHistogram is neither a function nor a data member. All works well and bins is accessible when I ... |
2,500,677 | 2,500,724 | Making Global Struct in C++ Program | I am trying to make global structure, which will be seen from any part of the source code. I need it for my big Qt project, where some global variables needed. Here it is: 3 files (global.h, dialog.h & main.cpp). For compilation I use Visual Studio (Visual C++).
global.h
#ifndef GLOBAL_H_
#define GLOBAL_H_
typedef st... | Yes. First, Don't define num in the header file. Declare it as extern in the header and then create a file Global.cpp to store the global, or put it in main.cpp as Thomas Jones-Low's answer suggested.
Second, don't use globals.
Third, typedef is unnecessary for this purpose in C++. You can declare your struct like ... |
2,500,877 | 2,532,646 | count of distinct acyclic paths from A[a,b] to A[c,d]? | I'm writing a sokoban solver for fun and practice, it uses a simple algorithm (something like BFS with a bit of difference).
now i want to estimate its running time ( O and omega). but need to know how to calculate count of acyclic paths from a vertex to another in a network.
actually I want an expression that calculat... | Not a solution but maybe you can think this idea a bit further. The problem is that you'll need to calculate also the longest possible path to get all paths. The longest path problem is NP complete for general graphs, so it will get a very long time even for relative small graphs (8x8 and greater).
Imagine the start-ve... |
2,501,087 | 2,508,254 | Programming a VPN, Authontication stage - RFC not clear enough | I have a custom build of a Unix OS.
My task: Adding an IPSec to the OS.
I am working on Phase I, done sending the first 2 packets.
What I am trying to do now is making the Identification Payload.
I've been reading RFC 2409 (Apendix B) which discuss the keying materials (SKEYID, SKEYID_d, SKEYID_a, SKEYID_e and the IV m... | You cannot negotiate a PRF based solely on RFC2409, so don't worry about that. 3 key Triple-DES, AES-192, and AES-256 all require the key expansion algorithm in Appendix B. Many implementations have these, so testing interoperability should not be that hard.
|
2,501,171 | 2,501,202 | Storing objects in STL vector - minimal set of methods | What is "minimal framework" (necessary methods) of complex object (with explicitly malloced internal data), which I want to store in STL container, e.g. <vector>?
For my assumptions (example of complex object Doit):
#include <vector>
#include <cstring>
using namespace std;
class Doit {
private:
char *a;
... | Note that Charles has answered your question perfectly.
Anyway, as per the Rule of Three, your class, having a destructor, should have a copy constructor and an assignment operator, too.
Here's how I would do it:
class Doit {
private:
char *a;
public:
Doit() : a(new char[10]... |
2,501,272 | 2,501,483 | Is there any algorithm for turning simple Haxe code into C/C++ code files? | I have simple Haxe app like
class Main
{
public static function main()
{
trace("hello world");
}
}
I know how to compile such app for windows (not as SWF but as app from pure C\C++ )(and you can see how here but be worned thay use hxcpp\0,4 ) The problem is - I do not want to compile app for Windo... | AFAICT hxcpp does generate C++ code which uses a platform specific library(Neko). the output is not windows specific.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.