question_id int64 25 74.7M | answer_id int64 332 74.7M | title stringlengths 20 150 | question stringlengths 23 4.1k | answer stringlengths 20 4.1k |
|---|---|---|---|---|
4,513,763 | 15,687,514 | Is there a way to load an icon from a memory file handler? | I am writing wxWidgets application where I am importing the .ICO file as a header. I am attempting to use a wxMemoryFSHandler to make this icon (and others as well) accessible as files. I am using the following code to do this:
wxFileSystem::AddHandler(new wxMemoryFSHandler);
wxMemoryFSHandler::AddFileWithMimeType(
... | I have determined that there was no means of loading the icon set directly from the virtual file system. I have figured out, however, a means to do so as follows:
wxFileSystem file_system;
Csi::SharedPtr<wxFSFile> ico_file(
file_system.OpenFile(
make_wxString(config->get_control()->get_attr_wstr(L"icon"))));
... |
4,513,811 | 4,513,831 | win32: WM_PAINT calls but not supposed to be! | I have a problem with WM_PAINT. Basically I want WM_PAINT to be called after a user WM_COMMAND, but for some reason it's called anyway in the main function.
case WM_PAINT:
{
createFont();
PAINTSTRUCT ps;
HBRUSH hbruzh = CreateSolidBrush(RGB(0,0,0));
HDC hdz = BeginPaint(hWnd,&ps);
string s... | WM_PAINT is called any time your window needs to be redrawn. That's what it's for. Showing the window, resizing the window, restoring the window from minimized state, bringing the window to the front after it's been covered by another window, minimizing another app that was covering up your window... these are just a f... |
4,514,008 | 4,514,093 | Anonymous namespaces: Are they really that great? | I have been using the static keyword a long time for defining internal linkage. Later, I switched to the C++ style of wrapping local things in anonymous namespaces.
However, now when I have worked with anonymous namespaces for some years, I start to think that static keyword is a lot easier to work with!
A common probl... | If the code in your namespace is too long, there's nothing to stop you doing this:
namespace {
int foo(char* x) {
return x[0] + x[1];
}
}
namespace {
int bar(char *x, char *y) {
return foo(x) + foo(y);
}
}
In C++03 the practical advantage of using an unnamed namespace is precisely that... |
4,514,124 | 4,514,204 | How could one implement std::auto_ptr's copy constructor? | Back on my crazy AutoArray thingy... (quoting important bits from there:
class AutoArray
{
void * buffer;
public:
//Creates a new empty AutoArray
AutoArray();
//std::auto_ptr copy semantics
AutoArray(AutoArray&); //Note it can't be const because the "other" reference
//is ... | auto_ptr uses a dirty trick.
I'll use a dumbed-down class named auto_int to demonstrate just the copy construction functionality without bringing in any complexities introduced by templates or inheritance. I think the code is mostly correct, but it's untested. Our basic auto_int look something like this:
class auto_i... |
4,514,191 | 4,514,219 | C++: Inheriting two base classes with same name, different namespace | Is it possible to inherit two base classes that have the same name, if the are in different namespaces?
By the way, I'm not planning at this time on doing this, but I was curious:
class SuperShape : Physics::Shape, Graphics::Shape
{
// constructor
SuperShape( int x, int y, float color) : ???( x, y ), ???( color... | Sure, why not? Nothing prevents you from doing so. Here is a working example:
#include <iostream>
#include <typeinfo>
#include <string>
namespace NS1 {
class MyClass {
public:
MyClass (const std::string &) {}
};
}
namespace NS2 {
class MyClass {
public:
MyClass (int) {}
};
}
class MyClass :
public NS... |
4,514,382 | 4,514,793 | Microsoft security essentials blocking manifest file | When compiling programs with Visual Studio 2010 C++ Express edition I get the error c101008a.
Including manifest-files in the ignore list in Microsoft security essentials solves this, but only once, when I compile again, I have to do it again.
Anyone have a solution for this except switching anti-virus software?
| I found several suggestions on the web, such as doing a Clean first.
|
4,514,529 | 4,514,535 | Check array for change in data | I need some help with C++. I have a thread running in the background that keeps continuously checking for data and upon some conditions met it will process that data. data is stored in an char array[]. I want to use this array in some other script. ( I can access this array from other script).
I want to do some thing l... | You need condition variables. They're in virtually every threading API. You can block on them until the condition becomes true. You need to refer to whatever implements your threading for more details.
|
4,514,553 | 4,514,579 | C++: Overlapping base class methods | When inheriting two base classes, what happens if both have a method with the same name and signature?
class Physics
{
public:
void Update() { std::cout << "Physics!" }
};
class Graphics
{
public:
void Update() { std::cout << "Graphics!" }
};
class Shape : Physics, Graphics
{
};
int main()
{
Shape shape;... | Well, first of all your code does not compile regardless of the call to Update :
The Update member functions lack returns types
Shape inherits privately from Physics and Graphics, so Update is inaccessible from main
Now, that being said, what happens when you attempt to call Update is an ambiguity which will lead to... |
4,514,679 | 5,098,212 | How can I marshall between XLOPER and VARIANT? | I'm working on an Excel plugin (XLL), which communicates with COM objects. So, I have to marshall between XLOPER and VARIANT. I've got most of this working, but arrays are definitely a pain. I need to support 1- and 2D arrays.
I imagine someone has already had to deal with this before. What's the best way to simpli... | I had to hand-roll my own marshalling code for this. There were no freely available libs to handle this. XLW is meant for wrapping your entire plugin - this was not an option for me.
In the end, it just took a lot of time, looking through the documentation for xloper and variant, and figuring out how to map them to e... |
4,514,722 | 4,514,999 | Window refuses to render | I recently got started trying to use SFML. For some reason my simple program will not render the window. I've tried throwing everything into main to see if there was an error in my code that had to do with multiple files etc. but to no avail.
I'll launch my program and nothing will appear.
What's the problem?
//main.h
... | I tried your code and it behaves exactly as I expect it to - that is to say that an iconless window with a black body pops up and it doesn't respond to events. Is that what you're getting? If not, you might need to rebuild SFML.
You might want to try introducing event-handling so that your startLoop looks more like thi... |
4,514,730 | 4,515,201 | What's a good, threadsafe, way to pass error strings back from a C shared library | I'm writing a C shared library for internal use (I'll be dlopen()'ing it to a c++ application, if that matters). The shared library loads (amongst other things) some java code through a JNI module, which means all manners of nightmare error modes can come out of the JVM that I need to handle intelligently in the applic... | My approach to the problem would be a little different from everyone else's. They're not wrong, it's just that I've had to wrestle with a different aspect of this problem.
A C API needs to provide numeric error codes, so that the code using the API can take sensible measures to recover from errors when appropriate, a... |
4,514,772 | 10,792,987 | Why would someone override paintEvent() just to drawPrimitive? | What's the point of this paintEvent override:
void QWidgetDerivedWhatchamit::paintEvent(QPaintEvent *)
{
QStyleOption opt;
opt.init(this);
QPainter p(this);
style()->drawPrimitive(QStyle::PE_Widget, &opt, &p, this);
}
Surely that's what QWidget already does?
| You shouldn't ever need to do that if you derive from QWidget. Forget you ever saw that code :)
|
4,514,842 | 4,514,854 | In Visual Studio how do I force a build if a component is outdated? | Recently I put my two C++ projects under one solution in VS 2010.
One project creates a DLL and the second is a test app that makes use of the DLL.
Before this transition, I used to build the DLL and copy the output .dll file into the Debug directory of the test app, then I would build that too (The app loads the DLL a... |
I wonder if there is a way to force a build of the DLL project when I build the test app , if the existing .dll file is outdated.
Yes.
In solution explorer, right click on the exe project and select Project Dependencies....
Select the DLL project checkbox and you're all set.
If your DLL project was a static library... |
4,514,849 | 4,514,882 | C3867 Transferring vector values | I need to access two values in a vector called camerapos which contains the values x,y,z but when I does it like tis I get c3867.
int Camera::getCamerapos(){
int x = camerapos.x; //c3867
int y = camerapos.y; //c3867
return x,y;
}
| From the error code (assuming MSVC) it looks like x and y are functions/methods. So, perhaps you should replace the code with
int x = camerapos.x();
int y = camerapos.y();
By the way, your return type is (one) int, so you cannot return both x and y at the same time. Maybe you want to return std::pair<int> or some kind... |
4,514,958 | 4,515,041 | C++ bitfield testing | Is there a more compact way of comparing my bits than this (the only way I know):
#define BIT1 1
#define BIT2 2
#define BIT3 4
#define BIT4 8
#define BIT5 16
#define BIT6 32
// I declare this somewhere in a structure
unsigned char bits: 6;
// I want all of them to be 0 at first (000000)
bits = 0;
/* I do some bite s... | If you want compact (as indicated in your comment) rather than fast, why not do something like:
#define BIT1 0x01
#define BIT2 0x02
#define BIT3 0x04
#define BIT4 0x08
#define BIT5 0x10
#define BIT6 0x20
#define BITS1THRU4 (BIT1|BIT2|BIT3|BIT4)
// or #define BITS1THRU6 0x0f
// I declare this somewhere in a structure
u... |
4,514,970 | 4,515,015 | C++: Namespace syntax question | namespace Stuff
{
class Sprite
{
};
class Circle : Stuff::Sprite
{
};
}
Will this work, or will this look for Stuff::Stuff::Sprite?
edit: forgot some semicolons.
edit 2: I'm accepting @Omnifarious' answer because once he edited it with @Vlad's help, it was the most complete answer. thanks also... | It will work if you put in the ; after the class definitions. But it will not work in quite the way you expect. First, it tries to figure out what namespace you're talking about. First it will looks for ::Stuff::Stuff, and when it doesn't find it, it then looks for the namespace ::Stuff. It finds that namespace, so... |
4,515,010 | 4,515,060 | Class templating std::set key types | I have a class to evaluate set algebra but wish to template it.
At the minute it looks a bit like this
set.h:
template<typename T>
class SetEvaluation
{
public:
SetEvaluation<T>();
std::set<T>
evaluate(std::string in_expression);
}
set.cpp
template<typename T>
std::set<T>
SetEvaluation<T>::... | Template classes and functions are a bit special and need to be defined in the header file. Then that header file needs to be #included wherever you want to use that template class. If you try to define the template functions in a cpp file the linker and try to call that function from another cpp file, the linker won't... |
4,515,242 | 4,515,553 | Multiple viewport problem | I'm setting up so I can switch between either one or four viewports but I got some trouble.
In my bottom right viewport I got camera view, the same camera that I can switch to full view on. The other three viewports are working with fixed locations but the bottom right viewport is compressed on the y scale and half of ... | glViewport() takes an offset and a size.
Your code seems to be passing lower-left and upper-right coordinates.
Try these:
glViewport( 0, 0, w/2, h/2); // lower-left
glViewport(w/2, 0, w/2, h/2); // lower-right
glViewport(w/2, h/2, w/2, h/2); // upper-right
glViewport( 0, h/2, w/2, h/2); // upper-left
|
4,515,306 | 4,515,328 | C++ reference syntax | Which is the correct way to specify a reference. I know both works with the compiler, but wanted to know the correct way since I have seen both in code bases.
void Subroutine(int &Parameter)
{
Parameter=100;
}
OR
void Subroutine(int& Parameter)
{
Parameter=100;
}
| There is no 'correct' way, in the same way like there is no 'correct' way to place your parentheses and brackets. It's a matter of style and preference.
It's more important to be consistent.
|
4,515,310 | 4,515,440 | How to use a variable inside a _T wrapper? | I want to make the hostname part of this string to be variable..
Currently, it is only fix to this URL:
_T(" --url=http://www.myurl.com/ --out=c:\\current.png");
I want to make something like this, so the URL is changeable..
_T(" --url=http://www." + myurl + "/ --out=c:\\current.png");
update. Below is my latest att... | It doesn't work because the _T() macro works only with constant string literals. The definition for _T() looks something like this:
#ifdef UNICODE
#define _T(str) L##str
#else
#define _T(str) str
Since you're apparently compiling in Unicode mode, _T(full) expands to Lfull, which is obviously not what you want.
In your... |
4,515,754 | 4,515,779 | How to perform a non-blocking write to device? | is it possible to make write(); function non-blocking without using threads?
short buffer[BUFFER_LEN];
int readcount;
while ((readcount = sounds[index].read(buffer, BUFFER_LEN)))
write(audio_device, buffer, readcount * sizeof(short));
The sounds play, but it blocks program until it finished playing.
| Using the fcntl to set the O_NONBLOCK flag for the file will probably work, but you need to be prepared to deal with partial writes and EWOULDBLOCK errors.
|
4,515,811 | 4,515,994 | Cross platform window library - Integrating OpenGL and DirectX | I'm about to start working on a custom cross platform engine (c++) that will need to be able to support the latest versions of both OpenGL and DirectX. The renderer is chosen before compilation.
I'm looking at cross platform libraries to handle window creation and input that can also handle the latest implementations o... | The OpenGL and DirectX are somewhat similar yet very different. OpenGL is built with idea to forward developers desire to render to devices if available. DirectX is built with idea to make rendering capabilities of devices available for developer.
Thanks to differences you end up implementing almost everything twice. ... |
4,515,827 | 4,515,833 | is ->Release() called on the destructor of COM objects? | If I have the following:
ID3D11Buffer **buffers; //ID3D11Buffer is a com object
buffers=new ID3D11Buffer* [num];
Then if I do this:delete[] buffers;Will the Release() method of each ID3D11Buffer* be called automatically, or do I have to call them myself?
| All delete[] buffers; will do is free the array containing the pointers to the COM objects. You do need to loop through the array and Release() each of them by hand.
|
4,515,874 | 4,515,899 | Searching for a fast/efficient histogram algorithm (with pre-specified bins) | I don't do much coding outside of Matlab, but I have a need to export my Matlab code to another language, most likely C. My Matlab code includes a histogram function, histc(), that places my input data (which is double-precision, not integer) into a specified array of bins, to form a histogram.
I'm sure I can piece to... | GSL (GNU Scientific Library) contains a histogram implementation.
Here is the documentation: http://www.gnu.org/software/gsl/manual/html_node/Histograms.html.
And here is an example use: http://www.gnu.org/software/gsl/manual/html_node/Example-programs-for-histograms.html.
|
4,516,144 | 4,516,183 | C++ Char array conversion to Hex or char array | I would appreciate for some C++ expertize advice on this please. I have a Char array
<unsigned char ch1[100];>
data (ASCII code) gets filled in this ( max 6 or 8 array spaces and rest is empty). I want to process valid bits in the array only either converting them to Hex or again Char array. I tried
<me... | Do you know how many valid bytes do you have in your array? If yes, you can pass that number in as the 3rd argument of memcpy.
Otherwise you can zero-initialize the array and use strcpy which will stop on the first zero:
char ch1[100];
// zero out the array so we'll know where to stop copying
memset(ch1, 0, sizeof(ch1)... |
4,516,272 | 4,516,292 | Is it not possible to make a C++ application "Crash Proof"? | Let's say we have an SDK in C++ that accepts some binary data (like a picture) and does something. Is it not possible to make this SDK "crash-proof"? By crash I primarily mean forceful termination by the OS upon memory access violation, due to invalid input passed by the user (like an abnormally short junk data).
I ... | You can check the bounds of an array in C++, std::vector::at does this automatically.
This doesn't make your app crash proof, you are still allowed to deliberately shoot yourself in the foot but nothing in C++ forces you to pull the trigger.
|
4,516,495 | 4,516,513 | How can I iterate over an STL map inside an STL map? | I have an STL map definition as follows:
map<string, map<int, string> > info;
I iterate that map using the following code:
for( map<string, map<int, string> >::iterator ii=info.begin(); ii!=info.end(); ++ii){
for(map<int, string>::iterator j=ii->second.begin(); j!=ii->second.end();++j){
cout << (*ii).first... | This is correct, it just lacks a few typedef and readability improvements :
typedef std::map<int, std::string> inner_map;
typedef std::map<std::string, inner_map> outer_map;
for (outer_map::iterator i = outerMap.begin(), iend = outerMap.end(); i != iend; ++i)
{
inner_map &innerMap = i->second;
for (inner_map::... |
4,516,577 | 4,516,595 | What type of input check can be performed against binary data in C++? | let's say I have a function like this in C++, which I wish to publish to third parties. I want to make it so that the user will know what happened, should he/she feeds invalid data in and the library crashes.
Let's say that, if it helps, I can change the interface as well.
int doStuff(unsigned char *in_someData, int ... | It cannot be checked whether the parameter in_data_length passed to the function has the correct value. If this were possible, the parameter would be redundant and thus needless.
But a vector from the standard template library solves this:
int doStuff(const std::vector<unsigned char>& in_someData);
So, there is no pos... |
4,516,669 | 4,517,518 | What libraries do I need to use std::placeholders? | Currently I am trying to generate combinations and I am using the following code:
#include <vector>
#include <algorithm>
#include <iostream>
#include <functional>
template<class RandIt, class Compare>
bool next_combination(RandIt first, RandIt mid, RandIt last)
{
std::sort(mid, last, std::bind(std::less<int>(), st... | why don't you use lambdas instead of cumbersome bind? if you use C++0x, it has sense to write
std::sort(v.begin(), v.end(), [](int l, int r)->bool { return l > r; });
instead. Note, that you don't need to specify the return type explicitly there. I wrote this way just to make it clearer.
|
4,517,214 | 4,521,668 | Windows Messaging - trapping calls originating from another API | Scenario:
We're busy wrapping up a 3rd party's C++ SDK as a DLL to make it simpler for other developers in our organisation to integrate this functionality into their own apps (be it, .net, delphi, etc)
The underlying system sends Windows messages to signal events that occur in the system. These events need to be deal... | The easiest way is to make a proxy DLL. The basic idea is to replace the API DLL with your own, replace the functions you want to and forward the rest to the original API DLL. You rename the original DLL and put in your with the original name of the API DLL. To do this you need to export the functions. Microsoft ha... |
4,517,425 | 4,518,083 | How to get program path |
Possible Duplicate:
how to find the location of the executable in C
I'm writting an multi-platform app in C++ using GTK+ and I have a problem. I must get program path. E.g., when program is in /home/user/program (or C:\Users\user\program.exe), i have /home/user/ (or C:\Users\user\).
Can and how I can do this?
| argv[0] contains the program name with path. Am I missing something here?
|
4,517,439 | 4,517,489 | Putting all methods in class definition | When I use the pimpl idiom, is it a good idea to put all the methods definitions inside the class definition? For example:
// in A.h
class A {
class impl;
boost::scoped_ptr<impl> pimpl;
public:
A();
int foo();
}
// in A.cpp
class A::impl {
// method defined in class
int foo() {
return 42;
... | I think you answered your own question : both solutions are equivalent.
However, I wouldn't be so sure that 'inlining has no effect since the methods are called in only one place' : an additional call could exists when the functions are not inlined. But chances are that the compiler is smart enough to optimize them awa... |
4,517,527 | 4,517,549 | What is the problem with this function | hi
I was writing a BST and wrote following function for adding Child.
void addChild(T value)
{
temp = root;
while(0 != temp)
{
temp1 = temp;
if(value > temp->getValue())
temp = temp->getRightChild();
else
temp = temp->getLeftChild();
}
if(temp1->g... | Try:
if(value > temp1->getValue())
...otherwise your insertion condition differs from your search for a spot in the loop above.
|
4,517,550 | 4,518,084 | embedded Lua and overloaded C++ operators | I am embedding Lua in my C++ application.
I have a class Foo which I am exposing to Lua (via tolua++).
Foo overloads some operators as shown below:
class Foo
{
public:
explicit Foo(const int i);
bool operator==(const Foo& foo) const;
bool operator< (const Foo& foo) const;
int operator-(const ... | According to the documentation tolua++ supports this - see Binding classes and methods - Overloaded operators:
tolua automatically binds the following binary operators:
operator+ operator- operator* operator/
operator< operator>= operator== operator[]
For the relational operators, toLua also automatically ... |
4,517,832 | 4,545,022 | Tracking flash application packets | I have this flash application that opens a socket connection with a server. What I need to do is to read packets sent and received byt he application to write a sort of "history" ( in WIndows).
Now, questions are:
How is the simplest way to do it? Application hooking? Load the flash application in my application and t... | The simplest way to do it (by far) is to use a socket proxy. The flash application connects to the proxy, the proxy connects to the server and relays streams both ways while logging.
As far as I know, the flash application can only connects to the server where it was donwloaded, so it means you may have to host the fla... |
4,517,971 | 4,518,348 | tolua++ ignores assignment and inequality operator? | I am embedding Lua in a C++ class.
It seems that tolua++ is ignoring some overloaded operators of my class.
tolua++ issues the following warnings:
**tolua++ warning: No support for operator=, ignoring
**tolua++ warning: No support for operator!=, ignoring
Is there any way around this?
| I'm not familiar with tolua++, but it makes sense that it wouldn't support either of those. tolua++ is just politely informing you so you don't think that code is having any effect.
The assignment operator makes no sense in the context of Lua, and the ~= operator is the negation of ==, so implementing operator== takes ... |
4,518,050 | 4,518,204 | Prevent windows from presenting any dialog on native code unhandled exception | Our buildserver compiles and runs testsuites for many different c++ programs. From time to time the programs are buggy, and can crash.
When they crash, Windows7 will always throw this modal dialog:
Which has to be clicked away by a human being, causing the buildserver to sit idle.
Is there a way to at a system level p... | Calling WerAddExcludedApplication should do the trick.
http://msdn.microsoft.com/en-us/library/bb513617.aspx
Or read more about Windows error reporting in MSDN:
http://msdn.microsoft.com/en-us/library/bb513636.aspx
|
4,518,163 | 4,518,356 | How does qobject_cast work? | I just found the following code in Qt and I'm a bit confused what's happening here.
Especially as to what reinterpret_cast<T>(0) does?
template <class T>
inline T qobject_cast(const QObject *object)
{
// this will cause a compilation error if T is not const
register T ptr = static_cast<T>(object);
Q_UNUSED(... | This is a little complicated...
Remember that qobject_cast<T>(obj) is a way to dynamically cast a QObject to the target type T which also derives from QObject. Now, for this to work, the macro Q_OBJECT should be included in the definition of class T.
Apparently, the qt_check_for_QOBJECT_macro call is for checking that ... |
4,518,588 | 8,585,517 | login screen replacement for windows 7 |
Possible Duplicate:
How can I customize the login screen for Windows Vista & 7?
I am developing a customize windows login screen which will be replaced by default login screen of Windows 7. I need few information for this purpose.
Is C# right language for this or C++
If C# is good choice then how about WPF for goo... | According to MSDN Magazine, you can not use managed code nor can you draw your own UI.
Regarding drawing the UI:
There has also been an important change regarding which component renders the graphical aspect of the logon. Previously, this was handled by GINA and thus a third-party component could have been doing the r... |
4,518,598 | 4,518,625 | Is it legal to recurse into main() in C++? | I read that the C++ standard forbids recursion in main(), but g++ compiles the following code without complaint:
int main()
{
main();
}
Can anyone clarify this?
| According to the standard in 3.6.1/3, it's not :
The function main shall not be used
(3.2) within a program
The definition of used being :
An object or non-overloaded
function is used if its name appears in a potentially-evaluated expression.
|
4,518,630 | 4,518,788 | const_casting question | I have the following code:
int main(){
const int a = 1;
const int* b(&a);
int* c = const_cast<int*>(b);
*c = 29;
cout<<*c<<a<<*b;
return EXIT_SUCCESS;
}
Why doesnt the value of 'a' change to 29? Does this mean that the constness of a is not removed when const_casting b?
| Constant variables also allows the compiler certain optimizations, one of these is that the compiler can keep the value in the registers and not reload it. This improves performance but will not work with variables that changes since these need to be reread. Some compilers even optimize constants by not allocating a va... |
4,518,675 | 4,519,115 | Wait for a SLOT to finish | I use QNetworkAccessManager to do form POST.
I have connected signals and slots as:
connect(manager,SIGNAL(finished(QNetworkReply*)),this,SLOT(readCookies(QNetworkReply*)));
Now, I make a request by doing:
manager->post(request,postData);
Now readCookies(QNetworkReply *) will be run as soon as SIGNAL is emitted. Now... | You can do the post in your readCookies() slot:
void readCookies( QNetworkReply* reply ) {
if ( ...error? ) {
report error...
return;
}
...
manager->post(request2,postData2);
}
I will be called when the cookies is read, and you can then continue with your post. Connect that to a second... |
4,518,787 | 4,518,867 | Typo at msdn page "C++ Constant Expressions"? | It says at msdn page for c++ constant expressions that:
Nonintegral constants must be
converted (either explicitly or
implicitly) to integral types to be
legal in a constant expression.
Therefore, the following code is
legal:
const double Size = 11.0;
char chArray[(int)Size];
At least on VC++ 10.0 the sec... | According to 5.19/1 :
An integral constant-expression can
involve only literals (2.13),
enumerators, const variables or
static data members of integral or
enumeration types initialized with
constant expressions (8.5), non-type
template parameters of integral or
enumeration types, and sizeof
expressions... |
4,518,835 | 4,518,910 | how many types of strings in visual c++ | How many types of string classes are there in visual c++. I got confused when i was going through the msdn center.
I found this type under the namespace system
http://msdn.microsoft.com/en-us/library/system.string(v=VS.71).aspx
and then in the headers section, i found the string header definitions. This seemed differen... | Different libraries come with different string types:
In plain old C you would use char*, the C++ standard library provides std::string which is widely used in C++ development. (string is defined as typedef basic_string<char> string;)
Microsoft created the MFC CString class which is (was?) used in MFC style programming... |
4,518,951 | 4,519,138 | Engineered bool compares equal to both true and false, why? | The example bellows compiles, but the output is rather strange :
#include <iostream>
#include <cstring>
struct A
{
int a;
char b;
bool c;
};
int main()
{
A v;
std::memset( &v, 0xff, sizeof(v) );
std::cout << std::boolalpha << ( true == v.c ) << std::endl;
std::cout << std::boolalpha << ( ... | Found this in the C++ standard, section 3.9.1 "Fundamental types" (note the magic footnote 42):
6. Values of type bool are either true or false. 42)
42) Using a bool value in ways described by this International Standard as ‘‘undefined,’’ such as by examining the value of an uninitialized automatic variable, might ca... |
4,519,148 | 4,519,215 | Inlining this function or not? | I'm supposed to implement a function which compares two strings simliar so strcmp but ignoring whitespace characters, so
strcmpignorews("abc ", " a b c")
should give the same result.
Here's my implementation:
namespace {
void SkipWhitespace(const char *&s) {
for (; std::isspace(*s, std::locale::classic);... | Historically, Inline has been an indication to the compiler that it should insert the function body into the call site. However, that is no longer a meaningful annotation. Modern compilers will inline a function or not regardless of the presence or absence of inline qualification.
To emphasize, whether compiler wil... |
4,519,372 | 4,524,706 | Recommendations for a free GIS library supporting raster images | I'm quite new to the whole field of GIS, and I'm about to make a small program that essentially overlays GPS tracks on a map together with some other annotations. I primarily need to allow scanned (thus raster) maps (although it would be nice to support proper map formats and something like OpenStreetmap in the long ru... | See GDAL www.gdal.org for a solid background library for raster formats and manipulation, and it incorporates PROJ.4 for transformations.
QGIS relies on GDAL for some data import, amongst other things.
|
4,519,476 | 4,522,065 | Free cross-platform library to convert numbers (money amounts) to words? | I'm looking for cross-platform library which I can use in my C application to convert money amounts (e.g. $123.50) to words (one hundred twenty three dollars and fifty cents). I need support for multiple currencies: dollars, euros, UK pounds etc.
Although I understand this is not hard at all to write my own implementat... | Are you looking for something like this? It's not a complete solution as it externalizes the handling of the currency. Furthermore, it fails for negative numbers.
Just allocate a character buffer and call write_number. The third and fourth argument are expected to be the currency units (in their plural form), e.g. "dol... |
4,519,596 | 4,519,658 | How to get a templated typename as a string? | The following code prints out the string "T" not the actual typename when the templated function is called. Is there a way to get the real typename without adding anything to the types being templated?
#define stringify(a) #a
#define tostring(a) stringify(a)
template <typename T>
void function_foo(T a, T b)
{
cout... | Templates don't work like that. In your template T specifies a type, and not a sequence of tokens:
typedef int lolztype;
typedef int lulztype;
function_foo<lolztype>(0, 0);
function_foo<lulztype>(0, 0); // calls the *same* template
There is no way to get lolztype or lulztype respectively. What you could try is using ... |
4,519,783 | 4,519,833 | win32: TextOut not being displayed | I recently having my mainwindow write text by using WM_PAINT, but now I realise it was maybe not the best message to do so in, so I'm trying another version;
The mainwindow contains a menu, upon clicing a menu item the ID_FILE_PID msg is sent and it builds the 4 new windows aswell as displays text in the mainwindow (pa... | You can only use BeginPaint/EndPaint in response to WM_PAINT. And WM_PAINT is the appropriate place to do drawing like this.
Windows calls WM_PAINT when a part of the window is "invalidated". For example if you restore the window, or part of the window becomes visible after moving a window out of the way, or resizing t... |
4,519,834 | 4,519,851 | Using malloc() and sizeof() to create a struct on the heap | I'm trying to use malloc() and sizeof() to create a struct on the heap. Here is my code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct Employee
{
char first[21];
char last[21];
char title[21];
int salary;
};
struct Employee* createEmployee(char* first, char* last, char* title, int... | In C++ (since you are using Visual C++ to compile), you have to explicitly cast the pointer returned by malloc:
struct Employee* p = (struct Employee*) malloc(sizeof(struct Employee));
|
4,519,849 | 4,520,048 | Code only runs properly if debugging step-by-step |
I'm making a webserver and I've come up with some very strange problems.
My server was running as expected
yesterday when I turned off my laptop, but today it only sends the http
headers (I didn't change anything)
When a user requests a file, if I send them using the following code, it works perfectly:
while ((n = ... | Assuming that data is char[] of some size, and that string is std::string your code doesn't do what you think it does. When you pass data to WEB::Send it's creating a std::string from all the bytes in data up to the first 0, which probably is about 2% of the total data. You want to call web.Send(std::string(data, n)); ... |
4,519,985 | 4,520,012 | How can I increase performance on this MFC code? | I conduct a file search and there is exception list for directories, the problem is below code recursively iterates through all files on hard drives. It works but it is slow. Therefore, I need help to optimize its performance. Thanks in advance.
CFileFind finder;
// build a string with wildcards
CString strWil... | I don't think you're going to be able to optimize performance here. You're going to be spending 80+% of your time inside FindFirstFile and FindNextFile here (windows API calls) no matter what you do in terms of optimization on your end.
I asked a similar question already and have yet to get an answer.
|
4,519,991 | 4,520,107 | mem_func and virtual function | I have the following classes:
class A
{
public:
virtual void myfunc(unsigned char c, std::string* dest) = 0;
};
class B : public class A
{
public:
virtual void myfunc(unsigned char c, std::string* dest);
};
void someOtherFunc(const std::string& str,A *pointerFunc)
{
std::string tmp;
... | You're looking for std::mem_fun(&A::myfunc).
EDIT: You can't use mem_fun at all here -- no overload of mem_fun allows you to make a two argument member function into a functor. You're going to have to use something like boost::bind/std::tr1::bind (If you have TR1)/std::bind (If you have C++0x) or you're going to have t... |
4,520,236 | 4,520,366 | Using find_if on map to find by value | I have a class which has a map. I need to find iterator in map by searching for a particualar value, instad of the key. Using a member function predicate IsValueFound, am trying this.
class A
{
public:
void findVal();
private:
int state;
map<int, int> exmap;
bool IsValueFound(pair<int key, int val> itr)
{
retu... | Edit: there's obviously an error in my answer, mem_fun1_ref(&A::IsValueFound) doesn't work as a predicate for std::find_if. I'm working on correcting that.
you forgot parenthesis with exmap.begin and exmap.end.
I think if you had read the compilation error report, it would have told seomthing about it.
I would write th... |
4,520,377 | 4,521,276 | Converting Window coordinates to Axis coordinates in OpenGL | Im creating a simple program in OpenGL to draw rectangles with the mouse. My goal is to click somewhere, drag the mouse and create a rectangle just like you do in paint or any other design program.
I have a view defined like:
glMatrixMode(GL_PROJECTION);
glOrtho(AXIS_X_MIN, AXIS_X_MAX, AXIS_Y_MIN, AXIS_Y_MAX, AXIS_Z_MI... | Try:
double x = x_mouse / (double) WINDOW_WIDTH
* (AXIS_X_MAX - AXIS_X_MIN) + AXIS_X_MIN;
double y = (1 - y_mouse / (double) WINDOW_HEIGHT)
* (AXIS_Y_MAX - AXIS_Y_MIN) + AXIS_Y_MIN;
|
4,520,553 | 4,521,004 | Set specific style to a certain QMessageBox | How to set a specific style to a certain QMessageBox in Qt. Particularly, I would like to invoke a message box which is written below by setting a font size and color for the text "Well done!!!".
QMessageBox::information(this, "Done", "Well done!!!");
| I have formated the text of the QMessageBox with HTML code. Sorry for the question. And thanks for answers.
|
4,520,624 | 4,520,991 | Advantages and disadvantages of Open Watcom | Since in some post on StackOverflow it was recommended to try to support multiple (in this case C/C++) compilers if feasible, since this forces you to code more standard compliant and helps finding bugs.
So I was looking for additional free C/C++ compilers I could add support for to my project (it is written C/C++ (bot... | There are probably no particular advantages since if portable code is your aim you would generally try to restrict your code to the standard subset implemented by all compilers. I would say lowest common denominator but that may seem somewhat derogatory.
The advantages of one compiler over another generally lie in eit... |
4,520,706 | 4,520,810 | A confusion about the porter stemming algorithm | I am trying to implement porter stemming algorithm, but I stumbled at this point
where the square brackets denote
arbitrary presence of their contents.
Using (VC){m} to denote VC repeated m
times, this may again be written as
[C](VC){m}[V].
m will be called the \measure\ of any
word or word part when represen... | Looks like the measure is the number of times a vowel is immediately followed by a consonant. For example,
"TROUBLES" has:
Optional initial consonants [C] = "TR".
First vowels-consonants group (VC) = "OUBL".
Second vowels-consonants group (VC) = "ES".
Optional ending vowels [V] is empty.
So the measure is two, the num... |
4,520,752 | 4,521,067 | How can I load a SQLITE database from a buffer with the C API? | I am trying to load a database from the memory instead of opening a .sqlite file. I have read the C/C++ API reference but I can not find the proper method.
The buffer I am trying to load is simply an sqlite file loaded in memory. I just want to use this buffer (a const char* array) without using the filesystem (I could... | I believe that the proper way to do this is to create an SQLite VFS layer around your buffer, as mentioned in this thread. A possible/partial solution, spmemvfs, is mentioned here, although I have never tried it.
If you don't need concurrency for your DB, creating your own VFS implementation should be quite simple.
|
4,520,770 | 5,969,253 | what is IWebBrowser::Navigate2 equivalent for window.open(...)? | i need equivalent for
window.open('url to open','window name','toolbar=no');
in c#, or C++ - no metter
Thanks for any help
| Simply use IHTMLWindow2::open.
BOOL OpenWindow(IWebBrowser2* pWebBrowser, CString strUrl, CString strName, CString strFeatures)
{
if(pWebBrowser != NULL)
{
CComDispatchDriver pDocDisp;
if(SUCCEEDED(pWebBrowser->get_Document(&pDocDisp)))
{
CComQIPtr<IHTMLDocument2> pDoc = p... |
4,520,788 | 4,521,106 | Recognizing unknown mouse buttons | So I've been writing a simple Windows program, and it really irks me how in some other programs, they can't recognize the full range of input. For example, in Starcraft 2, you can't bind the extra two mouse buttons on a five-button mouse. For keyboard input, I've been using the WPARAM of the WM_KEYDOWN message, so that... | I don't think there is a generic "WM_BUTTONDOWN" message available.
The best way to check that out is to use Spy++ on a window. You'll see that there is no generic message sent out. Plus the actual values of all the WM_xxBUTTONDOWN do not follow any pattern either.
What I would do is configure the app to be able to und... |
4,520,797 | 4,520,820 | QT - uncheck check box | Guys please let me know how to uncheck the check box using QT C++.
| use
QCheckBox::setChecked(false);
|
4,520,821 | 4,520,872 | Reading raw byte array into std::string | I've been wondering about the following issue: assume I have a C style function that reads raw data into a buffer
int recv_n(int handle, void* buf, size_t len);
Can I read the data directly into an std:string or stringstream without allocating any temporal buffers? For example,
std::string s(100, '\0');
recv_n(handle,... | Why not use a vector<char> instead of a string? That way you can do:
vector<char> v(100, '\0');
recv_n(handle, &v[0], 100);
This seems more idiomatic to me, especially since you aren't using it as a string (you say it's raw data).
|
4,520,825 | 4,749,531 | WxTextCtrl unable to load large texts | I've read about the solutuon written here on a post a year ago
wx.TextCtrl.LoadFile()
Now I have a windows application that will generate color frequency statistics that are saved in 3D arrays. Here is a part of my code as you will see on the code below the printing of the statistics is dependent on a slider which spec... | Disclaimer: My answer is more of an alternative than a solution.
I don't believe that there's any situation in which a user of this application is going to find it useful to have a scrolled text window containing ~16 million lines of numbers. It would be impossible to scroll to one specific location in the list that th... |
4,520,835 | 4,520,883 | Converting a VK_CODE into a displayable string | When writing a Windows application, the documentation says that some VK_CODEs are displayable characters, like VK_OEM1 is "o with an umlaut". How can I go from the WPARAM of non-ASCII characters into a displayable string? I'm using UTF-16.
| Maybe you're looking for the GetKeyNameText Function
It retrieves a string that represents the name of a key.
|
4,520,900 | 4,520,950 | What does the `const` keyword do when it is after a function? |
Possible Duplicate:
What is the meaning of a const at end of a member function?
I have seen some classes that have something like this.
void something() const;
What does const means?
| In addition to what SRM said (that the function cannot alter any members of the class (which is not exactly true, e.g. in the case of mutable members, which still can be altered)), it means that you can call this member function on things that are const. So if you get a Foo const& foo as a parameter, you can only call ... |
4,521,015 | 4,521,023 | How to pass arguments and redirect stdin from a file to program run in gdb? | I usually run a program as :
./a.out arg1 arg2 <file
I would like to debug it using gdb.
I am aware of the set args functionality, but that only works from the gdb prompt.
| Pass the arguments to the run command from within gdb.
$ gdb ./a.out
(gdb) r < t
Starting program: /dir/a.out < t
|
4,521,142 | 4,521,170 | Macro with some sort of condition | I'm trying to create an macro so safe me from some typing and make it nicer/easier to define an property, this is what I have in mind:
#define DefineProperty(Access, Type, Name) \
property<Access, Type> ##Name; \
void Set##Name(Type); \
Type Get##Name(void); \
Where Access is an enum with three possible values: ReadOn... | Yes, you can accomplish this fairly easily:
#define DefineGetReadOnly(Name, Type) Type Get##Name();
#define DefineGetReadWrite(Name, Type) Type Get##Name();
#define DefineGetWriteOnly(Name, Type)
#define DefineProperty(Access, Type, Name) \
DefineGet##Access(Name, Type)
The macro replacement takes place as follo... |
4,521,252 | 4,956,793 | Qt, MSVC, and /Zc:wchar_t- == I want to blow up the world | So Qt is compiled with /Zc:wchar_t- on windows. What this means is that instead of wchar_t being a typedef for some internal type (__wchar_t I think) it becomes a typedef for unsigned short. The really cool thing about this is that the default for MSVC is the opposite, which of course means that the libraries you're ... | Stumbled over the same issue ...
Obviously bjam expects cxxflags=-Zcwchar_t-
After building the static serialization libs via
bjam --with-serialization toolset=msvc-8.0 variant=debug threading=multi link=static cxxflags=-Zc:wchar_t-
everything linked like expected.
Hope this helps anyone.
|
4,521,456 | 4,521,548 | C++: check whether a word is spelled correctly | I'm looking for an easy way to check whether a certain string is a correctly-spelled English word. For example, 'looked' would return True while 'hurrr' would return False. I don't need spelling suggestions or any spelling-correcting features. Just a simple function that takes a string and returns a boolean value.
I co... | PyEnchant is based on Enchant, which is a C library providing C and C++ interfaces. So you can just use that for C++. The minimal example will be something like this:
#include <memory>
#include <cstdio>
#include "enchant.h"
#include "enchant++.h"
int main ()
{
try
{
enchant::Broker *broker = e... |
4,521,524 | 4,521,602 | C++0x: rvalue reference versus non-const lvalue | When programming in C++03, we can't pass an unnamed temporary T() to a function void foo(T&);. The usual solution is to give the temporary a name, and then pass it like:
T v;
foo(v);
Now, along comes C++0x - and now with rvalue references, a function defined as void foo(T&&) will allow me to pass a temporary. Which ... | "since a function that takes an rvalue reference can take both rvalue references (unnamed temporaries) as well as lvalue references (named non-const references)"
This is an incorrect statement. During the first iterations of the rvalue reference specification this was true, but it no longer is and is implemented at le... |
4,521,655 | 4,521,683 | how does url within function body get compiled | I just pasted a url to my code, and forgot to comment it, but I was surprised to see MSVC++ compiled it successfully. My code is like this,
void my_function()
{
http://www.google.co.in/
}
How come this gets compiled by MSVC++?
| Actually, http followed by a colon is treated as a label by C++, which you can use in goto statements (like goto http;), and the rest (i.e //www.google.co.in) is treated as single line comment. That's why it gets compiled.
See more,
void your_function()
{
http://www.google.co.in/
https://www.crazy_c... |
4,522,067 | 4,522,073 | Destruction of non-pointer members of a class | When is a non-pointer member of a class destructed? Example:
class foo {
private:
int a;
public:
foo(int sa):a(sa){}
~foo(){}//does anything need to be done here?
};
{
foo(10);
}//the destructor is called
Should anything be done inside the destructor? Thanks!
| No, not a thing. a will be destroyed after any code in your destructor completes. In a case like this, you don't even need to declare a destructor; the compiler will do the right thing on its own.
|
4,522,111 | 4,522,279 | Heavy use of templates for mobile platforms | I've been flicking through the book Modern C++ Design by Andrei Alexandrescu and it seems interesting stuff. However it makes very extensive use of templates and I would like to find out if this should be avoided if using C++ for mobile platform development (Brew MP, WebOS, iOS etc.) due to size considerations.
In Symb... | In my personal experience using (and even abusing) templates very rarely result in large code bloat, and compiling with -Os will help a lot.
It's not that common to see huge template classes duplicated (instantiated) many times, both because rarely classes are huge, and because in most cases you only instantiate templa... |
4,522,211 | 4,884,055 | Temporaries in member functions - C++ | After putting some code to work, I'm trying to optimize it. One thing that I'm trying to avoid is the creation of temporaries. Given a class
class foo{
private:
int a;
public:
foo(int sa):a(sa);
~foo(){}
inline int multiply(int b) {return a*b;}//temporary?
};
The intel compiler is giving me th... | I think the compiler issues a warning because it translates:
const complex <double> oneover2piI = (1.0 / (2.0 * pi * I));
to invoke a default copy constructor:
Object::complex<double>(const complex<double>&)
which takes a reference of the temporary object as the argument, and makes a shallow copy (that results in da... |
4,522,250 | 4,522,261 | C++ Classes - dot notation vs pointer |
Possible Duplicate:
What is the difference between the dot (.) operator and -> in C++?
What's the difference between using dot notation and the pointer way?
Instantiating an object with or without a pointer.
Instantiate w/o a pointer = then use dot notation
Instantiate w/ a pointer = then use ->
What are the dif... | If I understand your question: in C++, a->b is just shorthand for (*a).b -- they're exactly the same (Edit: unless you've overloaded them to behave differently!), it's just that the first is easier to type. :)
If you're referring to using string a; versus string* a = new string(), that's a different topic -- look up st... |
4,522,375 | 4,522,439 | Switch passed type from template | Is it possible in C++ to check the type passed into a template function? For example:
template <typename T>
void Foo()
{
if (typeof(SomeClass) == T)
...;
else if (typeof(SomeClass2) == T)
...;
}
| Yes, it is...but it probably won't work the way you expect.
template < typename T >
void foo()
{
if (is_same<T,SomeClass>::value) ...;
else if (is_same<T,SomeClass2>::value) ...;
}
You can get is_same from std:: or boost:: depending on your desire/compiler. The former is only in C++0x.
The problem comes with what... |
4,522,459 | 4,522,717 | porter stemming algorithm implementation question? | I am trying to implement porter stemming algorithm but i am stuck at this point:
Step 1b
(m>0) EED -> EE feed -> feed
agreed -> agree
(*v*) ED -> plastered -> plaster
bled -> bled
(*v*) ING ... | m of 'feed' is indeed 1. Yet, you need to re-read the document carefully. The m in the condition refers to the measure of the stem, that is you need to calculate in after the replacement. In your case to check if feed -> fee is valid, you calculate m(fee) = 0, hence you don't do the replacement.
Also thanks for the alg... |
4,522,468 | 4,522,975 | c++ read content of a pointer | i'm new in c++ world, i just use it for litle app that help me in my work, now, i need to read the content of a folder, list the folder content, i've made a function that return a pointer with the name of every obj in the folder, but now, i don't know how to read the content of the pointer to just print it in a console... | In C++, dereferencing a pointer is achieved using the * operator, just like in 'C'.
However, there are a number of problems with your code, which I have addressed here because I was bored...
#include <string>
#include <iostream>
#include <list>
#include <dirent.h>
typedef std::list<std::string> dir_list;
bool listdir... |
4,522,604 | 4,522,626 | File IO Default Param Question | When opening a file, what is the default parameter to the file?
fstream a1;
ifstream b2;
ofstream c3;
a1.open("randFile.txt");
b2.open("randFile.txt");
c3.open("randFile.txt");
Reference : http://www.cplusplus.com/reference/iostream/fstream/open/
| fstream:
void open ( const char * filename,
ios_base::openmode mode = ios_base::in | ios_base::out );
So by default file will be opened both for input and output.
For ifstream and ofstream default value will be read-only and write-only correspondently (check method references for ifstream and ofstream)
|
4,522,900 | 4,522,928 | C++: constant reference to temporary | There are several questions about lifetime of constant reference on SO, but still I don't get it.
Is this piece of code valid?
struct S
{
const int &ref;
S( const int &x ) : ref(x) { }
};
int main( )
{
S s( 0 );
// ...
use( s.ref );
// ...
return 0;
}
Intuitively I'd say no, since 0 should... | Seems invalid to me according to 12.2/4 :
There are two contexts in which
temporaries are destroyed at a
different point than the end of the
fullexpression. The first context is
when an expression appears as an
initializer for a declarator defining
an object. In that context, the
temporary that holds the... |
4,522,958 | 4,523,196 | Font Rendering with Glyph information | I call "GetCharABCWidthsFloatW" to get the width information for a character. With this I will get the leftside bearing, right side bearing and the advanced width.
For positioning each characters, I will start with a "xPlacement" variables that will begin at zero. I will first adjust the xPlacement variable by subtract... | Since C# is mentioned in the question tags, maybe you'll find some interest in looking at some very powerful classes that ship with .NET Framework (starting with version 3.0, in fact shipped with WPF core assemblies). They are:
GlyphTypeFace: Specifies a physical font face that corresponds to a font file on the disk.,... |
4,522,994 | 4,523,074 | Undefined behaviour with non-virtual destructors - is it a real-world issue? | Consider the following code:
class A
{
public:
A() {}
~A() {}
};
class B: public A
{
B() {}
~B() {}
};
A* b = new B;
delete b; // undefined behaviour
My understanding is that the C++ standard says that deleting b is undefined behaviour - ie, anything could happen. But, in the real world, my experience is th... | This is a never-ending question in the C++ tag: "What is the predictable undefined behavior". Easy to resolve all by yourself: get every C++ compiler implementation and check if the predictable unpredictable still works. This is however something you have to do by yourself.
Do post back what you found out, that would... |
4,523,123 | 4,523,150 | How to get the path of the exexuter in C++? | I am using Visual studio 2008 and I want to get the absolute path of the .exe file?
meaning when the user opens the exe file, I need to know its absolute path??
thanks in advance
| Under Windows try the following:
char ExeName[8192]; // or what ever max. size you expect.
if (0 != GetModuleFileName (NULL, ExeName, sizeof (ExeName)))
{
printf ("Your array was probably not large enough. Call GetLastError for details\n");
}
If you compile for unicode use wchar_t.
|
4,523,178 | 4,523,216 | how to print out all elements in a std::stack or std::queue conveniently | If I do not to want to create a new container in order to do so?
| I've written a snippet to do that for debugging. For example:
std::stack<int> s; // works with std::queue also!
s.push(1);
s.push(2);
std::cout << s; // [ 1, 2 ]
Please forgive me for this hackish code! but this is what I've written months ago:
#include <stack>
#include <queue>
#include <ostream>
template <class Con... |
4,523,220 | 4,523,483 | Sorting a vector of (double precision) reals and obtain their | In C++ would like to sort a lengthy (2^20) vector of reals, obviously sort() does the trick. Having used R before I was used to the nice order() function which yields the permutation that leads to the sorted vector.
Example:
x = {24, 55, 22, 1}
Then the permutation
perm = {3, 2, 0, 1}
Maps the original x to the sorte... | Edit
Better than before approach without using helper vectors: (source on ideone):
#include <vector>
#include <algorithm>
#include <iostream>
template<class Vals>
void sortingPermutation(const Vals& values, std::vector<int>& v){
int size = values.size();
v.clear(); v.reserve(size);
for(int i=0; i < size; ++i)
... |
4,523,289 | 4,523,408 | Is there an automatic way to remove debugging methods for a release build? | Note: This is an extension of an earlier question I asked here: Do additional function/method definitions increase a program's memory footprint?
When I write a class, I usually end up writing several testing/debugging methods, used to make sure the class works as it should, or for printing data to help with debugging, ... | From a Java perspective, there are a variety of strategies:
If it is snippets of code that produce log messages, use log4j or one of the other logging frameworks.
If it is a complete method that is unused in the production code, leave it there. At runtime, the JIT compiler will notice that it isn't used and not both... |
4,523,425 | 4,523,733 | How can i resize a specific window after it's created? | I want to resize some game window (DirectX) after it has been created, the game window allows resizing by mouse from the edges. But i want to automate this because it's quite hard to do this by mouse: cursor is invisible at the edges and i must de-focus the window first to be able to resize by clicking at the edges. To... | There might be problems, but its better to try simple things first.
As your post tagged with C++ I suppose you're looking for WinAPI solution. Try this one:
int width = 640;
int height = 480;
HWND handle = ::FindWindow(NULL, _T("Window title"));
::SetWindowPos(handle, 0, 0, 0, width, height, SWP_NOMOVE | SWP_NOOWNER... |
4,523,479 | 4,654,171 | Passing existing C++ objects to Lua and calling the passed objects' member functions | I'm working on a little simulation project which uses Lua to drive the behavior of individual units (ants) and using Luabind to glue the C++ and Lua sides together. Each individual ant (there are different types, derived from the base class Ant) has a Run() function, which calls the appropriate script; the script then... | The solution to this problem seemed to be tied to the AntFactory class/member functions being static. As soon as I switched from registering and using this:
//C++
static int AntFactory::CreateAnt(foo, bar)
{}
//Lua
factory:CreateAnt(foo, bar)
to an instantiated object and regular member functions like this:
//C++
... |
4,523,498 | 4,523,539 | Referencing string with pointers |
Possible Duplicate:
Why does simple C code receive segmentation fault?
Why code snippet 2 doesn't behave like snippet 1?
//Code snippet 1
char pstr[] = "helloworld";
char *p = pstr;
p[2] = 'd';
//Code snippet 2
char *p = "helloworld";
p[2] = 'd'; //error: access violation
P.S Forgive my ignorance.
| "helloworld" is an array of const char. There's a hole in the type system which allows you to point to it with a char*, because a lot of code exists which uses a char * to point to readonly data and this is safe.
But const_cast rules apply, you can't actually write to the const data even if you make a non-const pointe... |
4,523,545 | 4,523,690 | C++: Accessing parent methods and variables | In which way should I access this parent method and parent variable?
class Base
{
public:
std::string mWords;
Base() { mWords = "blahblahblah" }
};
class Foundation
{
public:
Write( std::string text )
{
std::cout << text;
}
};
class Child : public Base, public Foundation
{
DoSomething(... | The two syntaxes you use in your code (this->... and qualified names) are only necessary specifically when there is ambiguity or some other name lookup issue, like name hiding, template base class etc.
When there's no ambiguity or other problems you don't need any of these syntaxes. All you need is a simple unqualified... |
4,523,617 | 9,878,792 | Omit return type in C++11 | I've recently found myself using the following macro with gcc 4.5 in C++11 mode:
#define RETURN(x) -> decltype(x) { return x; }
And writing functions like this:
template <class T>
auto f(T&& x) RETURN (( g(h(std::forward<T>(x))) ))
I've been doing this to avoid the inconvenience having to effectively write the functi... | It would appear that g++ 4.8 is getting an implementation of auto return type deduction.
The patch was put in by Jason Merrill who is also sending a paper for C++-1Y for the feature. The feature is available with -std=c++1y.
Still playing with it.
|
4,523,686 | 4,523,725 | boost's regex won't compile | I am using boost 1.45.0 on Ubuntu with Code::Blocks as my IDE, and I can't get basic_regex.hpp to compile. I'm pretty sure I set up boost correctly, because I can compile programs using boost::format without any errors. But I'm getting this annoying error, and I don't know how to get rid of it.
The code that is provoki... | This looks like a linker error. boost::regex is not a header only library so you need to pass -lboost_regex with correct -L/path/to/boost/lib to linker.
|
4,523,841 | 4,523,853 | How are char[] interpreted as const std::strings in arguments | I recently realized that I can do this:
void someFunc(const std::string &str)
{
//content
}
...
someFunc("Hello World"); //this works
I'm wondering how that works and why it works.
Thanks
| It works because std::string has a constructor from const char * that is not marked explicit. The C++ compiler will insert a call to one such constructor (per argument) if necessary to make the arguments match.
|
4,523,895 | 4,523,902 | Why is const required [C++]? |
Possible Duplicate:
What's the difference between a const member function and a non-const member function?
class Message
{
public:
Message(const char* pStr, const char* key);
Message(const char* pStr);
Message();
void encryptMessage();
void decryptMessage();
... |
const char* getUnMessage() const;
Indicates that getUnMessage() may be invoked for an instance of the class that is const. It doesn't have any effect on the const-ness of the return value.
const char* getUnMessage() const;
...indicates that the value being returned from getUnMessage() is const (and says nothing abo... |
4,523,959 | 4,524,064 | std::map default value for build-in type | Recently, I was confused by the std::map operator[] function.
In the MSDN library, it says: "If the argument key value is not found, then it is inserted along with the default value of the data type."
I tryed to search much more exactly explanation for this issue. For example here:
std::map default value
In this page, ... | This is defined in the standard, yes. map is performing "default initialization" in this case. As you say, for class types, that calls a no-arguments constructor.
For built-in types, in the '98 standard, see section 8.5, "Initializers":
To default-initialize an object of type T means:
if T is a non-POD ...
if T is ... |
4,524,033 | 4,524,415 | Go to the next instruction without pressing enter | my problem is trying to go to the next instruction without pressing enter.. this is my code
cout<<"Enter Date Of Birth: ";
cin>>day;
cout<<"/";
cin>>month;
cout<<"/";
cin>>year;
by only providing 2 digit number for day, i want the next instruction to get printed without me pressing enter, and so goes to the rest month... | You could write a function like this:
#include <iostream>
#include <sstream>
#include <conio.h>
#include <vector>
#include <math.h>
int getInput(int count)
{
int i = 0;
std::stringstream ss;
while (count)
{
char c = _getch();
std::cout << c;
ss << c;
count--;
}
... |
4,524,060 | 4,524,193 | Can't get GetModuleFileNameA to work, keep getting error 'missing type specifier...' | I am trying to use 'GetModuleFileNameA' but I keep getting the error 'c4430: missing type specifier - int assumed'. From reading the results from my google search I am guessing that it is from my use of NULL:
char Filename[MAX_PATH]; //this is a char buffer
GetModuleFileNameA(NULL, Filename, sizeof(Filename));
NULL i... | Have you tried GetModuleFileNameA(GetModuleHandle(0),Filename,sizeof(Filename)) ?
From MSDN GetModuleFileName description
The global variable _pgmptr is automatically initialized to the full path of the executable file, and can be used to retrieve the full path name of an executable file.
You might want to check if th... |
4,524,095 | 4,524,134 | Why is it useful to make a const function? | why is it so useful to make a function const if you only can read variables but not write(class variable)?
| If you pass something else a const pointer or const reference to an instance of your class then it can only call the class's const methods (if any).
Obviously, if you never bother with const-correctness with your types then you can ignore this.
I suppose it may also help the compiler optimize things in certain situatio... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.