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,298,166 | 3,317,468 | Change background of indexed QTabBar tabs using stylesheets | Using Qt stylesheets, is it possible to set a different background colour for each tab in a QTabBar that has 4 or more tabs?
My Qt application has 6 tabs underneath the menu bar. I'd like to change their background colours to 6 different colours using stylesheets.
2 issues appear to be standing in my way:
I can only s... | The individual tabs are structs rather than objects. These structs are then used on painting. See the Qt source for more details.
I've had an experiment with this and I can't find a way to access a direct index, like you indicated. For your reference, I tried using properties such as the text, toolTip, whatsThis but c... |
2,298,217 | 2,298,301 | JNI Application State | How is state kept when accessing methods through JNI? In the example below my Java code is calling the native method drawFromJni, will my native class _nc be persisted between calls?
If there were better native debugging tools for the NDK this would be pretty easy to find out, but I'm really having problems with the N... | The implementation of JNI functions follows the scoping rules for the language you're implementing in. If you declare _nc as a global variable (as you've done in your example), it will be shared throughout the entire application.
|
2,298,292 | 2,298,383 | Container relationships and encapsulation | In my game engine I have a State class that represents the game world at a point in time. This State contains a number of Body objects that define one rigid body each. Each State has a container to keep track of the Body objects it owns, and each Body has a pointer back to its parent State.
Outline of State class:
clas... | Well, one way you could do it would be to have a friend function of both classes:
void associate(State& s, Body& b)
{
s.addBody(&b);
b.setState(&s);
}
|
2,298,305 | 2,298,394 | OpenProcess / SetProcessAffinityMask on process started by my service | In my manager.exe, I'm trying to change the CPU usage of my worker.exe, which is started by my service.exe. Service.exe is running under the System Account, while manager.exe is running under the logged in user's account.
When I call OpenProcess in manager.exe with worker.exe's PID, I get NULL for procHandle:
HAND... | You shouldn't have to call OpenProcess.
The service should already have a full-permission handle to the worker from when it called CreateProcessAsUser or CreateProcessWithLogonW. Use DuplicateHandle to make a version of that handle suitable for use by the manager process, and then have the service send that handle to t... |
2,298,387 | 2,298,531 | #warning and macro evaluation | I have the following code :
#define LIMIT_DATE \"01-03-2010\"
#ifdef LIMIT_DATE
#if _MSC_VER
#pragma message ("Warning : this release will expire on " LIMIT_DATE)
#elif __GNUC__
#warning ("Warning : this release will expire on " LIMIT_DATE)
#endif
#endif
The problem is that LIMIT_DATE is... | From gcc preprocessor documentation
Neither #error nor #warning
macro-expands its argument. Internal
whitespace sequences are each replaced
with a single space. The line must
consist of complete tokens. It is
wisest to make the argument of these
directives be a single string
constant; this avoids problem... |
2,298,604 | 2,299,253 | When should I concern myself with std::iostream::sentry? | Online references have rather brief and vague descriptions on the purpose of std::iostream::sentry. When should I concern myself with this little critter? If it's only intended to be used internally, why make it public?
| Most people will never write any code that needs to deal with creating sentry objects. A sentry object is needed when/if you extract data from (or insert it into) the stream buffer that underlies the stream object itself.
As long as your insertion/extraction operator uses other iostream members/operators to do its work... |
2,298,781 | 2,298,796 | Why do un-named C++ objects destruct before the scope block ends? | The following code prints one,two,three. Is that desired and true for all C++ compilers?
class Foo
{
const char* m_name;
public:
Foo(const char* name) : m_name(name) {}
~Foo() { printf("%s\n", m_name); }
};
void main()
{
Foo foo("three");
Foo("one"); // un-named object
printf("t... | A temporary variable lives until the end of the full expression it was created in. Yours ends at the semicolon.
This is in 12.2/3:
Temporary objects are destroyed as the last step in evaluating the full-expression (1.9) that (lexically) contains the point where they were created.
Your behavior is guaranteed.
There ar... |
2,299,028 | 2,299,053 | C++ pthreads - using code I used in C gives me a conversion error | I am running the same exact code that I ran in plain C:
pthread_create(&threads[i], &attr, SomeMethod, ptrChar);
And I get the errors:
error: invalid conversion from
'void*(*)(char'*)' to 'void*(*)(void*)'
error: initializing argument 3 of 'int
pthread_create(__pthread_t**,
__pthread_attr_t* conts*, void*(*)(vo... | Like it says, they are two different function signatures. You should do:
void *SomeMethod(void* direction) // note, void
{
char* dir = static_cast<char*>(direction); // and get the value
}
C was casting from one function pointer to the other, apparently. Casting one function pointer to another is undefined behavio... |
2,299,106 | 2,299,158 | How do I determine the number of places following a decimal in a floating point value? | In C++ you can use std::numeric_limits<FloatingPointType>::digits10 to find out exactly how many places of precision you can get before the decimal place. How do I find out how many decimal places I can get following it, if I know the number will always be fixed-point between 0 and 1 inclusive?
Edit: The reason I ask... | std::numeric_limits<FloatingPointType>::digits10 is the total number of decimal digits the type can exactly represent. If you write a number as 1234.56 or 1.23456 ⋅ 103 or 123456 ⋅ 10-2 doesn't matter for the number of exact digits, so there is no distinction between before and after the decimal place.
|
2,299,109 | 2,299,492 | How to handle linker errors in C++/GNU toolchain? | Given a C++/GNU toolchain, what's a good method or tool or strategy to puzzle out linker errors?
| With gcc toolchain, I use:
nm: to find the symbols in object files
ld: to find how a library links
c++filt: to find the C++ name of a symbol from its mangled name
Check this for details.
|
2,299,360 | 2,302,553 | Comparison of performance between Scala etc. and C/C++/Fortran? | I wonder if there is any reliable comparison of performance between "modern" multithreading-specialized languages like e.g. scala and "classic" "lower-level" languages like C, C++, Fortran using parallel libs like MPI, Posix or even Open-MP.
Any links and suggestions welcome.
| Given that Java, and, therefore, Scala, can call external libraries, and given that those highly specialized external libraries will do most of the work, then the performance is the same as long as the same libraries are used.
Other than that, any such comparison is essentially meaningless. Scala code runs on a virtual... |
2,299,397 | 2,299,500 | How to get the currently focused menu item ID? | I want to display info when my mouse cursor is on an item in my menu by using SendMessage() to my statusbar. How do i get the current menu item ID ? I suppose they use same ID's as my Visual Studio shows in the menu editor.
I found these on msdn but none of them seems to serve my needs:
WM_COMMAND
WM_CONTEXTMENU
WM_ENT... | While the user is moving around the menu you get WM_MENUSELECT messages. LOWORD(lParam) will be the id of the menu item unless what is currently being selected is a popup rather than an item.
so your code looks something like this
case WM_MENUSELECT
{
HMENU hmenu = (HMENU) lParam;
UINT idItem = (UINT) LOWO... |
2,299,460 | 2,299,542 | For a given number N i have to find all the prime numbers it's consisting of | Need a suggestion for an algorithm.
For a given number N i have to find all the prime numbers it's consisting of, like this:
N = 49
49 = 7 ^ 2
N = 168
168 = (2 ^ 3) * (3 ^ 1) * (7 ^ 1)
If you want to help me even more you can write the algo in c++.
Thanks.
| The most straightforward way is trial division. Basically just try dividing n by each prime number up to sqrt(n). For large numbers, this is a very slow algorithm.
http://en.wikipedia.org/wiki/Trial_division
For more sophisticated algorithms, try http://en.wikipedia.org/wiki/Integer_factorization
|
2,299,523 | 2,299,591 | Why does function calls to templatized base classes not work? | Consider the following example:
template <typename T>
class A {
public:
void f() {
cout << "A::f()\n";
}
};
template<>
class A<int> {
};
template<typename T>
class B: public A<T> {
public:
void g() {
cout << "B::g()\n";
A<T>::f();
}
};
int m... | It fails at 2). Member function of templates are instantiated when called.
More precisely: When a class template is instantiated, the declaration of its member functions are instantiated, but not their definition. The definition is instantiated when the function is used.
|
2,299,564 | 2,299,794 | Sending data between two ethernet interfaces on the same box | I would like to send data between two ethernet interfaces that are connected with a crossover cable in Linux. The two ethernet interfaces are on the same box. I defined the ethernet interfaces to have different static ip addresses (1.2.3.4 and 5.6.7.8) and have been using sockets to send bytes from one IP address to ... | You can not communicate using IP between 1.2.3.4/24 to 5.6.7.8/24 without going though a router. The problem is that IP can only talk to other computers in the same network segment. To calulate the network address you need to do a logic AND between both the interface address and the subnet mask. This will give you t... |
2,299,626 | 2,299,679 | Problem with sprintf function, last parameters are wrong when written | So I use sprintf
sprintf(buffer, "%f|%f|%f|%f|%f|%f|%d|%f|%d", x, y, z, u, v, w, nID, dDistance, nConfig);
But when I print the buffer I get the 2 last parameters wrong, they are lets suppose to be 35.0000 and 0 and in the string they are 0.00000 and 10332430 and my buffer is long enough and all the other parameters a... | I'd check to make sure your argument types match up with your format string elements. Trying to display a double as an integer type (%d) or vice versa can give you strange output.
|
2,299,824 | 2,299,847 | How do I use the C preprocessor to make a substitution with an environment variable | In the code below, I would like the value of THE_VERSION_STRING to be taken from the value of the environment variable MY_VERSION at compile time
namespace myPluginStrings {
const char* pluginVendor = "me";
const char* pluginRequires = THE_VERSION_STRING;
};
So that if I type:
export MY_VERSION="2010.4"
pluginRequ... | If I recall correctly, you can use the command line parameter -D with gcc to #define a value at compile time.
i.e.:
$ gcc file.c -o file -D"THE_VERSION_STRING=${THE_VERSION_STRING}"
|
2,300,191 | 2,300,377 | Dynamic memory allocation question | when you allocate dynamic memory on the heap using a pointer,
char *buffer_heap = new char[15];
it would be represented in memory as:
ÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍýýýý««««««««þþþ
why doesn't there be a NULL terminating character at the end instead of ýýýý««««««««þþþ?
| Í is byte 0xCD, which the Windows debug allocator writes into your 15 bytes of memory to indicate that it is uninitialised heap memory. Uninitialized stack would be 0xCC. The idea is that if you ever read memory and unexpectedly get this value, you can think to yourself, "hmm, I've probably forgotten to initialise this... |
2,300,193 | 2,300,323 | How can I search for a specific computer over a closed network? | I have a network of 16 computers all linked to the same switch, not connected to the internet. One of the 16 computers has a small Java app running on it along with a BlazeDS server (aka it's listening on a port for a message).
Currently, the other 15 "client" computers have to manually enter the "server" IP where the... | I would strongly recommend using Zeroconf/Bonjour for this as it makes it trivially easy to handle decentralized "where is the others who I should know about and should know about me"?
The easiest way to do this in Java (and completely inside your own application) is with the jmdns project. http://jmdns.sourceforge.ne... |
2,300,351 | 2,300,409 | Playing MIDI out in OS X, C++ | How can I send MIDI messages out from a C++ program and have them play the sound from the General MIDI bank?
I've looked around and there doesn't seem to be a simple answer, and my brain starts to melt after reading long manuals about CoreMIDI and things like that.
I have a simple C++ game/synthesizer project, and all ... | Another option would be rtmidi
It's aimed to be simple and crossplatform
I've used the similar rtaudio for realtime audio i/o, and it was relatively easy to use.
You should be able to list all midi devices with the example code, then select the GM bank, and send the appropriate MIDI message (note on/off message), after... |
2,300,401 | 2,300,761 | QApplication: How to shutdown gracefully on Ctrl-C | I have a QApplication that, depending on command line parameters, sometimes doesn't actually have a GUI window, but just runs without GUI. In this case, I want to shut it down gracefully if CTRL-C was hit. Basically my code looks like this:
int main(int argc, char* argv[])
{
QApplication app(argc, argv);
... /... | As it isn't documented, QApplication::watchUnixSignal shouldn't be used. And, from reading the code, it will not work properly when using the glib event dispatcher (which is the default on Linux).
However, in general you can safely catch Unix signals in Qt applications, you just have to write a bit of the code yoursel... |
2,300,471 | 2,300,511 | Windows Command Line History | I need to programmatically mount a WebDAV volume in Windows using C, and I think I'm going to use system() to achieve this (via the 'net use' command)... However, since net use requires that the password be written in plain text, I just wanted to make sure there's no logging of commands run in the Windows command line ... | The shell has a history, but it's only stored in memory not a log on disk. That said, it could end up in the swap file and open to (slightly non-trivial) discovery. Then again, if you did the connection directly in your own program using something like WNetAddConnection2, it could end up in the swap file anyway.
|
2,300,703 | 2,300,711 | STL vector taking up too much memory | Im using a STL vector in my SDL program. and it looks like this: vector< Bullet * > vec; this makes a vector that can contain pointers to Bullet objects. when i run my program i only add one item at a time using: vec.push_back( new_bullet ); (new_bullet is a pointer to a "new" Bullet object. then in a following functio... | Sounds like you're not deleteing the "bullet" objects as you remove them from the vector.
|
2,300,894 | 2,301,062 | Reading a process memory | I'm trying to read the process memory of a console program using ReadProcessMemory() API function.
Updated Code:
HWND hWnd = FindWindow(NULL, "Read Memory Window");
DWORD ProcessId;
ProcessId = GetProcessId(hWnd);
GetWindowThreadProcessId(hWnd, &ProcessId);
HANDLE hProcess = OpenProcess(PROCESS_VM_... | your using a fixed address, that is generally a very bad idea, even more so now that windows vista and windows 7 use ASLR, making it unsafe for even fixed based modules(even without ASLR its unsafe, because the image can reallocated for various reasons).
also, that address looks very dodgy, how did you derive that add... |
2,300,895 | 2,300,918 | How to add many strings in c++ | As I know that C++ only allows to add 2 strings together, i.e:
s = s1 + s2
But how can I add many strings together? Like:
s = s1 + s2 + s3 + s4 + ... + sn
| If you're trying to append string objects of std::string class, this should work.
string s1 = "string1";
string s2 = "string2";
string s3 = "string3";
string s = s1 + s2 + s3;
OR
string s = string("s1") + string("s2") + string("s3") ...
|
2,301,065 | 2,301,080 | Why use template<> without specialization? | I was reading the STL source code (which turned out to be both fun and very useful), and I came across this kind of thing
//file backwards/auto_ptr.h, but also found on many others.
template<typename _Tp>
class auto_... | That's specialization. For example:
template <typename T>
struct is_void
{
static const bool value = false;
};
This template would have is_void<T>::value as false for any type, which is obviously incorrect. What you can do is use this syntax to say "I'm filling in T myself, and specializing":
template <> // I'm go... |
2,301,363 | 2,301,375 | Creating a unique, auto assigned variable with Microsofts Extensible Storage Engine | I'm using Extensible Storage Engine and want a unique column (32bits wide). I need the values in this column to be auto assigned by the database
I'm hoping to find something like JET_bitIndexUnique that I can mask in?
if there isnt such a mask whats the proper way to achieve the goal?
| Please see: Version, Auto-Increment and Escrow Columns
Auto increment columns are automatically
incremented by ESE when a new record
is inserted into the table. The value
contained in the auto-increment column
is unique for every record in the
table and is not guaranteed to be
continuous. These values are ... |
2,301,371 | 2,301,401 | SendMessage Always returns ZERO? | Why does Windows SendMessage() always return ZERO, even the message delivery is success? Is there anyway to check the message delivery failure with SendMessage() ?
EDIT
Forgot to mention that I'm using SendMessage() inside a c++ DLL
LRESULT result = ::SendMessage(hwndOtherWindow,WM_COPYDATA, NULL/*(WPARAM)this->GetSafe... | A zero return from SendMessage for WM_COPYDATA means the target application didn't process the message (FALSE = 0).
The message might deliver successfully, but if the target application doesn't handle the message properly (ie, wrong return value, or passing it to the default window procedure) then your SendMessage call... |
2,301,372 | 2,301,427 | Undefined/Unspecified/Implementation-defined behaviour warnings? | Can't a compiler warn (even better if it throws errors) when it notices a statement with undefined/unspecified/implementation-defined behaviour?
Probably to flag a statement as error, the standard should say so, but it can warn the coder at least. Is there any technical difficulties in implementing such an option? Or i... | It all boils down to
Quality of Implementation: the more accurate and useful the warnings are, the better it is. A compiler that always printed: "This program may or may not invoke undefined behavior" for every program, and then compiled it, is pretty useless, but is standards-compliant. Thankfully, no one writes co... |
2,301,615 | 2,301,636 | sorting vector with 3D points by a coordinate value -- syntax | I want to sort points_vec vector as shown in the pseudocode below. I want to sort this vector, by a coordinate value like x or y or z
class A{
std:vector<double*> points_vec;
void doSomething();
}
Then, in method A::doSomething, I want sort this vector:
void A::doSomething() {
std::sort(points_vec.begin()... | You have two options for sorting: either pass a function/functor to sort or define the operator< for your class. Now, your class A seems to be more of a wrapper for a set of coordinates. So, create another class for your co-ordinates.
struct Point {
double x_, y_, z_;
Point(double x, double y, double z) : x_... |
2,301,839 | 2,301,868 | Class constructed only on stack; not with new. C++ | Is there a way to create a class Foo
so that I can do:
Foo foo;
but not
Foo* foo = new Foo();
?
I don't want people to be able to allocate copies of Foo on the heap.
Thanks!
EDIT: Sorry, I was wrong on the "stack only, not heap". What I want to say is "can not use new operator".
| Make your operator new private.
#include <new>
struct Foo {
int x;
private:
void* operator new (std::size_t size) throw (std::bad_alloc);
};
On C++0x you can delete the operator new:
struct Foo {
int x;
void* operator new (std::size_t size) throw (std::bad_alloc) = delete;
};
Note t... |
2,301,928 | 2,301,994 | measuring response time through packets? | good day!
im developing an app in c++ and winpcap that will list all the URL accessed in the browser with its corresponding response time..
currently, i can now track or monitor all accessed url through capturing and analyzing packets..
is there any way of measuring the response time of a web page to load, from the req... | You will have to keep track of the individual TCP connections between the browser and the server -
that's just keeping track of the source/destination IP and port numbes in the packets you capture.
Then you'll have to parse the HTTP in the captured packets and correlate HTTP requests with its response and take the tim... |
2,301,991 | 2,302,007 | C++ Portable way of programmatically finding the executable root directory |
Possible Duplicate:
how to find the location of the executable in C
Hi,
I am looking for a portable way to find the root directory of a program (in C++). For instance, under Linux, a user could copy code to /opt, add it to the PATH, then execute it:
cp -r my_special_code /opt/
export PATH=${PATH}:/opt/my_special_cod... | There is no portable way of doing this. Neither the C nor C++ standard require the argv array to hold this information and there are no library routines in the standard libraries that provide it.
You will need to find a non-portable way of obtaining this information in a platform-specific way, such as GetModuleFileName... |
2,302,251 | 2,302,259 | checking if a point is already in a vector/list -- performance | This is related to this question
I have a vector of points that will, for instance, store 100K+ points.
std::vector<Point> point_vec;
I want to check if a position (x, y, z) to be added is already in point_vec (represented by an instance of class Point ). The following function will check this (in a for loop)
bool s... | Is the collection of points always sorted or must it sometimes be in an unsorted state? If the former, a std:;set of points will be fast to determine if a point is already there, and will maintain the points in sorted order. You would have to supply a suitable ordering function (not an equality one), which may be faste... |
2,302,279 | 2,302,463 | Return an array in c++ | Suppose I have an array
int arr[] = {...};
arr = function(arr);
I have the function as
int& function(int arr[])
{
//rest of the code
return arr;
}
What mistake am I making over here??
| int& function(int arr[])
In this function arr is a pointer, and there's no way to turn it back to an array again. It's the same as
int& function(int* arr)
int arr[] = {...};
arr = function(arr);
Assuming the function managed to return a reference to array, this still wouldn't work. You can't assign to an array. At... |
2,302,288 | 2,302,506 | Set up CUTE (Eclipse CDT Unit Testing Plugin) on OSX | I am trying to set up the CUTE unit testing plugin for Eclipse C/C++ Development Tools.
The documentation says:
If you did not install Boost in the standard location, you will need to specify it. Right click on the newly created CUTE project, and select Properties. In C/C++ Build, Settings, choose the Tool Settings ta... | While many libraries in boost are header-only, some require libraries (as in .lib .a .dyld &c) to be built. Here are instructions on building boost.
As the bold part says "specify the library path and the boost_thread library name", it seems like you should build boost sources so that it produces needed libraries, like... |
2,302,388 | 2,302,575 | Draw a antialiased line in a fast way | I have a little problem. I've recently created an algorithm to allow thick lines to be drawed onscreen (as a quad structure), the problem is that when the line is very long and diagonal the aliasing is very high, making the line look very bad.
What are my chance to reduce the aliasing while trying to have high performa... | There is a very good article in GPU Gems 2 about antialiasing technique for lines, see it here:
http://http.developer.nvidia.com/GPUGems2/gpugems2_chapter22.html
|
2,302,419 | 2,302,492 | C++ TCL (tree container library): How to traverse a tree from a node straight to root | I am using this library to hold information about tree structure:
http://www.datasoftsolutions.net/tree_container_library/overview.php
Here is simplified version of my C++ code:
#include "tcl/sequential_tree.h"
// Node has some data which is not important now
typedef sequential_tree<Node> gametree_t;
typedef sequenti... | the common method is to use something like this
Node tmp = gametree_it;
while (tmp->parent() != NULL) {
tmp = tmp->parent();
}
root = tmp->get();
Maybe you have to use while (tmp->has_parent()) or something like that instead.
|
2,302,475 | 2,302,498 | unresolved external symbol "public: void __thiscall..." | I'm using boost::function to enable the passing of a function to a Button constructor so it holds that function. Calling it whenever it is activated.
typedef boost::function< void() > Action;
In my TitleState I've constructed a Button like this.
m_play(
ButtonAction, // This is where I pass a function to Button... | Add the library option when you are linking your program:
g++:
g++ -L/your/library/path -lyour_library_name
vc++:
using boost with vc++
|
2,302,487 | 2,305,834 | OpenGL Texture Transparency | I'm using C++ and OpenGL to make a basic 2D game, I have a png image with transparent areas for my player. It works perfectly on my laptop and lab computers, but on my desktop the entire image is mostly see through, not just the areas that are meant to be. What could cause/fix this?
Here is the code I've used and is th... | I found the problem, I changed
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
to
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
and it works correctly, not sure why though.
|
2,302,713 | 2,302,766 | Problem with method in a class when called from another class | I'm writing a simple scene graph to hold some objects so I can control the rendering and drawing of these objects in OpenGL. I have two classes, one called GameObject which defines the objects with certain parameters such as position and velocity as well as how to draw the object. It has a method called update() which ... | There are some big problems here.
GameObject *go = new GameObject();
go = this->data;
You're creating a new object and then you are forgetting the pointer to that object. This happens every time you call render, so you have tons of memory that you aren't using that grows with time. You can just say:
GameObject *go = N... |
2,302,734 | 2,302,806 | Memory debugger for mixed-mode C++ applications | I have to maintain a large C++ mixed-mode application (VC++ 2005, CLR-support: /clr:oldsyntax). I suspect the program has a number of memory leaks but it's hard to find them manually. For native C++ applications we use Purify (and Valgrind on Linux).
Unfortunately Purify does not support mixed mode assemblies. Anybody... | Take a look at AQTime. I've used it and it's pretty decent. They also provide a free trial version that's unhindered (last I checked).
|
2,302,815 | 2,303,509 | VS C++ 2008: Modifying Output text? | I'm using Visual Studio C++ 2008 Express Edition.
Is it possible to modify the text in the Output pane for compilation (or other) errors?
For example, I might receive an error that reads: error C2556: int Class::getResult(void) + a lot more relative garbage.
I can parse the output text and find and fix my mistakes easi... | It's pretty easy to take your best shot at this problem. The compiler itself is a command-line program named cl.exe. If you want to filter its output, what you need to do is create a program that's also named cl.exe. It will need to pass all the command line arguments through to the original cl.exe. Then it'll take wha... |
2,302,841 | 2,303,612 | Win32 PlaySound: How to control the volume? | I'm using the Win32 MultiMedia function PlaySound to play a sound from my application.
I would like to be able to dynamically adjust the volume of the sound that is being played without modifying the system volume level.
The only suggestions I could find for manipulating the volume of sounds played via PlaySound was to... | Two possible solutions:
First, if you are targeting Vista and up, you can use the new Windows Audio APIs to adjust the per-application volume. ISimpleAudioVolume, IAudioEndpointVolume, etc...
If that's not suitable, can load the WAV file directly into memory and modify the samples in place. Try this:
Read the WAV fil... |
2,302,969 | 2,303,798 | Convert a float to a string | How can I convert a floating point integer to a string in C/C++ without the library function sprintf?
I'm looking for a function, e.g. char *ftoa(float num) that converts num to a string and returns it.
ftoa(3.1415) should return "3.1415".
| When you're dealing with fp numbers, it can get very compex but the algorithm is simplistic and similar to edgar holleis's answer; kudos! Its complex because when you're dealing with floating point numbers, the calculations will be a little off depending on the precision you've chosen. That's why its not good program... |
2,303,067 | 2,303,085 | Initialize static member of template inner class | I have problem with the syntax needed to initialize a static member in a class template. Here is the code (I tried to reduce it as much as I could):
template <typename T>
struct A
{
template <typename T1>
struct B
{
static T1 b;
};
B<T> b;
typedef B<T> BT;
T val() { return b.b; }
};
template <typena... | Change the definition of b to the following:
template <typename T> template<typename T1>
T1 A<T>::B<T1>::b;
Notice that the typedef and B<T1> don't necessarily specify the same type: While the typedef relies on T being passed to B, B<T1> relies on the template parameter T1 being passed. So you cannot use the typedef h... |
2,303,087 | 2,303,103 | Assignment vs Initialization in C++ | I thought that constructors control initialization and operator= functions control assignment in C++. So why does this code work?
#include <iostream>
#include <cmath>
using namespace std;
class Deg {
public:
Deg() {}
Deg(int a) : d(a) {}
void operator()(double a)
{
... | This is what's called implicit type conversion. The compiler will look to see if there's a constructor to directly change from the type you're assigning to the type you're trying to assign, and call it. You can stop it from happening by adding the explicit keyword in front of the constructor you wouldn't like to be imp... |
2,303,188 | 2,303,197 | const correctness and return values - C++ | Please consider the following code.
struct foo
{
};
template<typename T>
class test
{
public:
test() {}
const T& value() const
{
return f;
}
private:
T f;
};
int main()
{
const test<foo*> t;
foo* f = t.value();
return 0;
}
t is a const variable and value() is a constan... | Because you have two levels of indirection - in your main function, that call to value returns a reference to a const pointer to a non-const foo.
This can safely be copied into non-const pointer to a non-const foo.
If you'd instantiated test with const foo *, it would be a different story.
const test<const foo*> t;
foo... |
2,303,264 | 2,303,284 | What is causing a segmentation fault? | I have been attempting to write a program that will determine if a number is prime or not. I have based it off of the Sieve of Eratosthenes. Anyway, my program works for small numbers (15485863 works), but if I use large numbers (ex. 17485863) I receive a segmentation fault. I am using unsigned long longs and do not th... | On Line 24 you have: bool array[arrayLength]; You cannot declare an array on the stack like this. The program is crashing on line 29. You need to declare this on the heap using new/delete;
Something to this effect (I may have a leak or two in there, but you get the idea);
//Beginning on Line 28
bool *array = new b... |
2,303,345 | 2,303,369 | Undefined reference to | I'm doing an opengl/qt3 assignment, but I'm running into an undefined reference error:
Renderer.h:
...
#include "Mesh.h"
... Mesh mesh;
Renderer.cpp:
...
mesh.load("ball.obj");
...
Mesh.h:
...
bool load(string filename);
...
Mesh.cpp:
#include "Mesh.h"
...
bool Mesh::load(string filename) { ... }
...
but the comp... | Forgot to add the files to QT Designer. Solved!
|
2,303,381 | 2,317,312 | Qt - how to detect what application is in focus | Is it possible to know what application is in focus using Qt ?
| You'll need to use some Win32 API functions. Mainly GetActiveWindow(). Search MSDN for the function.
|
2,303,408 | 2,303,574 | C++ Unwanted infinite while loop | I get an infinite loop when I use the following code in C++ and I don't understand why. I suspect the problem is within the input_words() function. Here is the code:
#include<iostream>
using namespace std;
string input_words(int maxWords) {
int nWord = 0;
string words[maxWords];
string aWord = "";
whil... | I modified the function in such a way:
string input_words(int maxWords) {
cout << "started" << endl;
int nWord = 0;
string words[maxWords];
string aWord = "";
while (aWord != "Quit" && nWord < maxWords) {
cout << "Enter a number ('Quit' to stop): ";
getline (cin, aWord);
word... |
2,303,435 | 2,303,449 | How to declare vectors in C++? | I'm trying to use a vector of strings in my code instead of an array of strings but apparently I miss some detail in the declaration of the vector. Using the following code, I get this error: ‘vector’ was not declared in this scope
// Try to implement a vector of string elements
#include<iostream>
using namespace std... | You should add these includes:
#include <vector>
#include <string>
|
2,303,440 | 2,303,478 | Limit Speed Of Gameplay On Different Computers | I'm creating a 2D game using OpenGL and C++.
I want it so that the game runs at the same speed on different computers, At the moment my game runs faster on my desktop than my laptop (i.e. my player moves faster on my desktop)
I was told about QueryPerformanceCounter() but I don't know how to use this.
how do I use that... | As a rule, you want to do all gameplay calculations based on a time delta, i.e. the amount of time that has passed since the last frame. This will standardize speed on all machines. Unless you want extreme precision, you can use clock() (from <ctime>) to get the current timestamp.
Example:
void main_loop() {
static ... |
2,303,490 | 2,303,881 | Why can't the linker prevent the C++ static initialization order fiasco? | EDIT: Changed example below to one that actually demonstrates the SIOF.
I am trying to understand all of the subtleties of this problem, because it seems to me to be a major hole in the language. I have read that it cannot be prevented by the linker, but why is this so? It seems trivial to prevent in simple cases, l... | Linkers traditionally just link - i.e. they resolve addresses. You seem to be wanting them to do semantic analysis of the code. But they don't have access to semantic information - only a bunch of object code. Modern linkers at least can handle large symbol names and discard duplicate symbols to make templates more use... |
2,303,555 | 2,303,674 | Taking user input with pointers | I'm trying to get better at using pointers, and not using array notation. So I have a function to read user input and return a pointer to that array. I can do it like this and it seems to work ok:
float *GetValues(float *p, size_t n)
{
float input;
int i = 0;
if ((newPtr = (float *)malloc(n * sizeof(... | A few tips:
The first GetValues allocates newPtr (which is not declared within the function, a global variable?) but then does nothing with it. There are two possible ways that your function could work with regards to memory storage:
The function gets a pointer to valid memory for an array of size large enough. In th... |
2,304,061 | 2,304,127 | Is it safe to use boost serialization to serialize objects in C++ to a binary format for use over a socket? | I know that you can use boost serialization to serialize to a text format and then push over a socket, but I'd like to serialize a class of statistics data into a binary format (both for size and encoding/decoding overhead reasons). Is it safe to use boost serialization for this?
My specific worries are:
Differenc... | No, in general boost binary serialization is not machine-independent. See here.
|
2,304,077 | 2,304,094 | How do i create a unicode filename in linux? | I heard fopen supports UTF8 but i dont know how to convert an array of shorts to utf8
How do i create a file with unicode letters in it? I prefer to use only built in libraries (no boost which is not installed on the linux box). I do need to use fopen but its pretty simple to.
| fopen(3) supports any valid byte sequence; the encoding is unimportant. Use nl_langinfo(3) with CODESET to get what charset you should use for the encoding, and libiconv or icu for the actual encoding.
|
2,304,203 | 2,304,211 | How to use boost bind with a member function | The following code causes cl.exe to crash (MS VS2005).
I am trying to use boost bind to create a function to a calls a method of myclass:
#include "stdafx.h"
#include <boost/function.hpp>
#include <boost/bind.hpp>
#include <functional>
class myclass {
public:
void fun1() { printf("fun1()\n"); }
v... | Use the following instead:
boost::function<void (int)> f2( boost::bind( &myclass::fun2, this, _1 ) );
This forwards the first parameter passed to the function object to the function using place-holders - you have to tell Boost.Bind how to handle the parameters. With your expression it would try to interpret it as a me... |
2,304,415 | 2,304,464 | question about recompiling the library in C++ | Suppose my class is depending on other library. Now I need to modify the class for one application. What kind of modification will force me to recompile
all libraries. What's the rule to recompile all libraries?
for example, I only know the case 2) is like this. What about the others?
1) add a constructor
2) add a data... | Do you really mean that the class you are changing depends on the library? You never have to recompile a library because you've changed something that depends on the library. You recompile a library if you change something that the library depends on.
The answer is that in C++, technically all of those things require r... |
2,304,466 | 2,391,745 | Render webbrowser control offscreen (or hidden) | I have a small application which embeds webbrowser controls. In that application I have created a popup class. This popup is used to display server generated error messages.
I want to be able to resize the popup to suit the message. This is so a short message is not contained in an oversize form and a large message is ... | I have solved the issue I was having. it was a timing one.
the problem was I was writing content to the webbrowser control. And then attempting to read the width and height. but the control hadn't rendered and so I was not getting those parameters.
I realised this early in the piece so I instead put the resize code in ... |
2,304,608 | 2,304,771 | Reading socket reply in loop | I have:
char buf[320];
read(soc, buf, sizeof(buf));
//print buf;
However, sometimes the reply is much bigger then 320 characters, so I'm trying to run the read in a loop to avoid taking up too much memory space. I tried read(soc, buf, sizeof(buf)) but that only prints the same first x characters over again. How would... | Change your loop to something like:
int numread;
while(1) {
if ((numread = read(soc, buf, sizeof(buf) - 1)) == -1) {
perror("read");
exit(1);
}
if (numread == 0)
break;
buf[numread] = '\0';
printf("Reply: %s\n", buf);
}
for the reasons Nikola states.
|
2,304,634 | 2,304,651 | Why do we need a Unit Vector (in other words, why do we need to normalize vectors)? | I am reading a book on game AI.
One of the terms that is being used is to normalize a vector which is to turn a vector into a unit. To do so you must divide each dimension x, y and z by its magnitude.
We must turn vector into a unit before we do anything with it. Why?
And could anyone give some scenarios where we mu... | You don't have to normalize vectors, but it makes a lot of equations a little simpler when you do. It could also make API's smaller: any form of standardization has the potential to reduce the number of functions necessary.
Here's a simple example. Suppose you want to find the angle between two vectors u and v. If th... |
2,304,673 | 2,304,682 | Are destructors not meant to be called when returning that object (not as a pointer)? | I have a function:
static Bwah boo(){
Bwah bwah;
return bwah;
}
And a main function:
int main(){
Bwah boo = Assigner::boo();
cout << "got here.." << endl;
}
The destructor to Bwah is only called once, after the "got here" print.
Is this guaranteed or is this a compiler optimization?
| This is an optimization called Return Value Optimization (RVO). It is a common optimization, but you can't rely on it.
Here are two really excellent links for learning more:
First, a really detailed article about pass by value, rvalue semantics, the return value optimization, and rvalue references and the move constru... |
2,304,729 | 2,316,049 | How do I declare an array created using malloc to be volatile in c++ | I presume that the following will give me 10 volatile ints
volatile int foo[10];
However, I don't think the following will do the same thing.
volatile int* foo;
foo = malloc(sizeof(int)*10);
Please correct me if I am wrong about this and how I can have a volatile array of items using malloc.
Thanks.
| int volatile * foo;
read from right to left "foo is a pointer to a volatile int"
so whatever int you access through foo, the int will be volatile.
P.S.
int * volatile foo; // "foo is a volatile pointer to an int"
!=
volatile int * foo; // foo is a pointer to an int, volatile
Meaning foo is volatile. The second case... |
2,304,732 | 36,835,959 | How do I specify an integer literal of type unsigned char in C++? | I can specify an integer literal of type unsigned long as follows:
const unsigned long example = 9UL;
How do I do likewise for an unsigned char?
const unsigned char example = 9U?;
This is needed to avoid compiler warning:
unsigned char example2 = 0;
...
min(9U?, example2);
I'm hoping to avoid the verbose workaround ... | C++11 introduced user defined literals. It can be used like this:
inline constexpr unsigned char operator "" _uchar( unsigned long long arg ) noexcept
{
return static_cast< unsigned char >( arg );
}
unsigned char answer()
{
return 42;
}
int main()
{
std::cout << std::min( 42, answer() ); // Compile... |
2,304,834 | 2,307,639 | getting the right compiler for C++ | I am trying to learn c++ but most of the tutorials and books I have read or looked up teaches you this...
(I am assuming like most tutorials, they are teaching in the beginning to code either in win32 console or CLR console. In either case the following does not work.)
#include <iostream>
int main( )
{
std::cout <... | A minor point, which I don't see elsewhere in the answers: When using precompiled headers, such as your stdafx.h, you need to include them first. Change it to:
#include "stdafx.h"
#include <iostream>
and that should fix the errors about it.
Alternatively, it may be easier to simply switch off precompiled headers: Proj... |
2,304,989 | 2,305,005 | error: ‘traits’ is not a template - C++ | I am having a very weird issue with templates. Getting an error error: ‘traits’ is not a template. I couldn't reproduce the issue on a sample test project. But it happens on my project (which is bigger than I can post here).
Anyway, following are the files and usages I have. Anyone have any idea about when this error o... | Syntax for template specialization is... not pleasant.
I believe your error can be fixed by replacing struct traits<U> by struct traits (but leave struct traits<U*> as-is!).
But look on the bright side! At least you aren't doing partial specialization over function types:
// Partial class specialization for
// function... |
2,305,009 | 2,305,129 | How can I find the largest item in a linked list recursively given the head node? | int findLargest (ListNode *p)
// --------------------------------------------------------------------------
// Preconditions: list head pointer is passed as a parameter.
// Postconditions: returns the largest value in the linked list.
// --------------------------------------------------------------------------
{
i... | This is definitely feasible, although I agree that recursion is not the best solution to solve this problem. In this case, non-recursive code would be easier to read (recursion), faster (overhead of function call), and more memory efficient (obviously more stack frames).
Each recursive call returns the greater of eithe... |
2,305,014 | 2,305,037 | What are Iterators, C++? | What are Iterators in C++?
| Iterators are a way of traversing a collection of objects. Typically, they allow you to access an STL (Standard Template Library) container sequentially in ways similar to accessing a classical C array with a pointer. To access an object through an iterator, you dereference it like a C pointer. To access the next ob... |
2,305,044 | 2,305,132 | A question about strftime | The question is simple "Say we have an integer 1 <= n <= 12,How to use strftime to display January for '1',February for '2',March for '3' and so on ... ?"
| #include <stdio.h>
#include <time.h>
size_t monthName( char* buf, size_t size, int month)
{
struct tm t = {0};
t.tm_mon = month - 1; // turn month 1..12 to 0..11 as `struct tm` wants
return strftime( buf, size, "%B", &t);
}
int main(int argc, char* argv[])
{
char buf[10];
monthName( buf, si... |
2,305,178 | 2,305,383 | Directx9 Index Buffers & Multiple Streams | Im trying to write up a 3DS Loader, which has an OpenGL rendering implementation for use in my generic rendering system.
The problem here is I have vertices indexed to one array, and texture coordinates indexed to another. I dont want to generate a new set of indexes and original vertices by checking each vertexes comb... | The thing is as far as the graphics card is concerned if 2 vertices have the same position and different tex coordinates (or different any vertex element) then they are different vertices. They will be stored on the card with the position/tex coord duplicated whatever you do under OpenGL (The driver will just expand t... |
2,305,299 | 2,305,354 | Draw sound wave with possibility to zoom in/out | I'm writing a sound editor for my graduation. I'm using BASS to extract samples from MP3, WAV, OGG etc files and add DSP effects like echo, flanger etc. Simply speaching I made my framework that apply an effect from position1 to position2, cut/paste management.
Now my problem is that I want to create a control similar ... | By Zoom, I presume you mean horizontal zoom rather than vertical. The way audio editors do this is to scan the wavform breaking it up into time windows where each pixel in X represents some number of samples. It can be a fractional number, but you can get away with dis-allowing fractional zoom ratios without annoying... |
2,305,480 | 2,305,512 | Why can't I read and append with std::fstream on Mac OS X? | Consider the following C++ program, which takes a file and prints each line. It's a slice of a larger program where I later append to the file, based on what I see.
#include <fstream>
using std::fstream;
#include <iostream>
#include <string>
using std::string;
int main()
{
fstream file("file.txt", fstream::in | fstre... | When you say:
fstream file("file.txt", fstream::in | fstream::out | fstream::app);
you open the file in append mode - i.e. at the end. Just open it in read mode:
fstream file("file.txt", fstream::in );
or use an ifstream:
ifstream file("file.txt" );
And of course as Earwicker suggests, you should always test that th... |
2,305,652 | 2,305,712 | Pollard rho integer factorization | I am trying to implement Pollard Rho integer factorization in C/C++.Google gives me a Java implementation of the problem here.
I don't know Java that well,so what I came up with this.My implemenation in C++ works for most cases but not in few like the one "9999", I used there.
I am aware that C++ didn't have Biginteger... | The problem's right here:
#define abs(x) (x>0)?(x):(-x)
You're missing some parentheses in your abs macro. Try:
#define abs(x) ((x)>0 ? (x) : -(x))
instead. (Consider what happens when abs(x-xx) is expanded in the case x-xx <= 0.)
Also, why does your gcd function return an int rather than a BigInteger?
You should a... |
2,305,767 | 2,305,850 | Converting sets of integers into ranges | What's the most idiomatic way to convert a set of integers into a set of ranges?
E.g. given the set {0, 1, 2, 3, 4, 7, 8, 9, 11} I want to get { {0,4}, {7,9}, {11,11} }.
Let's say we are converting from std::set<int> into std::vector<std::pair<int, int>>.
I treat Ranges as inclusive on both sides, since it's more con... | I don't think there's anything in the STL or Boost that does this.
One thing you can do is to make your algorithm a little bit more general:
template<class InputIterator, class OutputIterator>
void setToRanges(InputIterator first, InputIterator last, OutputIterator dest)
{
typedef std::iterator_traits<InputIterator... |
2,305,777 | 2,305,784 | Constructor in class with inheritance | I'm having some problems with inheritance and constructors in C++. What I've got is a class VirtualMotor which inherits Motor (is that the correct way to say it?). The class VirtualMotor should have it's own constructor, but I'm doing something wrong when I create it and the compiler gives me an error (se below). My so... | You've declared a default constructor for the class Motor in Motor.h (Motor(); immediately below public:), but you haven't given it a definition in Motor.cpp.
|
2,306,011 | 2,307,014 | Implementation of True Size display | I have an MFC application displaying images where I need to display the image in true-size i.e. the image should be rendered such that physical length of the object captured on the image should be same as the displayed length. For example, if I captured a object of 5 cm length the image should be displayed such that if... | The proper way would be calling GetDeviceCaps with LOGPIXELSX and LOGPIXELSY. For a screen device context, however, it is very likely that the value will simply be set to 96 (it is set by the user in a control panel). The function works fine for printer DCs.
|
2,306,307 | 2,306,385 | C++: How to access a class function inside another class? | I am learning how to work with std::vector and want to access its values and functions. I have a vector object inside another object called spectrum. Now when I try to determine the capacity of the vector using .capacity it works fine if I just declare the vector. But when I declare the vector inside another object, I ... | The line vector<float> band(max_oct); doesn't do what you think it does.
It defines an automatic variable called band in the scope of the Spectrum constructor. It doesn't touch the member variable also called band: in fact it "hides" it, so that any later references to band in the constructor refer to the automatic var... |
2,306,345 | 2,306,393 | function static binding in C++ | I am asking about the static binding of the function in C++. What's the data type conversion rules for the function binding.
Suppose we have
void func(int x);
void func(long x);
void func(float x);
void func(double x);
void func(char x);
and I have one function in main
func(1)
I know the function func(int x) will be... |
Is it always the best match?
Yes: 1 is an int. If an appropriate overload exists, it will be taken since this minimizes the number of necessary implicit conversions (none).
Does the order of declaration matter?
No. However, it matters whether a function has been declared before the call is made. If the function is ... |
2,306,350 | 2,306,371 | what will happen to inline functions inside virtual functions? | What will happen if I use a inline function inside a virtual function? I'm confused with questions like
http://www.parashift.com/c++-faq-lite/value-vs-ref-semantics.html#faq-31.6
I can understand it, but is that mean, it will non-sense to use (call) inline functions inside virtual functions (please assume that it is c... | It doesn't matter whether foo is virtual or not. It only matters whether doInlineJob is virtual. It's not, so it can be inlined without a problem.
|
2,306,432 | 2,306,635 | In Qt, how do I query the state of a QMutex or a QReadWriteLock? | I'm using a QReadWriteLock in my application to guard access to a resource object.
I'm using QReadLocks and QWriteLocks where I can, but sometimes I need a "long-lived" lock that crosses function boundaries. So sometimes I need to be able to query the state of the QReadWriteLock (or QMutex, same thing in this situation... | Untested code,
But this should be possible to do, if Qt Doc is correct (though it's a little short about when tryLock() returns true/false)
QMutex m;
bool queryMutexState(){
//static QMutex lock; if you call this frequent, you may need this "protector"
lock.lock();
bool b(m.tryLock());
if (b)
m.unlock();
//lock.unlock... |
2,306,538 | 2,306,557 | C++: How to make constructor for multidimensional vector? | I want to create two and three dimensional vectors using a constructor in a class. However, I do not know how for multidimensional vectors.
One dimensional works:
class One{
public:
vector < float > myvector;
One(int length) : myvector(length){}
};
Two dimensional does not work:
class Two{
pu... | For the twodimensional case, it should be:
Two(int length, int width) : myvector(length, std::vector<float>(width)) {}
I’ll let you figure out the third case yourself.
|
2,306,587 | 2,307,021 | "as if" in language standards | What is the exact meaning of the phrase "as if" in the standard and how does it work when a user can modify individual parts of the behavior.
The question is in regards to the C++ standard when talking about the nothrow version of operator new. 18.4.1.1/7 reads (my emphasis):
This nothrow version of operator new retu... | From 1.9 "Program execution:
conforming implementations are required to emulate (only) the observable behavior of the abstract machine
and in an informational footnote:
This provision is sometimes called the “as-if” rule, because an implementation is free to disregard any requirement of this International Standard a... |
2,306,645 | 2,306,705 | Using boost::optional with constant types - C++ | I have a container class which uses boost::optional to hold the value. Here is the code looks like,
template<typename T>
struct traits
{
typedef T value_type;
typedef T& reference;
};
template<typename T>
struct traits<const T>
{
typedef const T value_type;
typedef const T& reference;
};
template<ty... | The problem is not with boost::optional, but with the logic of what you're trying to do. First you create a container of const, and then you try to modify what's contained. I would be surprised if that worked.
I think you should probably do what standard containers (like vector) do and forbid non-copyable template argu... |
2,306,972 | 2,307,038 | Is there any way to decompile Linux .so? | Is there any way to decompile Linux .so?
| There are decompilers, but a decompiler might not emit code in the same language that the original program was written in.
There are also disassemblers, which will reassemble the machine code into assembly.
The Decompilation Wiki may be a good source of additional information.
|
2,307,062 | 2,307,416 | Drag and Drop like Winspector Spy | I was wondering if anybody could give insight on how to implement the window selector in Winspector Spy. Basically, I would want to provide a panel that I could mouse down on, drag over to another processes window (or sub window) and get something like the HWND out of it. Ideally, I would do this in C#, but if it's o... | You don't normally get mouse messages when the mouse isn't over your window. But you need to in order to do drag and drop operations. So, Windows provides a mechanism called mouse capture. To prevent mouse capture from being abused, you can only capture the mouse on a button down message. Once you have capture, you ... |
2,307,146 | 2,307,215 | Stack Overflow Error With This Recursive Program? - C++ | I'm a programming student in my first C++ class, and recently we were given an assignment to implement a recursive program that finds the first occurrence of a given substring in a given string.
For example:
int StringIndex("Mississippi", "sip"); // this would return 6
The hint we are given is to use a recursive helpe... | When writing recursive functions you should always keep two things in mind: you need stop conditions which end the recursion and you have to get closer to a stop condition with each function call. If you fail to check stop conditions or if your function doesn't get closer to a stop condition during each call, you'll ru... |
2,307,251 | 2,307,265 | How can I concisely initialize a safe collection in C++? |
Possible Duplicate:
C++: Easiest way to initialize an STL vector with hardcoded elements
I'm learning C++ right now, and I'm looking for a way to quickly and easily initialize a "safe" collection (like a vector) with different values for each element. I'm accustomed to Python's concise list/tuple initializations, an... | Look into Boost.Assign, particularly list_of. It allows you to initialize a collection using code such as:
const vector<int> primes = list_of(2)(3)(5)(7)(11);
|
2,307,395 | 2,307,413 | How to print string C++ mfc | I created project using VS2008 wizard SDI > CView
How can i print some text from Cstring to my main window CView
for example in dialog window with list box i use smth like this m_ListBox1.AddString((LPCTSTR)s);
| To print it in the view (without any controls or anything like that), you can use something like pDC->Textout() or pDC->DrawText() inside your view class' OnDraw() function. Note that by default the pDC parameter has its name commented out -- you'll need to un-comment it before you can use it.
|
2,307,460 | 2,307,526 | Reading variable length user input in C++ | How do I read in a variable number of characters? The user can input a positive or negative number that is too big to be stored in an integer. I am then checking to make sure the char is a number and storing it in an array of ints (although that will probably be changed to a short since I only need to be able to store ... | If you wish to read digits, you need to do it a character at a time. E.g.
char ch;
while (std::cin.get(ch) && ch >= '0' && ch <= '9') {
// You have a digit to process (maybe you want to push_back it into a vector)
}
Notice that you need to use ch - '0' to get the value of the digit because ch contains the characte... |
2,307,534 | 2,307,580 | Enable AntiAliasing in Direct3D9 (MultiSample Render Target) | I am trying to enable AA in a D3D9 application, but am not sure how to set up the surfaces correctly. So far, I have:
IDirect3DDevice9* m_pd3dDevice;
IDirect3DSurface9* screen;
IDirect3DSurface9* msaasurf;
D3DPRESENT_PARAMETERS m_presentationParameters;
Initialization:
m_presentationParameters.Windowed = TRUE;
m_prese... | You don't need the extra surface, you can render directly to the multisampled backbuffer. For me, the only reason to use StretchRect() like this is to get a non-multisampled copy of the scene for use with postprocessing (because multisampled render targets are bad textures, so you need the scene data in a resolved text... |
2,307,621 | 2,330,194 | Does getting random SIGTRAP signals (in MinGW-gdb) is a sign of memory corruption? | I wrote my own reference counted memory manager c++ (for fun) and I'm sure it isn't perfect ;) . And now when I'm trying to use it I got random SIGTRAP signals. If I comment out every line which are in connection with that memory manager everything runs fine. Getting SIGTRAP-s instead of SIGSEGV is quite strange.
I kno... | After searching on Google I realized that those sigtraps are same as those warnings you get in MSVC++ saying "Windows has triggered a breakpoint in xxxx.exe. This may be due to a corruption of the heap, and indicates a bug blahblahblah"...
So it seems yes, unexpected sigtraps can indicate memory corrupction (quite stra... |
2,307,780 | 2,307,864 | C++ Beginner's question on input/output text files.? | If I have an input text with the only thing written of "A" and I want a series of code that will allow me to generate the next ASCII set (B), how would I do so?
#include "stdafx.h"
int _tmain(int argc, _TCHAR* argv[])
{
return 0;
}
#include iostream>
#include fstream>
#include iomanip>
#include string>
using na... | Instead of declaring character as a string, declare it as a char. string refers to std::string, a high-level object for storing multiple characters. char is a low-level native type which stores exactly 1 character.
char character;
infile >> character;
outfile << "next after " << character << " is " << char(character+1)... |
2,307,815 | 2,308,001 | Segmentation Fault when outputting in C++ | I am trying to print out an array of integers. I am getting a seg fault when I try to print as below. If I uncomment the "In for loop" it will print everything except the last item of the array and it still has a seg fault. When I uncomment both of the comments (or just the "done with for loop") everything prints fine.... | You forgot the last line in ostream& operator<<(ostream &out, const LargeInt &l):
return out;
With this line it works perfectly.
|
2,307,884 | 2,307,889 | C++ Linker Error involving operator overload function | I have a List of type Node. I want to set a temporary Node equal to the Node at the front of the List, as follows:
class Node
{
public:
Node();
Node& operator = (const Node& n);
};
but I keep getting a Linker Error:
Linking...
main.obj : error LNK2019: unresolved external symbol "public: class Node ... | You only showed the declaration of operator=, not the definition. Either you didn't supply a definition or the linker can't find it.
Well, I should say: The linker definitely can't find the definition for operator=. Either that's because you forgot to supply one or because your project/Makefile is set up incorrectly.
|
2,307,895 | 2,307,914 | Force initialization of singleton in c++ before main() | I am using singletons as follows:
// Foo.hpp
class Foo {
static Foo* instance() {
static Foo* foo = new Foo();
return foo;
}
}
Now, my singleton is initialized the first time Foo::instance() is called. I want to make sure this is before main executes (my code is multi threaded, I want all singletons initia... | Your usage of singletons indicates interdependencies between them. Is that the case? Also, you shouldn't allocate it on the heap; it will never be be destroyed.
class Foo {
static Foo& instance() {
static Foo foo; // no pointer needed
return foo;
}
};
Anyway, the answer you ask for is to add such a depende... |
2,307,933 | 2,307,995 | C++ struct alignment and STL vectors | I have a legacy data structure that's 672 bytes long. These structs are stored in a file, sequentially, and I need to read them in.
While I can read them in one-by-one, it would be nice to do this:
// I know in advance how many structs to read in
vector<MyStruct> bunchOfStructs;
bunchOfStructs.resize(numberOfStructs);
... | The standard requires you to be able to create an array of a struct type. When you do so, the array is required to be contiguous. That means, whatever size is allocated for the struct, it has to be one that allows you to create an array of them. To ensure that, the compiler can allocate extra space inside the structure... |
2,307,965 | 2,307,989 | LibGD library is not working: crash when saving image | I've been seeking for JPG saving library for long time for c++, but i cant seem to get anything to work. Now i am trying use LibGD:
What im doing wrong ? It seems to work, but the saving crashes. Code:
...
#pragma comment(lib, "bgd.lib")
#include <gd/gd.h>
...
void save_test(){
gdImagePtr im;
FILE *jpegout;... | Check im and jpegout before you try and use them to make sure they were both allocated.
[Edit] It would be better to split assigning the file handle from the test for it's validity. Have you tried the libgd example?
[Edit2] I downloaded the same source etc, set up a project in VS2008 and get the exact same problem. You... |
2,308,026 | 2,308,177 | Which has been the most reliable, fastest Windows C++ profiler that you have used? | I need to profile a real time C++ app on Windows. Most of the available profilers are either terribly expensive, total overkill, or both. I don't need any .NET stuff. Since it is a real time app, I need the profiler to be as fast as possible. It would be excellent if it integrated in some way with Visual Studio 2005/20... | When I have to profile realtime code, I think the only solution is something hand-rolled. You don't want too much coverage or you end up slowing the code down, but with a small data set, you need to be very focused, essentially picking each point by hand.
So I wrote a header file several years ago that defines some m... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.