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 |
|---|---|---|---|---|
640,874 | 644,136 | How do draw to a texture in OpenGL | Now that my OpenGL application is getting larger and more complex, I am noticing that it's also getting a little slow on very low-end systems such as Netbooks. In Java, I am able to get around this by drawing to a BufferedImage then drawing that to the screen and updating the cached render every one in a while. How wou... | Hey there, thought I'd give you some insight in to this.
There's essentially two ways to do it.
Frame Buffer Objects (FBOs) for more modern hardware, and the back buffer for a fall back.
The article from one of the previous posters is a good article to follow on it, and there's plent of tutorials on google for FBOs.
I... |
640,983 | 641,008 | Detect newline byte from filestream | I'm trying to collect information from a textfile which contains names of organisations (without spaces) and floating integers. I want to store this information in an array structure.
The problem I'm having so far is collecting the information. Here is a sample of the textfile:
CBA 12.3 4.5 7.5 2.9 ... | char byte = ins.peek();
Or
if(ins.peek() == '\n') break;
(Edit): You'll want to also check for an eof after your peek(), because some files may not have a ending newline.
I'd like to point out that you might want to consider using a vector<callCentre> instead of a static array. If your input file length exceeds the c... |
641,043 | 641,056 | Pointer problems with overloading in C++? | Pointers present some special problems for overload resolution.
Say for example,
void f(int* x) { ... }
void f(char* x) { ...}
int main()
{
f(0);
}
What is wrong with calling f(0)? How can I fix the function call for f(0)?
| f((int*) 0) or f((char *) 0)
But if you find yourself doing this I would take another look at your design.
|
641,050 | 1,698,298 | What tools exist for comparing C++ code to coding guidelines? | There exist tools for comparing code against a custom specified set of coding guidelines/standards for a variety of languages (rather than pure static analysis for common defects). Examples include FxCop for .Net code and CheckStyle for Java, but I was wondering what examples people know of in the C++ world.
An existi... | The full list that I managed to generate:
PRQA's QA C++
Parasoft's C++Test
MS Visual Studio Team System seems to have some functionality but it's hard to tell via their website.
GrammaTech CodeSonar
Coverity Extend
The last two provide some functionality but not particularly customisable ones:
Klocwork Insight
Ra... |
641,064 | 641,972 | what is a domain error | in c++, <stdexcept> has a base class for 'domain errors', std::domain_error. i don't understand under what circumstances i should throw a domain error in my code. all of the other exception base classes are pretty self explanatory. i'm pretty sure that std::domain_error has nothing to do with internet domain names, ... | Domain and range errors are both used when dealing with mathematical functions.
On the one hand, the domain of a function is the set of values that can be accepted by the function. For example, the domain of the root square function is the set of positive real numbers. Therefore, a domain_error exception is to be throw... |
641,089 | 641,127 | Correct value for hWnd parameter of BeginPaint? | I am trying to make a Visual C++ 2008 program that plots some data in a Window. I have read from various places the correct way to do this is to override WndProc. So I made a Windows Forms Application in Visual C++ 2008 Express Edition, and I added this code to Form1.h, but it won't compile:
public:
[System::... | If you were making a raw Win32 application then you could use those functions.
If, on the other hand, you are making a WinForms application then you need to override the OnPaint event.
Switch to the design view (The view that shows your form.)
Click on the title bar of your form
In the properties window (by default ... |
641,335 | 656,650 | How to figure out where to load program data from? | I've got a project written in C++ (with glibmm helping), and I'm using autotools to manage it. The question I have to ask is "HOW ON EARTH DO I FIGURE OUT WHERE TO LOAD STUFF FROM?". While I can find all the guides I want to on autotools, none answer this question.
For example, maps go in $DATADIR/maps (usually /usr/[l... | Jonathan Leffler answer was helpful (he provided enough info for me to apt-get source evolution and find what I needed to do), but it didn't entirely answer my question, so I'll post the complete solution here:
In configure.ac (or configure.in, whatever) I added the following lines at the end:
# Defines so we know wher... |
641,397 | 641,422 | C++ best way to define cross-file constants | I am working on a game and have an interesting question. I have some game-wide constant values that I want to implement in one file. Right now I have something like this:
constants.cpp
extern const int BEGINNING_HEALTH = 10;
extern const int BEGINNING_MANA = 5;
constants.hpp
extern const int BEGINNING_HEALTH;
extern c... | Get rid of the extern and you're set.
This code works perfectly fine in a header, because everything is "truly constant" and therefore has internal linkage:
const int BEGINNING_HEALTH = 10;
const int BEGINNING_MANA = 5;
const char BEGINNING_NAME[] = "Fred";
const char *const BEGINNING_NAME2 = "Barney";
This code canno... |
641,514 | 641,552 | Are threading issues for C/C++ "system level programmers" significantly different from those faced by Java programmers? | I'm looking for a development job and see that many listings specify that the developers must be versed in multithreading. This appears both for Java job listings, and for C++ listings that involve "system programming" on UNIX.
In the past few years I have been working with Java and using its various synchronization m... | The fundamental challenges of threading (e.g. synchronization, race conditions, inter-thread communication, resource cleanup), but Java makes thread much more manageable with garbage collection, exceptions, advanced synchronization objects, advanced debugging support with reflection.
With C++, you are much more likely ... |
641,542 | 643,787 | Why doesn't glCopyTexSubImage2D copy my square correctly? | here is the output: http://i43.tinypic.com/9a5zyx.png
if things were working the way i wanted, the colors in the left square would match the colors in the right square. thanks for any help regarding the subject
#include <gl/glfw.h>
const char* title="test";
GLuint img;
unsigned int w=64,h=64;
int screenwidth,screenhei... | Try adding 'glColor3f(1,1,1);' in your 'drawmytex' function. I suspect that your texture is modulated (multiplied) with the current color, if so, the problem is not the texture copy but the way you display it.
|
641,724 | 641,854 | Remove the common entities from two vector? | say I have vector<class1a>,vector<class1b> how to remove the common entities from both of them
I have defined ==operator for the class1 objects class1a,class1b
| The stl algorithms provide several functions to perform set operations, notably calculating the set symmetric difference, which is what you need.
Here's an example of use:
#include <algorithm>
#include <vector>
int main(int argc, char **argv) {
std::vector<int> v1;
v1.push_back(1);
v1.push_back(2);
v1... |
641,826 | 641,904 | What is __unwind$ in a linker map file | For VS2008 (C++) generated linker map files, what does the symbol "__unwind$" mean? I have a good chunk of them in the linker map file for my app.
I have a log which says a crash happens at a particular offset say 'x'. When I look at the linker map for this offset, I find this __unwind$41357 corresponding to the offset... | "Unwinding" is happens with a stack when an exception is thrown. The __ prefix indicates a compiler-generated symbol. So, based on the description, you get a crash between a throw and a catch. My assumption is that the destructors called are called from the __unwind$ functions. An inlined destructor wouldn't have its o... |
641,864 | 641,881 | Returning a pointer to a vector element in c++ | I have a vector of myObjects in global scope.
I have a method which uses a std::vector<myObject>::const_iterator to traverse the vector, and doing some comparisons to find a specific element.
Once I have found the required element, I want to be able to return a pointer to it (the vector exists in global scope).
If I re... | Return the address of the thing pointed to by the iterator:
&(*iterator)
Edit: To clear up some confusion:
vector <int> vec; // a global vector of ints
void f() {
vec.push_back( 1 ); // add to the global vector
vector <int>::iterator it = vec.begin();
* it = 2; // change what was 1 t... |
641,935 | 733,928 | WASAPI prevents Windows automatic suspend? | First time poster, be gentle ;-)
I'm writing an audio app (in C++) which runs as a Windows service, uses WASAPI to take samples from the line in jack, and does some processing on it.
Something I've noticed is that when my app is "recording", Windows won't automatically suspend or hibernate.
I've registered for power e... | Many thanks to Larry for confirming this behaviour is by design and not me doing something silly.
To work around this issue I used the Win32 CallNtPowerInformation() API to retrieve the system idle timer:
SYSTEM_POWER_INFORMATION spi = {0};
NTSTATUS status = CallNtPowerInformation(SystemPowerInformation, NULL, 0,
... |
642,066 | 642,580 | g++ undefined reference to constructor | I'm compiling and linking a cpp file against a pre-compiled library, and I'm getting an "undefined reference" error.
Firstly, this is the command (the library in question is quicknet3, the program I'm compiling is trapper):
g++ -w -g -I. -g -O3 -pipe -Wall -I/home/install/x86_64/include/quicknet3 -L/home/install/x86_6... | A quick workaround is to add /home/install/x86_64/lib/libquicknet3.a to g++ commandline.
I you want to investigate further, if g++ is picking another copy of libquicknet3, you can pass -v to g++ so it will output its searching paths.
|
642,082 | 657,317 | How to embed Windows Form in unmanaged ATL GUI? | I have a Windows form user control that is made COM visible. Now I want to embed that control into an ATL dialog GUI.
The ATL project (unmanaged C++) shall only get the progID of the winform and dynamically create and embed it at runtime.
Is this possible and if so, how do I do it?
| I figured out a way to get it to work.
The following code is using a CWnd called m_Control that is made to host a winform via a little documented version of CreateControl. Seems to work fine so far. If anyone sees any drawbacks, please comment or respond.
AfxEnableControlContainer();
Microsoft::VisualC::MFC::CControlCr... |
642,213 | 642,258 | How to implement a natural sort algorithm in c++? | I'm sorting strings that are comprised of text and numbers.
I want the sort to sort the number parts as numbers, not alphanumeric.
For example I want: abc1def, ..., abc9def, abc10def
instead of: abc10def, abc1def, ..., abc9def
Does anyone know an algorithm for this (in particular in c++)
Thanks
| I asked this exact question (although in Java) and got pointed to http://www.davekoelle.com/alphanum.html which has an algorithm and implementations of it in many languages.
|
642,229 | 642,447 | Why do I need to use typedef typename in g++ but not VS? | It had been a while since GCC caught me with this one, but it just happened today. But I've never understood why GCC requires typedef typename within templates, while VS and I guess ICC don't. Is the typedef typename thing a "bug" or an overstrict standard, or something that is left up to the compiler writers?
For thos... | The typename is required by the standard. Template compilation requires a two step verification. During the first pass the compiler must verify the template syntax without actually supplying the type substitutions. In this step, std::map::iterator is assumed to be a value. If it does denote a type, the typename keyword... |
642,348 | 642,378 | Does GetSystemInfo give you the total number of virtual CPUs (i.e. hyper-threaded)? | GetSystemInfo will give you the number of physical CPUs / cores, but I would like to know the total number of virtual CPUs. I.e. on the new Nahelam chips, they have 4 cores, but appear as 8 cpus.
If GetSystemInfo doesn't give this information, what API do I need (I've seen a function for getting number of logical proce... | GetLogicalProcessorInformation Function
( Windows Vista, Windows XP Professional x64 Edition, Windows XP with SP3)
|
642,539 | 642,552 | How does one avoid accidentally redeclaring global constants in C++? | I have a template matrix class class defined in a header called "Matrix.h".
Certain matrices are used repeatedly in my program. I thought that I would define these in the "Matrix.h" header file, like so:
const Matrix<GLfloat> B_SPLINE_TO_BEZIER_MATRIX(4, 4, values);
When I do this g++ complains that I redefined the co... | If you don't want to split it between a header and implementation file,
Declare your constant static (or declare it in anonymous namespace) to make definition private. Linker will not complain, but it will result in multiple private copies across compilation units.
static Matrix<GLfloat> B_SPLINE_TO_BEZIER_MATRIX(4, 4... |
642,618 | 642,665 | Compile error using cl.exe (Visual Studio 2008) for this cpp code | I'm getting compile error in this code
#include<iostream>
#include<cstdio>
#include<string>
using namespace std;
void main(int argc,char *argv[])
{
int i;
for(i = 0;i<10;i++)
fprintf(cout,"%d\n",i);
fprintf(cout,"abc:\n");
string s;
cin>>s;
... | std::fprintf(stdout, )
|
643,023 | 643,063 | protected inheritance vs. public inheritance and OO design | When do you use each inheritance?
class Base{};
class Derived: protected Base{};
class Derived2: public Base{};
My case:
I have class called Snapshot which only contains GetXXX methods. It is a light-weight classed used to store current state of the Value class. I also use it for recovery, keeping instances of this c... | Generally speaking I would use public inheritance, if I want to implement a specific interface, e.g. if my class is to be accessed thrugh a specific contract.
Protected inheritance could be used, if you just want to reuse the functionality implemented in the parent.
I would make Snapshot a pure virtual class, e.g. just... |
643,202 | 643,228 | Send C++ string to C# string. Interop | I am new to inter process communication and need some help. I want to be able to send a string from a C++ program to a C# program. My problem is that the resultant string is gibberish. Here is my code:
Sending program (C++):
void transmitState(char* myStr)
{
HWND hWnd = ::FindWindow(NULL, _T("myApp v.1.0"));
... | char* in C++ is ANSI character string (usually one byte per character), char* in C# is Unicode character string (like WCHAR* - two bytes per character).
You in fact reinterpret_cast from char* to WCHAR*. This won't work. Use MultiByteToWideChar() on C++ side to convert.
|
643,317 | 643,337 | Virtual behavior by storing pointers to member functions | Why is virtual behavior being prevented?
class MyClass
{
//........
virtual double GetX();
virtual double GetSomethingElse();
virtual double GetT();
virtual double GetRR();
//........
};
class Processor
{
private:
typedef double (MyClass::*MemF... | This line here:
void Processor::Process(MyClass ms, const std::string& key)
Try replacing it with
void Processor::Process(MyClass &ms, const std::string& key)
What is happening is called slicing, even though you may have passed in a sub-class of MyClass, when you call Process, a new MyClass object is made on the sta... |
643,617 | 643,668 | Passing a list of numbers to a function in C++ without building array first? | I'm trying to build a function that accepts an array in the following manner:
int inCommon = findCommon({54,56,2,10}, 4);
int findCommon(int nums[], int len){
for(int i=0; i<len; i++) cout<<nums[i]<<endl;
return 1;
}
Note, that's not actually what my function does, but I do loop through the array. I'm just tryi... | This is not possible at the time. However, in the next C++ standard C++0x, this will be done using initalizer lists:
int findCommon(std::initializer_list<int> nums)
{
std::initializer_list<int>::iterator it;
for (it = nums.begin() ; it != nums.end() ; ++it)
{
std::cout << *it << std::endl;
}
... |
643,738 | 643,779 | What does `vcall'{0,{flat}}' signify in below example? | I am not sure if the question is already addressed. I was checking the one of the Stack overflow function and got this doubt.
Lets check the code first:
#include <string>
#include <map>
#include <iostream.h>
class MyClass
{
public:
virtual int Func()
{
return 0;
}
int Func2()
{
r... | There is a pretty thorough explanation of what thunk means over on WikiPedia
http://en.wikipedia.org/wiki/Thunk
The gist of is thunk is the mechanism by which the C++ virtual table is accessed at runtime. It is setup to call the appropriate virtual function for the runtime type of the object.
As to what the vcall{0,... |
644,397 | 644,427 | c++ class with template cannot find its constructor | I have a problem I don't really understand. I have a class Node.
template<class T>
class node {
protected:
T _data;
public:
node(T data);
};
This is in "node.h" file. In "node.cpp" file, there is this constructor:
#include "node.h"
template<class T>
node<T>::node (T data) {
_data = data;
}
While the c... | The problem is that templates aren't classes - you don't normally write them in two separate files. Template classes are code that the compiler uses to generate classes. As such, your implementation code needs to effectively be inline, i.e., in the header as you discovered.
For a fuller explanation of why it has to b... |
644,461 | 644,475 | C++ - Constructor overloading - private and public | Can you tell me why the following code is giving me the following error - call of overloaded "C(int)" is ambiguous
I would think that since C(char x) is private, only the C(float) ctor is visible from outside and that should be called by converting int to float.
But that's not the case.
class C
{
C(char x)
{
... | This is discussed in "Effective C++" by Scott Meyer. The reason this is ambiguous is that they wanted to ensure that merely changing the visibility of a member wouldn't change the meaning of already-existing code elsewhere.
Otherwise, suppose your C class was in a header somewhere. If you had a private C(int) member, t... |
644,629 | 644,639 | Base enum class inheritance | Is there a pattern where I can inherit enum from another enum in C++??
Something like that:
enum eBase
{
one=1, two, three
};
enum eDerived: public eBase
{
four=4, five, six
};
| Not possible. There is no inheritance with enums.
You can instead use classes with named const ints.
Example:
class Colors
{
public:
static const int RED = 1;
static const int GREEN = 2;
};
class RGB : public Colors
{
static const int BLUE = 10;
};
class FourColors : public Colors
{
public:
static const in... |
644,673 | 644,693 | Is it more efficient to copy a vector by reserving and copying, or by creating and swapping? | I am trying to efficiently make a copy of a vector. I see two possible approaches:
std::vector<int> copyVecFast1(const std::vector<int>& original)
{
std::vector<int> newVec;
newVec.reserve(original.size());
std::copy(original.begin(), original.end(), std::back_inserter(newVec));
return newVec;
}
std::vector<in... | Your second example does not work if you send the argument by reference. Did you mean
void copyVecFast(vec<int> original) // no reference
{
vector<int> new_;
new_.swap(original);
}
That would work, but an easier way is
vector<int> new_(original);
|
644,889 | 645,083 | What is the best Evaluation Kit for Learning Embedded C/C++ Development? | I am trying to improve my embedded C/C++ development on ARM architecture. I have recently moved from 68K development to ARM and wanted to use some of my spare time to dig into the platform and learn the best practices especially on developing for mobile platforms.
Preferably 32bit architecture will be helpful with supp... | ST Micro has a very attractively priced (and packaged too) kit for their ARM Cortex-M3 based STM32 line. MSRP runs about US$35 for the STM32-PRIMER with 128x128 color LCD, MEMS accelerometer, push button, LEDs, USB, and some spare GPIOs all in a package that includes a battery and USB to JTAG debug connection. A GCC to... |
645,046 | 645,058 | C++ Pointers to Member Functions Inheritance | I have a need to be able to have a super class execute callbacks defined by a class that inherits from it. I am relatively new to C++ and from what I can tell it looks like the subject of member-function-pointers is a very murky area.
I have seen answers to questions and random blog posts that discuss all sorts of thin... | If you can use boost libraries, I would suggest you use boost::function for the task at hand.
class A {
public:
void doSomething( boost::function< void ( int ) > callback )
{
callback( 5 );
}
};
Then any inheriting (or external class) can use boost::bind do make a call:
class B {
public:
void my_meth... |
645,062 | 645,095 | Visual Studio projects with multiple folders | Is there an easy way to use multiple folders in a project with Visual Studio? It has "filters" which look like folders, but it would be really nice to be able to make folders and insert files in them inside VS. Is there an add-in or secret option to enable this behavior?
| With VC++, the folders do not correspond directly with what's on your file system. They are simply used to help you organize your project in an independent manner.
The reason they have this design decision is because with C++ you typically have many include and source directories.
More on Filters:
At the top of your... |
645,165 | 645,171 | #include directive: relative to where? | I have looked in The C++ Programming Language to try to find the answer to this. When I #include "my_dir/my_header.hpp" in a header, where does it look for this file? Is it relative to the header, relative to the source file that included it, or something else?
| Implementation defined. See what is the difference between #include <filename> and #include “filename”.
|
645,168 | 645,273 | How to write a std::bitset template that works on 32 and 64-bit | Consider the following code
template<unsigned int N> void foo(std::bitset<N> bs)
{ /* whatever */ }
int main()
{
bitset<8> bar;
foo(bar);
return 0;
}
g++ complains about this on 64 bit because the <8> gets interpreted as an unsigned long int, which doesn't exactly match the template. If I change the templ... | The problem isn't whether or not you write 8u or 8. The problem has to do with the type of the template parameter of your function template. Its type has to match the one used in the declaration of std::bitset. That's size_t according to the Standard (section 23.3.5)
namespace std {
template<size_t N> class bitset ... |
645,268 | 645,306 | In COM: should I call AddRef after CoCreateInstance? | Does CoCreateInstance automatically calls AddRef on the interface I'm creating or should I call it manually afterwards?
| The contract with COM is anytime you are handed an object from a function like this, such as CoCreateInstance(), QueryInterface() (which is what CoCreateInstance() ultimately calls), etc, the callee always calls AddRef() before returning, and the caller (you) always Release() when you are done.
You can use CComPtr<> to... |
645,290 | 645,298 | How to hook up LED lights in C++ without microcontroller? | I want to light up/off LEDs without a microcontroller. I'm looking to control the LEDs by writing a C++ program. but the problem im having is hooking them up is there a free way to do !!!!
I'm using Windows XP if that is relevant.
I have LEDs but I don't have a microcontroller.
Well, I found some functions but their he... | That completely depends on which hardware you have, which determines which driver you need. Back then, i got a simple led and put it into the printer LPT port. Then i could write a byte to address 0x0378h and the bits in it determined whether a pin had power or not (using linux). For windows, you need a driver that all... |
645,595 | 645,604 | How would you remove elements of a std::vector based on some property of the elements? | If for instance you have a std::vector<MyClass>, where MyClass has a public method: bool isTiredOfLife(), how do you remove the elements that return true?
| I prefer remove_if
v.erase(remove_if(v.begin(), v.end(),
mem_fun_ref(&MyClass::isTiredOfLife)),
v.end());
remove_if returns an iterator pointing after the last element that's still in the sequence. erase erases everything from its first to its last argument (both iterators).
|
645,747 | 4,170,902 | Sharing precompiled headers between projects in Visual Studio | I have a solution with many Visual C++ projects, all using PCH, but some have particular compiler switches turned on for project-specific needs.
Most of these projects share the same set of headers in their respective stdafx.h (STL, boost, etc). I'm wondering if it's possible to share PCH between projects, so that inst... | Yes it is possible and I can assure you, the time savings are significant. When you compile your PCH, you have to copy the .pdb and .idb files from the project that is creating the PCH file. In my case, I have a simple two file project that is creating a PCH file. The header will be your PCH header and the source will ... |
645,778 | 645,855 | What are the advantages and disadvantages of separating declaration and definition as in C++? | In C++, declaration and definition of functions, variables and constants can be separated like so:
function someFunc();
function someFunc()
{
//Implementation.
}
In fact, in the definition of classes, this is often the case. A class is usually declared with it's members in a .h file, and these are then defined in a... | Historically this was to help the compiler. You had to give it the list of names before it used them - whether this was the actual usage, or a forward declaration (C's default funcion prototype aside).
Modern compilers for modern languages show that this is no longer a necessity, so C & C++'s (as well as Objective-C, a... |
645,888 | 645,894 | Process cannot be resumed after having been suspended | CreateProcess suspended but it can't be resumed.
Here is my code:
bool success=CreateProcess(m_Process,
NULL,
NULL,
NULL,
FALSE,
NORMAL_PRIORITY_CLASS||CREATE_SUSPENDED,
NULL,
NULL,
&suInfo,
&procInfo);
... | Remove one of the "|". This ends up as a one since it's a logical expression in your case. The constant for this is DEBUG_PROCESS, so you're debugging the child process.
|
645,994 | 646,001 | Why is 'this' a pointer and not a reference? | I was reading the answers to this question C++ pros and cons and got this doubt while reading the comments.
programmers frequently find it confusing that "this" is a pointer but not a reference. another confusion is why "hello" is not of type std::string but evaluates to a char const* (pointer) (after array to pointer... | When the language was first evolving, in early releases with real users, there were no references, only pointers. References were added when operator overloading was added, as it requires references to work consistently.
One of the uses of this is for an object to get a pointer to itself. If it was a reference, we'd ha... |
646,116 | 646,282 | Open Source & Cross Platform Multiplayer/Networking Libraries? | While raknet seems fairly interesting and really appealing from a feature-point of view, its licensing terms seem to be possibly troublesome for GPL'ed projects that may be leveraged commercially, something which is explicitly forbidden by the terms of the creative commons license.
While there's also opentnl, it doesn... | The wiki of Ogre3D provides a list of networking libraries and a short description for them.
|
646,217 | 646,222 | How to run a bash script from C++ program | Bash scripts are very useful and can save a lot of programming time. So how do you start a bash script in a C++ program? Also if you know how to make user become the super-user that would be nice also. Thanks!
| Use the system function.
system("myfile.sh"); // myfile.sh should be chmod +x
|
646,392 | 646,396 | How do perform a generic print for key type and map | With reference to this question StackoVerflow 529831, this was one of the suggested approaches
template<typename Map> typename Map::const_iterator
greatest_less(Map const& m, typename Map::key_type const& k) {
//How to print K and Map m
typename Map::const_iterator it = m.lower_bound(k);
if(it != m.begin(... | Use the << operator, making sure that << is defined for both your Map::key_type and Map::data_type types (you will know if that is not the case as the code will not compile.)
cout << k << endl;
for (typename Map::const_iterator it = m.begin(); it != m.end(); ++i) {
cout << it->first << " -> " << it->second << endl;
}... |
646,423 | 646,502 | Using a DLL with .h header in C++ | I have been given a small library, consisting of a .dll, a .h header and a .def file. I'm fairly sure the library was written in C, but possibly C++.
Is it possible for me to access the functions in the library without using the LoadLibrary/GetProcAddress/FreeLibrary method that is usually talked about. I have no .lib ... | Visual C++ has "lib" - look it up in the online help.
Use "lib /def" to make the .lib file.
|
646,427 | 646,429 | Should destructors be threadsafe? | I was going through a legacy code and found the following snippet:
MyClass::~MyClass()
{
EnterCriticalSection(&cs);
//Access Data Members, **NO Global** members are being accessed here
LeaveCriticalSection(&cs);
}
I am wondering will it help by any chance to guard the destructor ?
Consider a scenario :
1. Thr... | The destructor should not be called when the object is in use. If you're dealing with such a situation, it needs a fundamental fix. However, the destructor might want to alter some other thing (which is unrelated to the class being destructed) and it might need a critical section (e.g. like decrementing a global counte... |
646,468 | 646,478 | How to Rotate a 2D Array of Integers | I am programming a Tetris clone and in my game I store my tetromino blocks as 4x4 arrays of blocks. I now need to be able to rotate the integer positions in the arrays so that I get a rotated tetris block. I cannot simply rotate the texture because all my collision detection, etc has been designed to work with the 2D a... | If they're a 2D array, you can implement rotation by copying with different array access orders.
i.e., for a clockwise rotation, try:
int [,] newArray = new int[4,4];
for (int i=3;i>=0;--i)
{
for (int j=0;j<4;++j)
{
newArray[j,3-i] = array[i,j];
}
}
Counter-clockwise is similar.
|
646,559 | 646,563 | Two files containing definition of main() Visual Studio? | I have created a project in Visual Studio 2008 Professional Edition.
This project contains one .cpp file for each assignment like this...
[-]Source Files
\
|-- 233.cpp
|-- test.cpp
And each file contains definition of main().
Action:CTRL+F5
Error 1 error LNK2005: _main already defined in 233.obj test.obj
... | You can't have 2 functions called main() in a single project. What you should do is change the names of the functions, and then call them from a new main() function which would function as a menu.
If you make them separate projects, you can switch which one to run with Solution Properties -> Startup Project.
|
646,660 | 646,667 | Strange temporary array corruption | I am attempting to create a permutation, and I receive this strange error when I finish my problem:
Stack around the variable "temp" was corrupted
the segment of the variable is within a nested for loop:
for(int i = 0 ; i < str_length ; i++)
{
for(int j = 0 ; j < str_length ; j++)
{
char temp[1];
... | You just need to use char temp; and acces it as temp = text[i];, etc.
You're accessing a point on the stack one byte PAST temp, which is invalid. In this case, since you only want a single char, there's no need for an array at all.
|
646,673 | 646,682 | How can I get FindFirstFile to sort files | I am using the standard FindFirst and FindNext to retrieve all files in a directory
but I need the results to come back sorted ( in the same order that clicking on the name column in explorer would sort them basically )
How can I achive this
This has to be done via Win32
Thanks
| You can use the Indexing Service for this, but I would recommend just to handle the sorting yourself while using FindFirstFile.
Sorting is not possible with the FindFirstFile Win32 API. There is a slightly more advanced FindFirstFileEx, but even that does not allow sorting.
There is a Raymond Chen post on The Old New ... |
646,737 | 646,762 | Map of boost function of different types? | i was wondering if there was a way to do this in C++?
void func1(const std::string& s)
{
std::cout << s << std::endl;
}
void func2(int me)
{
std::cout << me << std::endl;
}
int main()
{
std::map<std::string, boost::function< ??? > > a_map;
a_map["func1"] = &func1;
a_map["func1"]("HELLO");
}
Is there any way to do ... | There are ways to store the functions, the problem is, in order to be able to call the function with the desired argument you'd have to know the calling signature of the function anyways, and if you have that information, you might as well use separate maps, or use a more complicated object than boost::function.
If you... |
647,074 | 647,075 | How to make Linux C++ GUI apps | What is the easiest way to make Linux C++ GUI apps? I'm using GNOME and ubuntu 8.10.
| I personally prefer QT as I prefer working with the signal/slots mechanism and just find it easy to develop applications quickly with it. Some of your other options would be wxWidgets and GTK+.
|
647,092 | 647,108 | Should a list of objects be stored on the heap or stack? | I have an object(A) which has a list composed of objects (B). The objects in the list(B) are pointers, but should the list itself be a pointer? I'm migrating from Java to C++ and still haven't gotten fully accustomed to the stack/heap. The list will not be passed outside of class A, only the elements in the list. Is it... | Bear in mind that
The list would only be on the stack if Object-A was also on the stack
Even if the list itself is not on the heap, it may allocate its storage from the heap. This is how std::list, std::vector and most C++ lists work – the reason is that stack-based elements cannot grow.
These days most stacks are ar... |
647,138 | 772,270 | How can I download a utf-8-encoded web page with libcurl, preserving the encoding? | Im trying to get libcurl to download a webpage that is encoded in UTF-8, which is working fine, except for the fact that it converts it to ASCII and screws up some of the characters. Is there an easy way to get it to keep it in UTF-8?
| libcurl doesn't translate/convert the data at all so there's actually nothing particular you need to do. Just get it.
|
647,413 | 647,424 | what is the difference in using && and || in the do...while loop? | #include<iostream>
using namespace std;
int main()
{
char again;
do
{
cout<<"you are in the while loop";
cout<<"do you want to continue looping?";
cin>>again;
} while (again != 'n' || again != 'N');
system("pause");
return 0;
}
i know something is wrong with the test ... | This is a common boolean logic question. || means "or," which means "as long as one side of this is true, then the expression is true." So when you pass an uppercase 'N' to c != 'n' || c != 'N' the program says "well, 'N' is not equal to 'n', therefore one side of the expression is true, therefore the whole expressi... |
647,648 | 647,700 | Is it better to store class constants in data members or in methods? | I recently wrote a class that renders B-spline curves. These curves are defined by a number of control points. Originally, I had intended to use eight control points, so I added a constant to the class, like so:
class Curve
{
public:
static const int CONTROL_POINT_COUNT = 8;
};
Now I want to extend this class... | Typically I favour maintaining as few couplings manually as possible.
The number of control points in the curve is, well, the number of control points in the curve. It's not an independent variable that can be set at will.
So I usually would expose a const standard container reference:
class Curve
{
private:
... |
647,704 | 647,717 | Why is getcwd() not ISO C++ compliant? | This MSDN article states that getcwd() has been deprecated and that the ISO C++ compatible _getcwd should be used instead, which raises the question: what makes getcwd() not ISO-compliant?
| Functions not specified in the standard are supposed to be prefixed by an underscore as an indication that they're vendor-specific extensions or adhere to a non-ISO standard. Thus the "compliance" here was for Microsoft to add an underscore to the name of this specific function since it's not part of the ISO standard.... |
647,705 | 647,708 | As a programmer with no CS degree, do I have to learn C++ extensively? | I'm a programmer with 2 years experience, I worked in 4 places and I really think of myself as a confident, and fluent developer.
Most of my colleagues have CS degrees, and I don't really feel any difference! However, to keep up my mind on the same stream with these guys, I studied C (read beginning C from novice to p... | For practical advancement:
From a practical sense, pick a language that suites the domain you want to work in.
There is no need to learn C nor C++ for most programming spaces. You can be a perfectly competent programmer without writing a line of code in those languages.
If however you are not happy working in the exac... |
647,796 | 648,088 | How to figure out source line number from Linker Map | For some reason I have only the linker map for an application I am debugging. There is a crash log which says crash occurred at offset "myApp.exe! + 4CA24".
From the linker map I am able to locate the method. Say this is at offset "myApp.exe! + 4BD7C".
Is there anyway to figure out the exact line in source code using... | The best you can do if you only have MAP-files is to study the EXE-file in a disassembler and compare to constructs that you recognize from the common ways the compiler generates code. These you have to learn. That means learning at least some assembler is required. This is good knowledge that will help you in the futu... |
647,967 | 647,977 | How to extend std::tr1::hash for custom types? | How do I allow the STL implementation to pick up my custom types? On MSVC, there is a class std::tr1::hash, which I can partially specialize by using
namespace std
{
namespace tr1
{
template <>
struct hash<MyType>
{ ... };
}
}
but is this the recommended way? Moreover, does th... | Yes, this will also work for GCC. I'm using it in a bigger project and it works without problems. You could also provide your own custom hashing class for the TR1 containers, but it is specified that std::tr1::hash<> is the default hashing class. Specializing it for custom types seems like the natural way to extend the... |
647,988 | 647,997 | Why can't I assign values to pointers? | After reading the faq's and everything else I can find, I'm still confused. If I have a char pointer that is initialised in this fashion:
char *s = "Hello world!"
The string is in read-only memory and I cannot change it like this:
*s = 'W';
to make "Wello world!". This I understand, but I can't, for the life of me, un... | The easiest way to modify it is to create an array for your storage, and then copy the string into it.
For example:
char buf[128];
const char *src = "Hello World";
strncpy(buf, src, 127); // one less - we always 0-terminate
buf[127] = '\0';
// you can now modify buf
buf[0] = 'W';
The reason your code doesn't work is ... |
648,138 | 648,202 | HELP VS8 Command line to IDE? | PROBLEM:
C:\>cl /LD hellomodule.c /Ic:\Python24\include c:\Python24\libs\python24.lib /link/out:hello.dll
'cl' is not recognized as an internal
or external command,
operable program or batch file.
I am using Visual Studio Prof Edi 2008.
What PATH should I set for this command to work?
How to execute above c... | You can set up the environment by using
C:\Program Files\Microsoft Visual Studio 9.0\VC\vcvarsall.bat
|
648,334 | 648,345 | Should I learn GTK+ or GTKMM? | I am a C# programmer who started using ubuntu about 2 years ago. I'm wanting to learn GUI programming in either C or C++. I don't really like mono, it tends to crash on my system. I have a basic understanding of C++. I have never worked in C, but it looks cool. Which toolkit should I learn/use? Give Pro/Cons of each. T... | Since C++ is more familiar to you, you may find GTKmm to be a better fit, since you can use idioms like RAII. Unfortunately, GTKmm is a little incomplete and is missing a few of the lesser-used parts of GTK.
GTK+ on its own, however, essentially exposes an object model similar to what you find in C++, but with only C f... |
648,380 | 648,442 | Evaluation order of new expression? | In the following code sample, do the C++ standard guarantee that '++i' is evaluated after the memory allocation (call to operator new) but before the call to X’s constructor?
new X( ++i )
| From my copy of n2798:
5.3.4 New
21 Whether the allocation function is called before evaluating the constructor arguments or after evaluating the constructor arguments but before entering the constructor is unspecified. It is also unspecified whether the arguments to a constructor are evaluated if the allocation funct... |
648,464 | 648,465 | Why does g++ compile this? | Recently, after being very tired, I wrote the following code:
GLfloat* array = new GLfloat(x * y * z);
Which, of course should have been:
GLfloat* array = new GLfloat[x * y * z];
(Note the square brackets as opposed to the parenthesis.)
As far as I know, the first form is not valid, but g++ compiled it. Sure, it spat... | GLfloat* array = new GLfloat(x * y * z);
Creates a pointer called array to an object of type GLfloat with a value of x * y * z.
|
648,545 | 648,550 | How to perform fast formatted input from a stream in C++? | The situation is: there is a file with 14 294 508 unsigned integers and 13 994 397 floating-point numbers (need to read doubles). Total file size is ~250 MB.
Using std::istream takes ~30sec. Reading the data from file to memory (just copying bytes, without formatted input) is much faster. Is there any way to improve re... | Do you need to use STL style i/o? You must check out this excellent piece of work from one of the experts. It's a specialized iostream by Dietmar Kuhl.
I hate to suggest this but take a look at the C formatted i/o routines. Also, are you reading in the whole file in one go?
|
648,619 | 648,629 | Resizing an OpenGL window causes it to fall apart | For some reason when I resize my OpenGL windows, everything falls apart. The image is distorted, the coordinates don't work, and everything simply falls apart. I am sing Glut to set it up.
//Code to setup glut
glutInitWindowSize(appWidth, appHeight);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA);
glutCreateWindow("Test... | You should not forget to hook the GLUT 'reshape' event:
glutReshapeFunc(resize);
And reset your viewport:
void resize(int w, int h)
{
glViewport(0, 0, width, height); //NEW
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0, w, h, 0);
}
A perspective projection would have to take the new aspe... |
648,647 | 648,661 | In C++, where in memory are class functions put? | I'm trying to understand what kind of memory hit I'll incur by creating a large array of objects. I know that each object - when created - will be given space in the HEAP for member variables, and I think that all the code for every function that belongs to that type of object exists in the code segment in memory - pe... | It's not necessarily true that "each object - when created - will be given space in the HEAP for member variables". Each object you create will take some nonzero space somewhere for its member variables, but where is up to how you allocate the object itself. If the object has automatic (stack) allocation, so too will... |
648,888 | 648,963 | How to pass references by value in C++? | I'm trying to create am immutable type (class) in C++,
I made it so that all methods "aka member functions" don't modify the object and return a new instance instead.
I'm running across a bunch of issues, but they all revolve around the reference types in C++.
One example is when passing parameters of the same class ty... | In Java and C#, you are not really dealing with a reference - they are more like handles or pointers. A reference in C++ is really another name for the original object, not a pointer to it (although it may be implemented with a pointer). When you assign a value to a reference, you are assigning to the object itself.... |
648,900 | 648,905 | C++ templates, undefined reference | I have a function declared like so:
template <typename T>
T read();
and defined like so:
template <typename T>
T packetreader::read() {
offset += sizeof(T);
return *(T*)(buf+offset-sizeof(T));
}
However, when I try to use it in my main() function:
packetreader reader;
reader.read<int>();
I get the followin... | You need to use the export keyword. However, I don't think G++ has proper support, so you need to include the template function's definition in the header so the translation unit can use it. This is because the <int> 'version' of the template hasn't been created, only the <typename T> 'version.'
An easy way is to #inc... |
648,917 | 648,937 | Can I use execvp() on a function defined inside my program? | I have a C++ function that I'd like to call using execvp(), due to the way my program is organized.
Is this possible?
| All of the exec variants including execvp() can only call complete programs visible in the filesystem. The good news is that if you want to call a function in your already loaded program, all you need is fork(). It will look something like this pseudo-code:
int pid = fork();
if (pid == 0) {
// Call your function he... |
648,960 | 649,071 | std::vector on VisualStudio2008 appears to be suboptimally implemented - too many copy constructor calls | I've been comparing a STL implementation of a popular XmlRpc library with an implementation that mostly avoids STL. The STL implementation is much slower - I got 47s down to 4.5s. I've diagnosed some of the reasons: it's partly due to std::string being mis-used (e.g. the author should have used "const std::string&" w... | The STL does tend to cause this sort of thing. The spec doesn't allow memcpy'ing because that doesn't work in all cases. There's a document describing EASTL, a bunch of alterations made by EA to make it more suitable for their purposes, which does have a method of declaring that a type is safe to memcpy. Unfortunately ... |
648,998 | 649,035 | Is C++ a "waste of time"? | I ran into this supposed interview of Bjarne Stroustrup, the inventor of C++.
http://artlung.com/smorgasborg/Invention_of_Cplusplus.shtml
Stroustrup: Well, it's been long enough, now, and I believe most people have figured out for themselves that C++ is a waste of time but, I must say, it's taken them a lot longer tha... | You just have to check the Stroustrup's website (the FAQ part) to find that it's wrong - a well known hoax as Judah Himango already pointed :
Did you really give an interview to IEEE?
in which you confessed that C++ was
deliberately created as an awful
language for writing unmaintainable
code to increase program... |
649,618 | 650,615 | How to Build a custom simple DNS server in C/C++ | I need to build a custom simple non-authoritative caching DNS server in C/C++. Any guidance? Links? Samples?
| There's no such thing as a "simple" cacheing DNS server, particularly if you want decent security. Recent DNS attacks have shown that the cacheing function in recursive DNS servers is particularly vulnerable.
Re-evaluate whether you actually need local cacheing of your own. If you don't, you're probably better off mo... |
649,640 | 649,709 | How to do an efficient priority update in STL priority_queue? | I have a priority_queue of some object:
typedef priority_queue<Object> Queue;
Queue queue;
From time to time, the priority of one of the objects may change - I need to be able to update the priority of that object in the queue in an efficient way. Currently I am using this method which works but seems inefficient:
Que... | I think you are out of luck with standard priority queue because you can't get at the underlying deque/vector/list or whatever. You need to implement your own - it's not that hard.
|
649,789 | 650,533 | What would be C++ limitations compared C language? | Following are the benefits of C++
C++ provides the specific features they are asking about
Their C compiler is almost certainly really a C++ compiler, so there are no software cost implications
C++ is just as portable as C
C++ code can be just as efficient as C (or more so, or less so)
Are there any concrete reasons ... |
This is prompted by a an answer I gave to a current question which asks about a generics library for C - the questioner specifically states that they do not want to use C++.
C is a complete programming language. C is not an arbitrary subset of C++. C is not a subset of C++ at all.
This is valid C:
foo_t* foo = mallo... |
649,793 | 649,861 | Howto Create Map of Vector From Sorted Data | I have the following data as input (sorted by first column):
foo 1 2
foo 3 3
bar 10 11
I want to create a Map of Vector with first column as key of the map
such that we have:
foo = {1,2,3,3}
bar = {10,11}
But why my code below doesn't work as expected?
#include <vector>
#include <map>
#include <iostream>
... | As Mykola said, you should use the vector in the map instead of creating one yourself. I changed your whole code so it works for me. Note that you wrote some of the variable names with wrong case (MyMapOfVec instead of myMapOfVec) and this led to compiler errors.
Also be sure you don't have a newline at the end of your... |
649,855 | 649,883 | What is the point of adding a return statement at end of a void C/C++ routine? | I see functions/methods with a void return in the signature that have a return statement at the end of the function. What is the reason for this, and does this apply to other languages?
For all I know, I can use return if I want to exit anywhere else but the end of the function.
A C example:
void function(void)
{
i... | This seems pointless here. But my guess is that this kind of thing can be used to put a breakpoint in IDEs which don't support putting a breakpoint at the closing brace and by putting a breakpoint here, some values can be checked in the watch window etc.
|
649,886 | 649,906 | How can you break on handle creation? | I have an application that spawns multiple child processes. Before launching a child, I create stdOut and stdErr handles to a log file (for example, if I am about to launch procA, i create handles to logA.log). I set these handles on the child processes.
By looking with ProcExplorer, I can see that each child process ... | One possible solution can be that handle to file are shared between any child processes beacause they are created by the parent process.
That's the only solution I can see because I don't see how you can have multpile handle (one to each log file) in each child processes if you design so that you only have one var to h... |
649,900 | 649,946 | Detecting the launch of a application | How do I detect with C# on Windows the moment when an external application is being launched?
I tried the FilesystemWatcher which doesn't work because the file is not really changing. Also having a timer constantly check all the open processes might be a bit over kill. Is there any other way to do this? If not in C# is... | You can use System.Management and WMI (Windows Management Instrumentation)
class WMIEvent {
public static void Main() {
WMIEvent we = new WMIEvent();
ManagementEventWatcher w= null;
WqlEventQuery q;
try {
q = new WqlEventQuery();
q.EventClassName = "Win32_Proc... |
650,091 | 650,142 | Using an abstract class in C++ | I'm trying to use an abstract class when passing an extended object as an parameter to a function, but my attempts so far have led to some compiler errors.
I have a few clues as to what the problem is, I'm obviously not allowed to instantiate an abstract class, and I believe some of the code in MyClass is trying to do ... | Your problem is that you should accept a reference in your function. The reason is that a reference does not actually copy the argument passed. If you however accept an A - instead of a reference A& - then you actually copy the argument passed into the parameter object, and what you get is an object of type A - but whi... |
650,162 | 650,218 | Why can't the switch statement be applied to strings? | Compiling the following code gives the error message: type illegal.
int main()
{
// Compilation error - switch expression of type illegal
switch(std::string("raj"))
{
case"sda":
}
}
You cannot use string in either switch or case. Why? Is there any solution that works nicely to support logic similar... | The reason why has to do with the type system. C/C++ doesn't really support strings as a type. It does support the idea of a constant char array but it doesn't really fully understand the notion of a string.
In order to generate the code for a switch statement the compiler must understand what it means for two valu... |
650,232 | 650,237 | Using a pointer to an object stored in a vector... c++ | I have a vector of myObjects in global scope.
std::vector<myObject>
A method is passed a pointer to one of the elements in the vector.
Can this method increment the pointer, to get to the next element,
myObject* pmObj;
++pmObj; // the next element ??
or should it be passed an std::Vector<myObject>::iterator and inc... | Yes - the standard guarantees in a technical correction that the storage for a vector is contiguous, so incrementing pointers into a vector will work.
|
650,261 | 650,276 | C++ ULONG definitions to VB.NET or C# equivalent? | I am trying to use a call-recording API using sockets. We have the API documentation, but the samples are all in C++.
How would I declare the following in VB.NET or C#?
#define SIF_GENERAL 0x08000000
#define SIF_CONFIGURATION 0x08010000
#define SIF_ARCHIVE 0x08020000
#define SIF_SEARCH 0x08030000
#define SIF_REPLAY 0x0... | VB.NET
Module Constants
Public Const SIF_GENERAL as Integer =&H08000000
Public Const SIF_CONFIGURATION As Integer = &H08010000
Public Const SIF_ARCHIVE As Integer = &H08020000
Public Const SIF_SEARCH As Integer = &H08030000
Public Const SIF_REPLAY As Integer = &H08040000
Public Const SIF_STATISTICS As Integ... |
650,283 | 650,301 | Duplicating arrays when equalizing Objects | Greetings everyone. I'm in need of some experiance here as how to deal with dynamic arrays with Objects.
I've a class 'SA', consisting of several objects 'Obj1', 'Obj2' etc...
Within the class I have a dynamic array 'SA_Array' which I initialize in the following manner where size sets its length:
double * SA_Array;
SA_... | If the size is determined at runtime, easiest to use one is a vector
vector<double> SA_Array(size);
Now you can copy, swap, resize it and it will act accordingly. If you need a pointer to the begin, you can do that with &SA_Array[0]. If the size is determined and fixed at compile time, you can use boost::array
boost::... |
650,309 | 682,876 | How to inhib "Delayed Write Failed" message? | I have a Windows service running in a specified user account with write permission on a shared drive on another computer. The service is logging on that shared drive.
I allow the user to enter mapped path or network path (e.g. z:\MyRemoteFolder or \RemoteComputer\MyRemoteFolder) as the log destination.
As I am in an un... | Using "FILE_FLAG_WRITE_THROUGH" and "FILE_FLAG_NO_BUFFERING" in create file worked for me.
|
650,461 | 650,711 | What are some tricks I can use with macros? | In our legacy code, as well as our modern code, we use macros to perform nifty solutions like code generations, etc. And we make use of both the # and ## operators.
I am curious how other developers use macros to do cool things, if they use them at all.
| In C, it's common to define macros that do some stuff getting the verbatim argument, and at the same time define functions to be able to get the address of it transparently.
// could evaluate at compile time if __builtin_sin gets
// special treatment by the compiler
#define sin(x) __builtin_sin(x)
// parentheses avoid... |
650,708 | 650,723 | Is it valid to pass a pointer to a stack variable to realloc()? | int main()
{
char myString = NULL;
realloc(&myString, 5);
strncpy((char *)&myString, "test", 5);
}
Seems to work fine but I'm still slightly confused about stack vs heap. Is this allowed? If it is allowed, does myString need to be freed manually or will it be released when it goes out of scope?
Edit: Thanks ... | No, this is completely wrong. realloc should only be used to reallocate memory allocated by malloc, what you are doing works only by accident, and will eventually crash horribly
char *myString = malloc(x);
myString = realloc(myString,y);
free(myString)
You are better off using new and delete, and even better off using... |
650,770 | 650,783 | C++: Is it possible to share a pointer through forked processes? | I have a count variable that should get counted up by a few processes I forked and used/read by the mother process.
I tried to create a pointer in my main() function of the mother process and count that pointer up in the forked children. That does not work! Every child seems to have it's own copy even though the addre... | Each child gets its own copy of the parent processes memory (at least as soon as it trys to modify anything). If you need to share betweeen processes you need to look at shared memory or some similar IPC mechanism.
BTW, why are you making this a community wiki - you may be limiting responses by doing so.
|
650,889 | 650,901 | Is there a way to prevent the hide operation of a toolbar? | In Qt, if I right-click on a toolbar the menu will be shown that allows me to hide the toolbar. I need to disable this functionality because I don't want the toolbar to possible to hide. Is there a way to do this?
| Inherit QToolbar and reimplement contextMenuEvent().
|
650,931 | 650,977 | C++ MI static template - static method disapears at join | #include <iostream>
using namespace std;
/*
TA <-- defines static function
/ \
| B <-- subclass TA, inherits it so B::StaticFunc can be used.
\ /
C <-- want to inherit static func from A, subclass B privately
*/
template <class T> class TA
{
public:
// retu... | I get a different, more reasonable error (with g++ 4.3.3):
tst.cpp: In function ‘int main()’:
tst.cpp:49: error: reference to ‘instance’ is ambiguous
tst.cpp:22: error: candidates are: static T* TA<T>::instance() [with T = B]
tst.cpp:22: error: static T* TA<T>::instance() [with T = C]
This can be fixed... |
651,012 | 651,109 | returning a set of keys in the map matching the criteria | First I will give a specific case, and the I would like to see if it can be applied to a general problem.
Say I have map. And I want to get all the keys meeting a certain criteria.
For example all keys that contain "COL". My naive implementation will be
template<typename T>
void Filter (map<string, T> & m, std:set<s... | I think your solution is rather good: it is clear, and except if you can "guess" hash values based on the condition, I don't think you could be much more performant. However, you could change your function to make it more generic:
template<typename TKey, typename TValue, typename Predicate>
void filter (const map<TKey,... |
651,060 | 653,332 | Returning an object as a property in ATL | I am creating a COM object using Visual Studio 2008 and ATL. Adding simple properties and methods is easy enough but now I want to do something more complicated. I want to give access to a C++ object via a property of my COM object, so I can do something like:
// Pseudo-code
var obj = CreateObject("progid");
obj.aPro... | I just came across this article:
HOWTO: Implement static object hierarchies in ATL
This looks very similar to what I am trying to achieve.
|
651,154 | 651,188 | why does throw "nothing" causes program termination? | const int MIN_NUMBER = 4;
class Temp
{
public:
Temp(int x) : X(x)
{
}
bool getX() const
{
try
{
if( X < MIN_NUMBER)
{
//By mistake throwing any specific exception was missed out
//Program terminated here
throw ... | This is expected behaviour. From the C++ standard:
If no exception is presently being
handled, executing a throw-expression
with no operand calls
terminate()(15.5.1).
As to why the compiler can't diagnose this, it would take some pretty sophisticated flow analysis to do so and I guess the compiler writers would... |
651,158 | 652,714 | CBlobCache usage - ATL Server Library | Someone may have an example of use for CBlobCache?
| BlobCache documentation and samples are on MSDN.
|
651,198 | 652,151 | can you create a lib or dll in VS 2005 and link with VS 2008 | I am using visual studio 2008 SP1.
And I am creating a desktop application using MFC.
I have a library I want to link with my application. However, the library was written in WIN32 visual studio 2005.
I am been having a trouble linking:
fatal error LNK1104: cannot open file 'AgentLib.lib'
I am wondering if it is beca... | Make sure you have added the path where your lib files are under project settings in Linker>General>Additional Library Directories
|
651,497 | 651,502 | How to do std::string indexof in C++ that returns index of matching string? | I'm looking for a string indexof function from the std namespace that returns an integer of a matching string similar to the java function of the same name. Something like:
std::string word = "bob";
int matchIndex = getAString().indexOf( word );
where getAString() is defined like this:
std::string getAString() { ...... | Try the find function.
Here is the example from the article I linked:
string str1( "Alpha Beta Gamma Delta" );
string::size_type loc = str1.find( "Omega", 0 );
if( loc != string::npos ) {
cout << "Found Omega at " << loc << endl;
} else {
cout << "Didn't find Omega" << endl;
}
|
651,834 | 651,856 | Deterministic Random Number Streams in C++ STL | I want to supply a number, and then receive a set of random numbers. However, I want those numbers to be the same regardless of which computer I run it on (assuming I supply the same seed).
Basically my question is: in C++, if I make use of rand(), but supply srand() with a user-defined seed rather than the current ti... | srand() & rand() are not part of the STL. They're actually part of the C runtime.
Yes, they will produce the same results as long as it's the same implementation of srand()/rand().
Depending on your needs, you might want to consider using Boost.Random. It provides several high-quality random number generators.
|
652,155 | 652,249 | invalid use of incomplete type | I'm trying to use a typedef from a subclass in my project, I've isolated my problem in the example below.
Does anyone know where I'm going wrong?
template<typename Subclass>
class A {
public:
//Why doesn't it like this?
void action(typename Subclass::mytype var) {
(static_cast<Subclass*>... | The reason is that when instantiating a class template, all its declarations (not the definitions) of its member functions are instantiated too. The class template is instantiated precisely when the full definition of a specialization is required. That is the case when it is used as a base class for example, as in your... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.