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 |
|---|---|---|---|---|
6,253,351 | 6,253,386 | Can't use "not", "or", or "plus" as identifier? | I tried to compile this:
enum class conditional_operator { plus, or, not };
But apparently GCC (4.6) thinks these are special, while I can't find a standard that says they are (neither C++0x n3290 or C99 n2794). I'm compiling with g++ -pedantic -std=c++0x. Is this a compiler convenience? How do I turn it off? Shouldn'... | Look at 2.5. They are alternative tokens for || and !.
There is a bunch of other alternative tokens BTW.
Edit: The rationale for their inclusion is the same as the one of trigraphs: allow the use of non ASCII character sets. The committee has tried to get rid of them (at least of trigraphs, I don't remember for alter... |
6,253,372 | 6,253,530 | Converting vector of digits from base to base | How can I convert a vector<int> in base a to vector<int> in base b without the use of a library like gmp?
The contain the digits of the numbers. a and b are less than 1024. a can be smaller or larger than b.
I thought about using the standard base conversion algorithm but the numbers won't fit even in long long.
|
I thought about using the standard base conversion algorithm but the numbers won't fit even in long long.
This is the correct (as in: “clean”) approach. Since the numbers won’t fit in a native number type, and you don’t want to use existing libraries, you essentially need to implement your own number type, or at leas... |
6,253,425 | 6,253,517 | Is it possible to use the STL multimap value_type function with a multiple argument C++ constructor | Good morning , In Scott Meyers book Effective STL, Mr Meyers explains how the map::value_type function saves the cost of construction and deletion of a temporary object.
We are trying use Mr. Meyers technique with a multimap where the class Range has two constructors:
class Range {
public:
explic... | The third option would be available as emplace in a compiler supporting C++0x, like gcc 4.5 or 4.6.
Currently std::pair can only be constructed with two parameters. Variadic templates will change that and offer new possibilities, as will rvalue references and perfect forwarding.
|
6,253,547 | 6,253,631 | Need a map from enum (class) to std::binary_function | I have this enum (class)
enum class conditional_operator
{
plus_op,
or_op,
not_op
}
And I'd like a std::map that represents these mappings:
std::map<conditional_operator, std::binary_function<bool,bool,bool>> conditional_map =
{ { conditional_operator::plus_op, std::logical_and<bool> },
... | You really want std::function<bool(bool, bool)>, not std::binary_function<bool, bool, bool>. That only exists for typedefs and stuff in C++03. Secondly, I'd just use a lambda- they're short enough and much clearer. The std::logical_and and stuff only exists for C++03 function object creation, and I'd use a lambda over ... |
6,253,574 | 6,253,600 | Uncaught exception in a callback from a 3rd party static library | I am compiling my program with a 3rd party library. That library contains an error callback if an error occurs internally. Inside that error callback I am throwing an exception and I have a unit test to verify that when I do something invalid that the exception is thrown. This all works beautifully in Windows, but when... | When you interface with third-party libraries you usually have to catch all exception on the border between your code and their code:
int yourCallback( params )
{
try {
doStuff( params );
return Okay;
} catch (...) {
return Error;
}
}
The reason is you can't be sure that library is writte... |
6,253,589 | 6,253,635 | c++: call overloaded function for derived classes as arguments too (without explicit cast) | Imagine the following scenario:
template<class T>
void myFunction(T *)
{
//do nothing
}
void myFunction(myBase * _base)
{
//do something with _base
}
int main( int argc, const char* argv[] )
{
myDerivedFromBase * ptr = new myDerivedFromBase;
myFunction(ptr); //calls t... | Use type traits to prevent the template from binding:
template<typename T>
typename std::enable_if<!std::is_base_of<myBase, T>::value, void>::type myFunction(T*)
{
}
If you can't use C++0x, use Boost's type traits library instead.
|
6,253,665 | 6,253,881 | How to determine if a string is a valid IPv6 address in C++? |
Possible Duplicate:
IPv6 parsing in C
I need to check strings if they are valid IPv6 addresses in C++.
There are elegant solutions for C# here and rather ugly regex here.
Is there a good way to do this in C++ ?
I'm currently using this, but it doesn't work on Windows XP (inet_pton() is missing):
unsigned char buf[si... | You can use getaddrinfo in Linux, or in Windows since Windows 2000. (See the section of that document page entitled "Example code using AI_NUMERICHOST")
|
6,253,730 | 6,262,030 | libcurl: Detect chunk boundaries of chunk-encoded responses | I am using libcurl, currently the easy api. I am making a request to a web server that responds with HTTP Chunked Encoding. I would like to know if there is a way to know when a chunk from the server has finished. I was looking for some type of callback. DEBUGDATA didn't seem to include it, and CHUNK_END_FUNCTION seem... | If you use the CURLOPT_DEBUGFUNCTION option you will get the data "un-chunked" and then you can scan and parse the data yourself as you see fit and thus track the end of chunks or whatever you like. ()
As "n.m." already said, libcurl has no API that exposes chunks as it tries to make the transfer encoding completely tr... |
6,253,737 | 6,253,766 | C++: How to read and write multi-byte integer values in a platform-independent way? | I'm developing a simple protocol that is used to read/write integer values from/to a buffer. The vast majority of integers are below 128, but much larger values are possible, so I'm looking at some form of multi-byte encoding to store the values in a concise way.
What is the simplest and fastest way to read/write mult... | XDR format might help you there. If I had to summarize it in one sentence, it's a kind of binary UTF-8 for integers.
Edit: As mentioned in my comment below, I "know" XDR because I use several XDR-related functions in my office job. Only after your comment I realized that the "packed XDR" format I use every day isn't ev... |
6,253,834 | 6,254,733 | Eclipse C++ Running/Debugging problems with console IO | I've been trying to get into C++ programming with Eclipse, but I'm having problems setting up Eclipse.
I have MinGW installed and in the environment path, and I created the simple C++ project with the following source code:
#include <iostream>
int main(void)
{
std::cout << "what is your name? ";
std::string na... |
Is there an alternative method to have Windows find the dll's in MinGW's bin folder rather than have to copy them over each time?
Set the PATH environment variable in the run configuration settings (Run -> Run Configurations... -> Environment).
|
6,253,998 | 6,280,139 | How to create and read pkcs7 signed envelop with smime format? | I want to create pkcs7 signed envelop having S/MIME format and also want to read it. The file extension is pk7.
How to do it with the OpenSSL library?
| The SMIME_read_PKCS7() and SMIME_write_PKCS7() functions can be used to convert an SMIME message into a PKCS7 structure and vice-versa.
You can use PKCS7_sign() / PKCS7_encrypt() to create PKCS7 structures, and PKCS7_verify() / PKCS7_decrypt() to consume them.
|
6,254,102 | 6,254,175 | Passing a double to later in a program - using a dialog box for entry | I am trying to pass a double that is used later in my program. When the program launches, a dialog box appears, asking for a number to be input. The following code is supposed to receive entry of the number, and convert it into a double to be passed on:
char MaxBuf[256];
#ifdef WIN32
edit_dialog(NULL,"Max", "Enter Max... | First of all, defining variable in a header file is not a good practice because every file that includes that header will have its own version of the variable (unless you use some guarding macro to anticipate this).
That is why you experience uninitialized variable because it is different variable with the variable you... |
6,254,307 | 6,254,440 | Create a map of pointers to objects in a list? | In trying to patch memory leaks among other things in a side project I've totally confused myself with pointers and lists and maps and memory, etc.
I want to create a list of objects to use throughout the programs life. But I also want to use a map to quickly access individual objects from that list through their uniq... | I would alter this a little bit, and use something like a std::shared_ptr<cObject> in both your list and your map. You can, for the map, use either an int, or possibly a std::string for the key-type, and then for the value-type, use the std::shared_ptr<cObject>
So your code would look more like:
using namespace std;
... |
6,254,361 | 6,254,461 | dll needed at runtime if lib included? | I want to create a .dll (in C++) that uses RAPI. For this I create the visual studio project and then I set the additional include directories to the place where I have "rapi2.h" needed, and also the additional link directories to the place where rapi.lib is located.
Then I write another application using my created .... | You need to understand the difference between dynamic linking and static linking. In your case, the lib is an import library only and does not contain actual executable code. That is dynamically linked at runtime.
|
6,254,447 | 6,268,367 | Using pHash from .NET | I am trying to use pHash from .NET
First thing I tried was to register (regsvr32) phash.dll and asked here
Second of all, i was trying to import using DllImport as shown below.
[DllImport(@".\Com\pHash.dll")]
public static extern int ph_dct_imagehash(
[MarshalAs(UnmanagedType.LPStr)] string file,
... | The current Windows source code project (as of 7/2011) on phash.org does not seem to export the ph_ API calls from the DLL. You will need to add these yourself by __declspec(dllexport) at the beginning of the line in pHash.h like so:
__declspec(dllexport) int ph_dct_imagehash(const char* file,ulong64 &hash);
You shoul... |
6,254,599 | 6,254,800 | A problem with higher order functions and lambdas in C++0x | I have a program where I must print many STL vectors on the screen after doing some calculation on each component. So I tried to create a function like this:
template <typename a>
void printWith(vector<a> foo, a func(a)){
for_each(foo.begin(), foo.end(), [func](a x){cout << func(x) << " "; });
}
And then use it lik... | The following works for me:
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
template <typename a, typename F>
void printWith(vector<a> foo, F f){
for_each(foo.begin(), foo.end(), [&](a x){cout << f(x) << " "; });
}
int main(){
vector<int> foo = {1,2,3,4,5};
printWith(foo, [](int... |
6,254,915 | 6,254,951 | Abstract class accessing the implemented type through a templated virtual function? | I was wondering if there could be any way to write a template function in an abstract class, and have it (the template function) automatically instantiated with the type of the derived class?
So you have a class that looks something like this
class A
{
virtual template < typename T>
void vtfunc(void)
};
class B : p... | I’m not sure what you’re after but one common pattern is the so-called curiously recurring template pattern; here, the base class itself is the template, not its member functions. In other words:
template <typename T>
class A
{
virtual void vtfunc(void)
};
class B : public A<B>
{
…
};
|
6,255,339 | 6,255,364 | Checking if a file opened successfully with ifstream | I have the following that will open a file for reading. However, I want to check to make sure that the file was open successfully, so I am using the fail to see if the flags have been set. However, I keep getting the following error:
I am new to C++, as I am coming from C. So not sure I understand this error:
cannot c... | You can simply do this:
int devices::open_file(std::string _file_name)
{
ifstream input_stream;
input_stream.open(_file_name.c_str(), ios::in);
if(!input_stream)
{
return -1;
}
file_name = _file_name;
return 0;
}
fail() is not a static method, you must call it on an instance no... |
6,255,445 | 6,255,799 | Basic dialog box input for a strobe light implementation | I have connected a photographic flash unit to my computer using a relay switch connected to the serial port. The following code causes the strobe to flash at 4Hz for 10 flashes:
#include <windows.h>
//Initialise Windows module
int WINAPI WinMain (HINSTANCE hThisInstance, HINSTANCE hPrevInstance, LPSTR lpszArgument, in... |
Open Visual Studio, New, Project,
Visual C++, Windows Forms
Application. This will give you a
GUI where you can drag and drop what
you need. If you don't have Visual
Studio then perhaps your IDE has
something similar?
Make this a console app that accepts the data in the command line. Call the app with an appropriate c... |
6,255,480 | 6,296,301 | C++ Structures with different members - decided at runtime | I have the following situation. A pseudo-code is attached below. I have a class A which has an object c of type D or E and this varies (actually its randomly decided). It uses b as a message for communication with a remote computer.
So, how should I get the struct B to have different variables (float or double in this... | Union can be used to solve the problem.
struct B
{
int a;
bool d; //d = 0 for D and 1 for E
union
{
float b;
double c;
}
};
|
6,255,555 | 6,256,215 | socket identifier equals -1 | Somehow, someway the socket is -1. It shouldn't be because my client program connects and send information but is stopped by SIGPIPE signal. When I debug the server I see that accept returns -1. I have got no idea why. If you no, answer please.
client.cpp
using namespace std;
using namespace msg;
using namespace dataEx... | One glaring issue I see is that your port is invalid. sockaddr_in::sin_port is a uint16_t, whose largest value can possibly be 65536. Best case, you're truncating your port on the call to htons, which should result in 57920.
In regards to why the accept is failing, -1 indicates an error occured, and you should check th... |
6,255,599 | 6,255,621 | trouble implementing a linked list | I'm trying to implement a simple link list. The initial value is inserted successfully, but the next elements are not entered properly. Please help me resolve what the error is. Thanks in appreciation.
#include<iostream>
using std::cout;
class node
{
public:
node():next(0){}
void setNext(node *nex... | After a cursory glance, perhaps the problem is
void setNext(node *next){ next = next; }
You are assigning a variable to itself, because local variables overshadow instance variables. Try changing that to
void setNext(node *next){ this->next = next; }
In other notes:
In list::list, you probably shouldn't initialize h... |
6,255,610 | 6,255,753 | A good tutorial for Visual Studio c++ linker | I've started working on solutions with LOTS of different c++ projects.
I want to understand better the different types of libraries (static/dynamic libraries).
MFC static/shared...
using ATL...
And basically understanding the meaning of the 100s of options in a c++ project properties.
Can anyone recommend a good source... | Here is the compiler and linker reference from MSDN. And another link that might be worth looking at is: Creating and Managing Visual C++ Projects
Apart from the Microsoft solutions, you can also take a look at CMake. Here is the CMake documentation with links to wiki, tutorial and reference.
|
6,255,682 | 6,255,774 | Simple value input in a Windows program | I have a program that runs in the Win32 environment. There is one variable that I would like to set before the program begins. The only reason it is a Win32 program is because I am accessing serial ports. I don't care how I input the variable - it is a number and I suppose a dialog edit box would be best - but I don't ... | To access serial port, you don't need windows application. You can create a simple console based application, it will be a still win32 by architecture.
The advantages being using a console application would that you could use 'C' style scanf or C++ style cin to read the input from user.
For the windows application, yo... |
6,255,825 | 6,255,899 | What operators should be declared as friends? | In some books and often around the internet I see recommendations like "operator== should be declared as friend".
How should I understand when an operator must be declared as friend and when it should be declared as member? What are the operators that will most often need to be declared as friends besides == and <<?
| This really depends on whether a class is going to be on the left- or right-hand side of the call to operator== (or other operator). If a class is going to be on the right-hand side of the expression—and does not provide an implicit conversion to a type that can be compared with the left-hand side—you need to implement... |
6,255,984 | 6,256,005 | Abstract Base Class w/o Polymorphism | Why would you have an abstract base class defining an interface for a library where there is only one (always and forever) derived class?
| You may want to swap out the implementation for something like Unit Testing
|
6,256,101 | 6,256,190 | Two types using each other in C++ | In my header file I have a function pointer and a struct:
typedef struct _CONTINUE_STATE {
DWORD CurrentCycle;
CommandProc* CommandFunc;
void* Resered;
} CONTINUE_STATE, *PCONTINUE_STATE;
--
typedef HRESULT (*CommandProc)(SOCKET client, char* command, char* response, CONTINUE_STATE* continueProc);
The pro... | Firstly:
typedef struct _CONTINUE_STATE {
DWORD CurrentCycle;
CommandProc* CommandFunc;
void* Resered;
} CONTINUE_STATE, *PCONTINUE_STATE;
No need for typedefs, and you should not typedef pointers. So lets make that:
struct _CONTINUE_STATE {
DWORD CurrentCycle;
CommandProc* CommandFunc;
void* R... |
6,256,400 | 6,256,435 | Return a string from Win32 RPC call | I'm trying to make an RPC call which requests 2 numbers and a string from the RPC server, the IDL looks like this:
void GetCurrentStatus([in] handle_t hBinding, [out, ref] DWORD *dwRef1, [out, ref] DWORD *dwRef2, UINT *nLength, [out, size_is(, *nLength)] LPWSTR *pszName);
In the server-side call I do this:
// name = s... | If you have a choice in the matter, use BSTR (i.e. SysAllocString). RPC knows all about this data type and how to copy it and find its length.
Just
[out, retval] BSTR* pstrName
is enough, no separate length parameter needed.
|
6,256,492 | 6,256,543 | If I delete a class, are its member variables automatically deleted? | I have been researching, and nothing relevant has come up, so I came here.
I am trying to avoid memory leaks, so I am wondering:
Say I have class MyClass with member ints a and b, and an int array c, which are filled in a member function:
class MyClass
{
public:
int a, b;
int c[2];
void setV... | When delete mc is executed, the compiler calls the destructor of the object (MyClass::~MyClass()) and then deallocates the memory associated with it.
The default destructor (when you don't declare your own) calls the destructors of all member variables, in order from last to first by declaration (that is, in this case,... |
6,256,552 | 6,575,544 | List of sanity test generators for C++? | I have found only
http://ispras.linux-foundation.org/index.php/API_Sanity_Autotest
because it is listed on Wikipedia. Is there any other Sanity suite for C++?
| It seems API Sanity Autotest is the only one existent
|
6,256,676 | 6,257,086 | Perform an action after driver initialization during boot | I would like to perform an action on the device drivers in the system after they initialize during boot-up. I would like to do this from my own application that would not be part of any existing driver. Is there a way to check when a driver is done with its initialization from my application so I can do what I would li... | Your question is unclear. Control from where? Is your question better phrased like this?
I would like to perform an action on every driver in the system after they initialize from my own, separate driver/application/etc. code. This code would not be part of any existing driver.
If that's what you're after then no,... |
6,256,682 | 6,256,742 | Can flash detect a screenshot (or GDI bitcopy) being taken? | Can pixels be read covertly from a browser window containing flash + HTML?
(Is it possible for flash or the browser to detect a screenshot being taken?)
What about for other methods of capturing pixels? (Like the one described here: How to read the screen pixels?)
EDIT: (background info)
A C++ application is going to r... | For sure, you cannot detect someone using a framegrabber card to get a screenshot. There is no way you can be aware of this happening, as it happens behind the graphics card output. So for this way, no, no way you can detect it.
Otherwise, it's also pretty simple: Some application can hook your browser and prevent any ... |
6,256,797 | 6,256,993 | Store a cache COPY of table locally SQL Server |
Is it possible to store a cache copy of the table data locally to avoid transfer (data does not change, This I assure it!) in SQL Server. So C++, C# can know the data stored by SQL in cache and then read the data in cache and compute some things with the table?
Is it possible this kind of communication between SQL ... | ADO.You need to use ADO.NET (Disconnected) DataSets:
1) Create a Dataset
DataSet dsCustomers = new DataSet();
2) Create a DataAdapter, specifying what data to get
SqlDataAdapter daCustomers = new SqlDataAdapter(
"select CustomerID, CompanyName from Customers", conn);
3) Fill the Dataset
daCustomers.Fill(dsCustome... |
6,257,031 | 6,257,120 | A question about Template in C++ | I know the basics of templates in C++, but I am still learning it.
I have a question regarding to the following code:
#include <iostream>
using namespace std;
class PNG {
public:
static void draw() {
cout<<"PNG drawing"<<endl;
}
};
template <typename Image>
void draw() {
Image::draw();
}
int ma... | Your first question
if I call this template function
draw() in main in this way: draw(); is
it allowed?
As you have realised, the compiler cannot deduce by itself that you mean draw<PNG> if there are no function arguments from which to figure it out.
So, you have to write (as you already do):
int main() {
draw... |
6,257,166 | 6,257,182 | std::vector and algorithm::sort , What is wrong with following code | I am trying sort std::vector using algorithm::sort , But I am getting runtime error
Invalid operator <.
Following is my code.
struct Point {
double x_cord;
double y_cord;
int id;
Point(int d, double x, double y) {
x_cord = x;
y_cord = y;
id = d;
}
};
struct compareX {
bo... | Your comparison function always returns true!
|
6,257,243 | 6,257,442 | What information does "Top" output while using MPI | I am trying to figure out how much memory my program which uses MPI needs. It was suggested to use the function "top" to obtain the usage of memory. However, I am unclear on what the information means.
I wish to know how to estimate the system memory and how much it utilizes?
top - 13:52:41 up 208 days, 19:50, 1 use... | The standard information displayed by top is, in order:
The Process ID
The owning username
The kernel-assigned process priority (higher is "lower" priority)
The "niceness" of the process (higher is "nicer" to other processes and gives the process a "lower" priority)
The virtual memory allocated for the process in KiB
... |
6,257,265 | 6,257,373 | What's the syntax to overload operator== as a free function with templated parameters? | I have a set of polymorphic classes, such as:
class Apple {};
class Red : public Apple {};
class Green : public Apple {};
And free functions which compare them:
bool operator==(const Apple&, const Apple&);
bool operator< (const Apple&, const Apple&);
I'm designing a copyable wrapper class which will allow me to use c... | Your template is declared as
template <typename Cat>
bool operator==(const Copy<Cat>& copy, const Cat& e)
This doesn't match redCopy == Red() because Red() is of type Red, so the compiler deduces Red as the type of the second argument, i.e. Cat = Red, but then it expects the type of the first argument to be Copy<Red>... |
6,257,515 | 6,257,534 | Threadsafe way to convert time between timezones | I am writing a application to convert utc-time to different timezones, now I can use something like this
putenv("TZ=TIMEZONE1");
tzset()
...
do time conversions
but I don't think it is thread safe, so is there any C/C++ library which can do timezone conversion by taking timezone as argument to function instead of bei... | Boost.DateTime supports time-zone conversions.
|
6,257,689 | 6,257,762 | How to form a C++ string from concatenations of string literals? | I would like concatenate string literals and ints, like this:
string message("That value should be between " + MIN_VALUE + " and " + MAX_VALUE);
But that gives me this error:
error: invalid operands of types ‘const char*’ and ‘const char [6]’ to binary ‘operator+’|
What is the correct way to do that? I could split... | You should probably use stringstream for this.
#include <sstream>
std::stringstream s;
s << "This value shoud be between " << MIN_VALUE << " and " << MAX_VALUE;
message = s.str();
|
6,257,807 | 6,259,317 | What's happening in the background of a unsigned char to integer type cast? | I was getting some odd behaviour out of a switch block today, specifically I was reading a byte from a file and comparing it against certain hex values (text file encoding issue, no big deal). The code looked something like:
char BOM[3] = {0};
b_error = ReadFile (iNCfile, BOM, 3, &lpNumberOfBytesRead, NULL);
switch ... |
"Can someone briefly explain what was
going on in the char -> int promotion
that produced 0xffffffef instead of
0x000000ef?"
Contrary to the four answers so far, it didn't.
Rather, you had a negative char value, which as a switch condition was promoted to the same negative int value as required by
C++98 §6.4.2... |
6,257,850 | 6,257,899 | C++ codebase rewrite from MFC to *nix | I'm interning in a company for the summer and I've to look at different ways of looking at the current codebase (C++,MFC, around 100K lines) and using state machines to model the current program.
I've been reading a couple papers and CPP2XMi looks like it may be some use to try to build sequence diagrams as a start.
Th... | The first thing I would look at is where do I use mfc and other non portable stuff. If the only place there is mfc is in the interface layer for example you then can isolate the work.
If there is no such separation I would look at the fesablity of creating some sections of the code that are isolated and portable. On... |
6,258,052 | 6,282,442 | Illegal read/write error when making legacy code x64 compliant | I have the following MyType::Is_Inst () function which is throwing an invalid memory access error on return in 64-bit mode but not in 32-bit:
MyType MyType::Is_Inst () {
unsigned char Bar=0;
MyType Foo={0};
return Foo;
}
Looking at the disassembly + step-through, the program crashes at the line... | I've posted a bug report to MS here:
https://connect.microsoft.com/VisualStudio/feedback/details/674672/callee-disassembly-expects-address-which-caller-is-not-providing-in-x64-mode
Again, thanks to all for your help!
|
6,258,137 | 6,258,202 | How do I store this data set in C++ (which containers do I use)? | I have data represented as follows.
A-> B,C,D,E,F
B-> C,(D,E),F
D-> (E,F)
E-> (F,G)
F-> (G)
G-> NULL
Each letter represents a string. All letters/strings are in alphabetical order. The B-> means that B is a member of every element succeeding it. So for this example row B consists of the sets (B,C), (B,D,E) and (B,... | It seems a graph is what you are looking for, but the standard C++ library (STL) does not have such a data structure. The next best bet is multimap: a map is an 1:1 associated array, where as multimap is a 1:many associated array.
|
6,258,387 | 6,258,434 | How is the C++ multimap container implemented? | For example a C++ vector is implemented using a dynamic array where each element uses consecutive memory spaces.
I know that a C++ multimap is a one to many relationship but what is the internal structure?
| The C++ standard does not define how the standard containers should be implemented, it only gives certain constraints like the one you say for vectors.
multimaps have certain runtime complexity (O(lg n) for the interesting operations) and other guarantees, and can be implemented as red-black trees. This is how they are... |
6,258,458 | 6,258,560 | Trouble adding compiler to windows path | I'm having a seemingly silly problem with my gcc compiler. I have installed MinGW at location C:\MinGW... and I have added C:\MinGW\bin to my windows path. However, when I got to the command prompt and type gcc --version... it doesn't recognize it. I have to cd manually to the bin before it will recognize it.
When I... | How did you set the path? You should set it from Control Panel->System->Advanced->Environment Variables. The change will affect newly opened command consoles only.
If it then does not work, in the console, when you enter the command path does the displayed path list include your path? Is it correct?
Are ther other G... |
6,258,485 | 6,449,051 | Boost Python signature mismatch problem | I'm getting a signature mismatch with a method I'm exposing to python. Here's the code below
class StatusEffect
{
public:
//Virtual functions and non related ommitted
void AddCancellation(std::string &effect)
{
CancelsEffects.insert(effect);
}
}
There are some virtual methods in StatusEffect that I ... | Turns out I need to have
void AddCancellation(std::string &effect)
{
CancelsEffects.insert(effect);
}
as
void AddCancellation(const std::string &effect)
{
CancelsEffects.insert(effect);
}
|
6,258,812 | 6,258,888 | Why does this Stream of data end at byte 26? | I'm still working on that bitmap I/O problem from a week ago. I got stuck again, so I decided to start with a type of I/O I was familiar with, and make it more like what I needed steadily (which is checking each byte (pixel) at a time and outputting to a file based on that byte's value).
I started out with a program t... | If you look up what ascii code 25 is you'll see it means end of medium so there's a good chance that if you're reading in ascii mode, any subsequent reads aren't going to work.
Try specifying that you're using a binary file:
sourcefile.open("Input.FILE", ios::binary);
|
6,258,855 | 6,258,869 | How do I insert a list of strings (text format) into a container alphabetically? | Supose i have
(A,B)
(A,C)
(A,D)
(B,C)
(B,D)
(C,D)
(D,E)
in a text file. I'll extract it using regular expressions.
I would like to insert the data in to a container so that it looks like this.
A->B,C,D
B->C,D
C->D
D->E
Which container do I use?
I need to be able to look up data on both the left hand and right hand s... | A std::vector with a one-off sort at the end may well be more efficient than something like a std::set (which will maintain ordering as you insert).
My advice would be to pick the one that best matches the semantics of what you want to do, and then modify it later if you find that it is inefficient.
|
6,258,912 | 6,258,933 | How do I insert a list of pairs most efficiently? | Supose i have
(A,B)
(A,C)
(A,D)
(B,C)
(B,D)
(C,D)
(D,E)
in a text file. I'll extract it using regular expressions.
I would like to insert the data in to a container so that it looks like this.
A->B,C,D
B->C,D
C->D
D->E
Which container do I use?
I need to be able to look up data on both the left hand and right hand s... | std::multimap comes to mind... Is basically a map, but allows duplicates in the map key (i.e. you can have multiple "A" keys, each mapping to a "B", "C" or "D" key, to continue your example).
EDIT: In response to Chris' comment: you insert items into a multimap in the same manner as a map - you make a std::pair object ... |
6,259,022 | 6,259,322 | How can I handle DLL_EXPORT when compiling dll to a static library? | I have a project in visual c++ 2010, which contains preprocessor directives in a key header file. Actually, it is the ZMQ source code.
The project is normally configured to be a dll, so the header uses DLL_EXPORT's status (defined/not defined). If the project is used to compile a dll, the header can be used by both the... | I would just introduce a second (optional) macro, something like ZMQ_STATIC:
#if defined(ZMQ_STATIC)
# define ZMQ_EXPORT
#elif defined(DLL_EXPORT)
# define ZMQ_EXPORT __declspec(dllexport)
#else
# define ZMQ_EXPORT __declspec(dllimport)
#endif
Define said macro both when building your library as a static libr... |
6,259,055 | 6,263,700 | CreateProcess such that child process is killed when parent is killed? | Is there a way to call CreateProcess such that killing the parent process automatically kills the child process?
Perhaps using Create Process Flags?
Edit
The solution is to create a job object, place both parent and child in the job object. Whent he parent is killed the child is killed. I got the code from here:
Kill... | Using jobs as Neil says is IMHO the best way. You can make the child processes get killed when the job owning process dies by setting JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE on the job object using SetInformationJobObject(). The job object handle will be closed when your parent process exits/dies. For this to work it is ess... |
6,259,079 | 6,262,136 | Are elements searchable in a multimap? Is it needed? | If I have Key->Elements
A->B,C,D,E
Are B,C,D,E searchable , i.e. are they inserted into a red and black tree.
I think the answer is no. I think I would need a
multimap<string,map>
to make the value part searchable efficiently (i.e. part of a red and black tree)
A->B,C,D
B->C,D
C->D
D->E
If I use a map of sets,... | If you want the value part to be a sequence with efficient look-up time, you can use
multimap<string, set>
if the elements of the value-sequence are unique, or
multimap<string, multiset>
if not. This would give you logarithmic lookup time, and logarithmic insertion (this can be better or worse depending on the type o... |
6,259,291 | 6,259,332 | how to call methods of defined classes from within template class methods | How should I call a method within a defined class from a template class method?
Below is my scenario -
Template Class
template <class T>
class TC {
void myTemplateMethod() {
T.myMethod(); //can I call like this ?
}
};
Defined Class
class tdef {
void myMethod() {
//does something
}
}... | That's a non-static member function, so it can only be called on an instance. Templates don't change that fact.
T t;
t.myMethod();
or if the function were static:
T::myMethod();
|
6,259,390 | 6,259,618 | How I can get QMetaObject from just class name? | I need to get QMetaObject for dynamic creation of object instances.
If I khow the object then QObject::metaObject() is what I need. If I know the class then I can use QObject::staticMetaObject variable. But what should I use if I know only class name as a string value?
| You ask for a QMetaObject, but say it is for creation purposes. If that's all you have to do, QMetaType may well be what you need. You have to register your types with it, but I'm pretty sure QT doesn't have a master list of QMetaObjects just floating around by default, so such registration will be necessary no matte... |
6,259,438 | 6,259,634 | Remove overlap from vectors of vectors | What basically I am doing is the set cover problem, removing duplicate from the vectors that has the same numbers. An example:
I have the following vectors of vectors after sorting:
{{1,2,3,4,5},{2,3,7,8},{10,11,12}}
NOW, I would like to remove the occurrence from 2nd vector which is 2,3 and sort again ...
{{1,2,3,4... | Pick this apart and take what you need:
#include <algorithm>
#include <vector>
struct binary_search_pred
{
typedef bool result_type;
explicit binary_search_pred(std::vector<int> const& v) : v_(&v) { }
bool operator ()(int const& i) const
{
return std::binary_search(v_->begin(), v_->end(), i);... |
6,259,466 | 6,259,676 | Do compilers optimize away calls to trivial functions made through pointers? | Say I have a function that takes a function pointer:
int funct(double (*f)(double));
And I pass it a function that doesn't actually do anything:
double g(double a) { return 1.0;}
//...
funct(g);
Will the compiler optimize out the calls to g? Or will this still have overhead? If it does have overhead, how much? Enou... | Newer versions of GCC (4.4 and later) can inline and optimize a known function pointer using the option -findirect-inlining. This only works when GCC also knows all of the code that uses the pointer.
For example, the C library function qsort will not benefit from this optimization. The compiled machine code for qsort i... |
6,259,557 | 6,259,595 | mq_notify only starts one thread | I am trying to use the mq_notify call to initiate a thread with POSIX message queues. Everything seems right but I only get one thread and it process all messages but it never terminates. I was under the impression I would get new threads to process with and this doesn't seem right.
| First, mq_notify() will only start one thread at a time. Second, threads are not started each time a message is put in the queue; they are only started when a queue that has been empty gets a new message. Third, mq_notify() is a one-shot deal. Once a thread is fired off, if you want to fire a new one the next time a... |
6,259,889 | 6,263,558 | Equivalent fread using ifstream | I want to use ifstream to read n blocks of data like fread, is there a way to do implement similar functionality in C++ using ifstream?
I tried to load the TGA file, and its header looks like:
struct TgaHeader {
char identSize;
char colorMapType;
char imageType;
unsigned short colorMapStart;
unsign... | As the comments under the question say, you want basic_istream<>::read() and to use size * count instead of the two separate arguments of fread().
|
6,260,049 | 6,260,081 | Telling the scene manager you are ready to switch scenes? | Right now for my game, I have a scene manager and it runs a scene. What it does is send event messages to the scene such as render, input, etc. This has allowed me to make the scene unaware of the scene manager. I would now like the scene to be able to send the scene manager a message saying which scene it would like t... | One way is to have the scene manager pass in NOT a reference to itself, but a reference to a smaller object that only supports the small number of methods needed for the particular messages to pass.
This could be an abstract class (aka "interface") which the scene manager implements, or a separate object.
And if you're... |
6,260,316 | 6,260,337 | polymorphism and encapsulation of classes | I'm trying to take advantage of the polymorphism in c++, but I'm from a c world, and I think what I've done could be done more cleverly in a OOP way.
I have 2 classes that has exactly the same public attributes, and I want to "hide" that there exists 2 different implementations. Such that I can have a single class wher... | There are many ways to do it. Through a Factory for example.
But to keep it simple - make a base abstract class that defines the interface, and derive your classes from it to implement the functionality. Then you only need to make the distinction once, when you create the class, after that you don't care, you just call... |
6,260,421 | 6,260,433 | Variant of defining a namespace and the meaning of __visibility__ | Today, while seeing preprocessed code of <iostream> (g++ 4.4.1), I saw a line which is quite unusual for me syntactically.
namespace std __attribute__ ((__visibility__ ("default"))) {
// ...
}
I have questions for that particular line:
What's __attribute__ and what it's
doing after std ? (new syntax !)
How the double... | __attribute__ is a gcc-specific language extension. It lets you alter the declaration of a function, namespace, or other entity in ways that aren't directly supported by the standard C++ language.
C++0x adds language support for attributes, though the syntax is different and most attributes are still implementation-sp... |
6,260,428 | 6,260,512 | whats the difference in define an object's member a value, a pointer or a reference | I'm new to C++, and are confused about sth
I'm going to define a class, and when should I define a member a pointer? or when should I define a member a value? or when should I just define it as a reference?
what confused me is when I read the book TCPL 24.3.3
It said that
"The pointer solution should be used when ther... | "The pointer solution should be used when there is a need to change the pointer to the ‘‘contained’’ object during the life of the ‘‘containing’’ object"
Pointers can be pointed to different object types.
References are just alias of types and cannot be bound to other types. They remain alias to the object to which ... |
6,260,600 | 6,260,709 | Should I use std::for_each? | I'm always trying to learn more about the languages I use (different styles, frameworks, patterns, etc). I've noticed that I never use std::for_each so I thought that perhaps I should start. The goal in such cases is to expand my mind and not to improve the code in some measure (readability, expressiveness, compactness... | There is an advantage to using std::for_each instead of an old school for loop (or even the newfangled C++0x range-for loop): you can look at the first word of the statement and you know exactly what the statement does.
When you see the for_each, you know that the operation in the lambda is performed exactly once for ... |
6,260,616 | 6,264,375 | Using Lua to modify an XML string from C++ | In my C++ app, I have a string which contains XML data. Let's say I have an attribute Number1 and an attribute Number2.
I want to send that string to a Lua script and have it return a modified XML string. Let's say it adds a new attribute Product with the value of Number1 and Number2.
Is that easily done using C++/Lu... | There are several methods to work with XML data listed at the Lua Users Wiki. The better options involve calls back to C (e.g. LuaXML and LuaExpat) so this only makes sense to do if there are other reasons to use Lua beyond just parsing XML.
|
6,260,798 | 6,260,825 | Java create .dll file | I want to create .dll with java jni. My .cpp file refers to an external .lib for a .dll . When I compile this file (with cl command) I get error:
LNK2019: unresolved external symbol "__declspec(dllimport) unsigned long __stdcall ConnectDevice(char const *, unsigned long)"
(__imp_?ConnectDevice@... | Yes, you can. You can directly link to it, by putting this into one of your .c/.cpp files:
#pragma comment(lib,"libname")
or specifying the lib on the command line (unusual for MSVC), or in the IDE options.
What's more tricky is making sure that your DLL is found. If both DLL's are kept in the same folder, and SetDllD... |
6,260,883 | 6,260,913 | C++ Function receiving an enum as one of its parameters | I am trying to make a function receive an enum as one of its parameters. I had the enum as a global but for some reason my other files couldn't change the enum. so I was wondering how do you set an enum as an argument for a function like,
function(enum AnEnum eee);
or is there a better way to solve the above problem? ... | If you want to pass a variable that has a value of one of the enums values, this will do:
enum Ex{
VAL_1 = 0,
VAL_2,
VAL_3
};
void foo(Ex e){
switch(e){
case VAL_1: ... break;
case VAL_2: ... break;
case VAL_3: ... break;
}
}
int main(){
foo(VAL_2);
}
If that's not what you mean, please clarify.
|
6,260,917 | 6,261,198 | Why isn't there any compiler error when a return statement is not present? | Unlike Java, in C/C++ the following is allowed:
int* foo ()
{
if(x)
return p;
// What if control reaches here?
}
This often causes crashes and it is hard to debug problems. Why doesn't the standard enforce to have a final return for non-void functions? (Compilers generate an error for a wrong return value.)
I... | It is not allowed (undefined behaviour). However, the standard does not require a diagnostic in this case.
The standard doesn't require the last statement to be return because of code like this:
while (true) {
if (condition) return 0;
}
This always returns 0, but a dumb compiler cannot see it. Note that the standard... |
6,260,929 | 6,260,994 | Dev-C++ - [Build Error] [main.o] Error 1 | Im running into big trouble with my compiler Dev-C++, every time i compile any project, whether it is 1 im working on, or a completely fresh 1 I get the same error every single time, I have been on the bloodshed forums and IRC channel but Im not getting anywhere with it... at the moment and every project I try to compi... | Have you looked at this thread? Specifically the first post on this page.
|
6,260,989 | 6,262,142 | When do casts call the constructor of the new type? | What are the rules to determine whether or not a particular static_cast will call a class's constructor? How about c style/functional style casts?
| Any time a new object is created, a constructor is called. A static_cast always results in a new, temporary object (but see comment by James McNellis) either
immediately, or through a call to a user defined conversion. (But in
order to have an object of the desired type to return, the user defined
conversion operator... |
6,261,201 | 8,417,851 | How to find memory leak in a C++ code/project? | I am a C++ programmer on the Windows platform. I am using Visual Studio 2008.
I usually end up in the code with memory leaks.
Normally I find the memory leak by inspecting the code, but it is cumbersome and is not always a good approach.
Since I can't afford a paid memory leak detection tool, I wanted you guys to su... | Instructions
Things You'll Need
Proficiency in C++
C++ compiler
Debugger and other investigative software tools
1
Understand the operator basics. The C++ operator new allocates heap memory. The delete operator frees heap memory. For every new, you should use a delete so that you free the same memory you allocated:
ch... |
6,261,375 | 6,261,438 | How to declare data members that are objects of any type in a class | In this piece I'm trying to declare in Class B a list that can hold objects of Class A of any type, such as A<int>, A<double>, A<float>. I intend to add A objects to the list during runtime:
#include <list>
template <class T> class A {};
class B {
template<class T> std::list<A<T>*> objects;
};
It seems like maki... | That's just not how C++ works. If you want to group different objects together, they need to have at least some relation. Being instantiations of the same class template doesn't imply that they are related, they're completely distinct types. If you want a list of A<T>*s, better make a list of base-class pointers and fo... |
6,261,496 | 6,266,590 | Find menu item based on mouse position in C++ | I am trying to get the menu item from another application.
I can do this by manually getting the handle to the main menu and loop through its sub menu. But it is very difficult to find out how many levels of sub menus are there for a given menu. For example if we look at outlook view menu some thing like this, View -> ... | I suspect that what you're trying to achieve is more or less made impossible by how the menu system in windows is designed.
Note that there might be some non-conventional ways around this, however I doubt you'll find such a solution to carry less amount of work than your current strategy of traversing the menu hierarch... |
6,262,184 | 6,263,771 | Win32 threads producer updating a consumer thread | I am trying to use a class based implementation of Win32 threads to create a Producer thread and a Consumer thread. Information of type int x in the consumer is updated by the producer.
Producer and Consumer both inherit from IRunnable
struct IRunnable {
virtual unsigned long run() = 0;
virtual void stop() = ... | In first try block you are assigning Consumer instance to newly created local variable Consumer *obj1 instead of using existing variable that was created just before try block. Try something like this instead:
Consumer *obj1=0;
Thread *consumerThread=0;
try {
// create the threadable object first
obj1 = new Co... |
6,262,189 | 6,262,260 | Cannot read simple binary integers from file? (C++) | My code is simply as this:
UPDATED:
#include <iostream>
#include <fstream>
using namespace std;
int main(int argc, char **argv)
{
ifstream r("foo.bin", ios::binary);
ofstream w("foo.bin", ios::binary);
int i;
int ints[10] = {0,1,2,3,4,5,6,8,9};
w.write((char*)&ints, sizeof(ints));
int in_ints[10];
r.r... | try w.flush() or w.close() before r.read. the problem is when you write it usually bufferes text and doesn't save it in file. so there is nothing realy in file for r.read.
|
6,262,237 | 6,262,329 | How to break a video into frames using OpenCV over C++ | I am really new to openCV and I would like to break a video file that I have (*.avi) into separate frames.
Does anyone know how to do it?
Thanks!!
| Take a look at cvCaptureFromFile, cvQueryFrame and cvSaveImage ! They'll do everything you need.
|
6,262,712 | 6,262,784 | c++ member function pointer problem | I'm new to c++ . I want to know about object pointer and pointer to member function . I wrote a code which is following:
code :
#include <iostream>
using namespace std;
class golu
{
int i;
public:
void man()
{
cout<<"\ntry to learn \n";
}
};
int main()
{
golu m, *n;
void golu:: *t =&golu::man();... | Two errors corrected here:
int main()
{
golu m, *n;
void (golu::*t)() =&golu::man;
n=&m;
(n->*t)();
}
you want a pointer to function
the priority of the operators is not the one you expected, I had to add parenthesis. n->*t(); is interpreted as (n->*(t())) while you want (n->*t)();
|
6,262,876 | 6,272,027 | Bulk loading of data with libpqxx | I need to bulk load a large amount of data (about 7.000.000 entries) into a PostgreSQL database using libpqxx. I have read the documentation on how to populate the database, but I am not sure on how to use this in my case. First I cannot use files, so a COPY on the database is out of question. Also the database and the... | There are a pg_index and pg_constraint tables, which references indexes and constraints. (The former requires a join with pg_class to get the full details.) See the pg_catalog for the gory details.
You can use the latter to fetch the needed index definitions and so on after the mass-inserts/updates.
|
6,262,914 | 6,262,941 | maximum size of std::vector | I am using vector in my code
std::vector<CEventLogInfo >
class CEventLogInfo
{
// date and time
unsigned short m_sMonth;
unsigned short m_sDay;
unsigned int m_nYear;
unsigned short m_sHour;
unsigned short m_sMin;
unsigned short m_sSec;
unsigned long m_nGatewayMa... | Your problem isn't the size of the vector (while there are practical limits, you're nowhere near them). It is most likely due to some bug in your code that gets exposed when you create more objects.
I would recommend examining the stack trace at the point of the crash, and perhaps adding it to your question. Another go... |
6,263,044 | 6,263,182 | Idiomatic C++ for remove_if | I have this class
class Point2D
{
public:
bool isValid();
// ...
private:
double x_, y_;
};
I have a std::vector< Point2D > and I would like to remove the invalid points, now I do like this:
bool invalid ( const Point2D& p )
{
return !p.isValid();
}
void f()
{
std::vector< Point2D > points;
// fill points
poin... | Try this:
points.erase(std::remove_if(points.begin(),
points.end(),
std::not1(std::mem_fun_ref(&Point2D::isValid))),
points.end());
|
6,263,262 | 6,263,320 | How can I force MinGW to use tr1 namespace? | I'm using MinGW 4.5.2 and I'd like to use unordered_map from the tr1 namespace, not the one from std namespace that is enabled by passing -std=c++0x. I'm sure this can be done since there are two unordered_map files, and one is in the tr1 sub-directory.
Clarification:
I'm also compiling this code with msvc10 and it sup... | Include <tr1/unordered_map> and use std::tr1::unordered_map<>.
EDIT:
I'm also compiling this code with msvc10 and it supports it in both namespaces but only in one location. So I'd like to make it compile with both compilers with changing as least as possible.
To make it compile with both compilers you can use someth... |
6,263,824 | 6,272,688 | unordered_map and virtual template | The problem is: I want to use unordered_map to store keys and values, where the key can be either class A or class B, depending on the users options. Both classes A and B inherit from the same class P.
class A: public P {...}
class B: public P {...}
I would like to define the map with the abstract P class and later, ... | Here's an example how you can make the map keyed on P* but still use different implementations in the derived classes:
struct P
{
virtual size_t hash_self() const = 0;
virtual bool equal(const P &) const = 0;
};
struct A : public P
{
inline bool operator==(const A & other) const { return false; /*Implement!*/}
... |
6,263,829 | 6,263,870 | Receive packet by packet data from TCP socket? | I have a tcp socket on which I receive video stream. I want to receive data as packet by packet from socket so that I could remove the packet header and keep the only stream data. How can I do this??
any help will be appreciated.
| You can't. TCP doesn't work with packets / messages etc. TCP works with bytes. You get a stream of bytes. The problem is that there's no guarantee reagarding the number of bytes you'll get each time you read from a socket. The usual way to handle this:
When you want to send a "packet" include as the first thing a leng... |
6,263,909 | 6,264,110 | Using C MPI syntax in a C++ application | I am developing a C++ MPI application. I have some existing code that is a C MPI application which partly do what I want, so I should be able to copy some of the code (or rewrite it in a cleaner C++ way) into my new program. Since the C++ interface to MPI is being deprecated (and it is much harder to find documentation... | There is no harm in using a C API from a C++ application. Many popular APIs are written in C (the Windows API comes to mind as an example. Or POSIX. Or SQLite, zlib, Python or dozens and dozens of others).
So if that seems like the most convenient solution, go ahead and use the C API. It should be fairly easy to write ... |
6,264,031 | 6,264,507 | Why does the compiler try to instantiate a template that I don't actually instantiate anywhere? | Updated below.
The following is the entire code I have in my main.cpp:
template<class T>
struct other_traits;
template<class T>
struct some_traits{
typedef decltype(&T::operator()) Fty;
typedef typename other_traits<Fty>::type type;
};
int main(){
}
But I get the following errors with Visual Studio 2010 whil... | It seems to be a Bug (if there is not special flag set as mentioned below).
Following is an excerpt from Oracle website for C++ templates:
7.2.2
The ISO C++ Standard permits
developers to write template classes
for which all members may not be
legal with a given template
argument. As long as the illegal
memb... |
6,264,137 | 6,264,527 | std::cin.putback() and "wake up" it | I have threads in my program and I want to put character into stream and read it in another thread, but after std::cin.putback() I need to write something from keyboard to "wake up" std::cin in function main. Can I do something to read automatically?
| That's not how streams work. The std::cin reads data that come from outside your program to standard input and the putback only allows keeping a character that you actually just read back to the buffer for re-parsing next time you invoke operator>> (or get or getline or other read method).
If you want to communicate be... |
6,264,249 | 6,264,256 | How does the compilation/linking process work? | How does the compilation and linking process work?
(Note: This is meant to be an entry to Stack Overflow's C++ FAQ. If you want to critique the idea of providing an FAQ in this form, then the posting on meta that started all this would be the place to do that. Answers to that question are monitored in the C++ chatroom... | The compilation of a C++ program involves three steps:
Preprocessing: the preprocessor takes a C++ source code file and deals with the #includes, #defines and other preprocessor directives. The output of this step is a "pure" C++ file without pre-processor directives.
Compilation: the compiler takes the pre-processor'... |
6,264,264 | 6,265,715 | Question About The C++ Programming Language | In Chapter 24.3.4 of the book The C++ Programming Language it said that
class Cfield : public Field{ /*...*/ }
This expresses the notion that a
Cfield really is a kind of Field,
allows notational convenience when
writing a Cfield function that uses a
member of the Field part of the
Cfield, and - most import... | Let's give a concrete example:
struct Field {
Field(char const* s): string(s) {}
char const* string;
};
struct CField: Field {
CField(char const* s): Field(s), length(s ? ::strlen(s) : 0) {}
std::size_t length;
};
This is a very basic kind of string, that does not allow modification of the string it refers to... |
6,264,433 | 6,264,881 | Segfault on set::insert | I experience a segfault after the following line:
this->my_set.insert(my_string);
The set has been initialized and it contains std::string.
The inserting string is not referring to a dandling pointer and it's null-terminated.
All the other strings contained in the set are not null and terminate with '\0'.
This is the... | Since you stated that the code is multi-threaded without locks, this is probably the result of a race condition. (At least a race condition may result in the exact same stack trace.)
Use proper locks to ensure correct execution. For example, if you are using OpenMP, then change the code you’ve shown us to:
#pragma omp ... |
6,264,449 | 6,265,006 | FormatMessage Fails with error code 317 | When I executed the following code piece it fails with error code 317. How can solve the issue? We are using Unicode Character Set for the project
char* pszMessgeBuffer = NULL;
FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS,
NULL,
... | Using the error code lookup tool from Visual Studio, 317 is described as
The system cannot find message text
for message number 0x%1 in the message
file for %2.
This means that a message description does not exist in the system for the previous error code. The MSDN documentation for FormatMessage with flag FORMA... |
6,264,906 | 6,265,066 | How to generate a time-stamp for HTTP-Header If-Modified-Since from QDateTime? | I want to set an If-Modified-Since-header on a request and take the time from the timestamp on the file. So I extracted the timestamp into a QDateTime. I could generate something looking similar to the date-format HTTP uses, but my server and my client use different time-zones. Is there a way to get the timezone-string... | I think this will do:
QString modificationDate = fileinfo.lastModified().toUTC().toString("ddd, dd MMM yyyy hh:mm:ss") + "GMT";
|
6,264,995 | 6,265,104 | Why wouldn't a search from glGetString(GL_EXTENSIONS) work correctly? | I read this page:
http://www.opengl.org/wiki/GlGetString
For example, if the extension
GL_EXT_pixel_transform_color_table is
listed, doing a simple search for
GL_EXT_pixel_transform will return a
positive whether or not it is defined.
How is that possible since its space separated? Why dont you just put a spa... | What if the extension you are looking for is listed last? Then it will not be followed by a blank.
|
6,265,164 | 6,265,360 | Visual Studio 2010: C/C++ global include and lib folder | How to make user include and lib folders globally and permanently available to all projects? In Visual Studio 2008 it is Tools -> Options -> Projects and Solutions -> VC++ Directories. In 2010 it says deprecated... blah blah... instead use property sheets... click '?' for help.... Click and it takes you to a web page a... | I found this article helpful.
|
6,265,240 | 6,265,313 | Determining value of preprocessor token | How can I tell what the value of the __GNUC__ definition is on my C++ compiler?
| You can get all the GCC predefined macros with this:
g++ -dM -E - < /dev/null
A quick grep will get you what you want.
|
6,265,492 | 6,265,738 | How to decide on stack vs heap vs boost::pool allocation in a case like this? | I have a class that uses boost::variant to store a double or a string, like this :
class value
{
boost::variant<double, std::string> val;
};
It's supposed to be an immutable value type for a toy interpreter I'm playing with.
At first it seemed like a good idea to pass it around by const reference and return by valu... |
What should I do in this case and why?
As always, write the program so that it is easiest to understand. If profiling later uncovers that this is indeed a problem, you can always turn value::val into some dynamically allocated object later. (Of course, this presumes val to be abstracted away well enough for this to... |
6,265,555 | 6,303,047 | call avio_open function with non-english filename is invalid | i have been writing unicode based program with libav and i wanna make some file through libav with filename "中.mp4".
this filename is not english, and when i call, function return positive integer(not fail).
but there is "ѱ۰.mp4" instead of "中.mp4". (invalid file name.)
what's the matter?
char * szFilenameA = 0;
#ifde... | finally!
it's because of charset.
convert ansi filename to UTF8 and then it works fine.
int ANSIToUTF8(char *pszCode, char *UTF8code)
{
WCHAR Unicode[100]={0,};
char utf8[100]={0,};
// read char Lenth
int nUnicodeSize = MultiByteToWideChar(CP_ACP, 0, pszCode, strlen(pszCode), Unicode, sizeof(Unicode));
//... |
6,265,592 | 6,265,665 | passing array on the heap and on the stack to function | I have a simple c++ question concerning passing an array to a function foo(). Assume I have two arrays A and B:
double* A=new double[3];
and
double B[3];
When I pass both to the function
foo(double* A; double *B)
which is intended to manipulates both arrays. However by executing
foo(A,B)
foo is acting on a copy of ... |
foo is acting on a copy of A and only the changes to B remain when leaving foo().
What exactly are you doing inside of foo? Changes to the objects themself should be visible outside of foo in both cases. If you are trying to change the value of pointer A, it won't be visible outside of foo - a copy of the pointer is... |
6,265,791 | 6,265,921 | C++ - Identifying a family of polymorphic classes without introducing tight coupling | Suppose I have an abstract base class called Component, which is the root of a hierarchy of GUI components. In such a case, we might have two subclasses, Button and Label, both of which are also abstract classes and exist as the root of their own respective hierarchies of concrete classes.
Concrete classes inheriting f... |
I need to identify them as being either Buttons or Labels.
That's your problem. That assumption, as common as it might be, is usually wrong.
Why do you believe that you need to identify them?
At what stage in your code is that knowledge important?
You can probably get around the "requirement" to know their concrete... |
6,265,797 | 6,266,524 | Handle connection/disconnection of many signals/slots with boost::signals2 | I've started using boost::signals2 instead of my old signals-code. I'm having a problem with administering multiple connections though. Here's my problem:
I have many instances of the class Person:
class Person {
public:
void SetName (string new_name)
{
name = new_name;
NameChange (name);
}
... | What about:
class PeopleBrowser
{
public:
void AddPerson (Person& p)
{
name_change_connections[&p] = p.NameChange.connect(...);
}
void RemovePerson(Person& p)
{
name_change_connections.erase(&p);
}
private:
std::map<Person*, boost::signals2::scoped_connection> name_change_c... |
6,265,851 | 6,265,919 | typedef syntax with member function pointers | according to MSDN the typedef syntax is:
typedef type-declaration synonym;
Very easy:
typedef int MY_INT;
But how the heck does the member-function-pointer typedefs comply to this rule?
typedef int (MyClass::*MyTypedef)( int);
100% confusion – the synonym (MyTypedef) is in the middle?
Can someone please explain wha... |
the synonym (MyTypedef) is in the middle??
Its not in the middle. Just forget member-function for a while, see how a function pointer is defined:
int (*FuncPtr)(int);
And this is how you would typedef it:
typedef int (*FuncPtr)(int);
Simple! The only difference is, in the typedef FuncPtr becomes a type, while in... |
6,265,913 | 6,266,326 | Best way to make incremental updates to a texture? (Render to Texture) | I would like to render to a texture in OpenGL but make changes to the texture incrementally.
Here's how I imagine the process:
Clear Color & glViewport() to texture size
Draw original texture (glOrtho or something), how can I copy the original with perfect quality?
Draw incremental changes
Clear again, set viewport t... | You have two choices. If your hardware doesn't support FBOs, you will have to do like you've written. To draw the original texture, just draw a screen-sized quad with [0,1] texture coordinates. Make sure to use GL_NEAREST as filtering mode and GL_CLAMP_TO_EDGE as wrapping mode, to get an exact copy of the image. Then d... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.