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 |
|---|---|---|---|---|
3,407,003 | 3,407,475 | Where to find information on Embedded C++? | I want to find information on "C++ programming in an embedded platfrom".
I googled it but I was unable to find sufficient information on that topic. What exactly I want to find is How exactly C++ is useful in an embedded environment with detailed description and examples (if they are available)
Can anyone please sugg... | I would recommend reading books related to embedded C, for example Embedded C by Michael J.Pont, 2002 or Programming Embedded Systems in C and C++ by Michael Barr, 1999 (http://book.opensourceproject.org.cn/embedded/embeddedc/).
In a nutshell, all embedded systems are started with C/assembler. C++ can be used also, bu... |
3,407,012 | 3,407,254 | Rounding up to the nearest multiple of a number | OK - I'm almost embarrassed posting this here (and I will delete if anyone votes to close) as it seems like a basic question.
Is this the correct way to round up to a multiple of a number in C++?
I know there are other questions related to this but I am specficially interested to know what is the best way to do this i... | This works for positive numbers, not sure about negative. It only uses integer math.
int roundUp(int numToRound, int multiple)
{
if (multiple == 0)
return numToRound;
int remainder = numToRound % multiple;
if (remainder == 0)
return numToRound;
return numToRound + multiple - remainder;... |
3,407,141 | 3,419,071 | Help with InternetOpenUrl and InternetReadFile in <WinInet.h> API | I am trying to simply access a page using the WinInet APIs. Once I access it, I'd like to be able to read the contents into a string. I've already initialized the root node. Here's what I got so far:
HINTERNET hChildURL = InternetOpenUrl(hInternetRoot,
LPCTSTR(CString("http://www.g... | Well, you just read it in one chunk at a time:
HINTERNET Request = InternetOpenUrl(...);
if(Request != NULL)
{
BYTE Buffer[8192];
DWORD BytesRead;
while(InternetReadFile(Request, Buffer, 8192, &BytesRead) && BytesRead != 0)
{
// do something with Buffer
}
InternetCloseHandle(Request);
... |
3,407,253 | 3,408,613 | How do I put a checkmark on a menu item that has submenu items. (Visual studio 2008 C++/MFC) | I have a menu that contains submenus.
eg:
Item1
Item2
Item3
item A
Item B
Item3 has items under it.
At any given time 1, 2, or the items under 3 should be checked. Since I don't have an ID for Item3 I have to use the MF_BYPOSITION indicator when I try to set a check on Item3 to indicate one of its children has a ... | I've done this before for popup menus. You will need to access the submenu by position, instead of ID. Using your example above, Item 3 would be at position 2:
CMenu popupMenu;
popupMenu.LoadMenu(IDR_MYMENU);
popupMenu.GetSubMenu(0)->CheckMenuItem(2,MF_BYPOSITION|MF_CHECKED);
.
.
.
popupMenu.GetSubMenu(0)->TrackPopupMe... |
3,407,409 | 3,407,630 | Design pattern to refactor switch statement | I have something like the following in the header
class MsgBase
{
public:
unsigned int getMsgType() const { return type_; }
...
private:
enum Types { MSG_DERIVED_1, MSG_DERIVED_2, ... MSG_DERIVED_N };
unsigned int type_;
...
};
class MsgDerived1 : public MsgBase { ... };
class MsgDerived2 : pub... | Pull Types and type_ out of MsgBase, they don't belong there.
If you want to get totally fancy, register all of your derived types with the factory along with the token (e.g. 'type') that the factory will use to know what to make. Then, the factory looks up that token on deserialize in its table, and creates the right... |
3,407,493 | 3,434,761 | Floating point C++ compiler options | preventing a/b -> a* (1/b) | I'm writing realtime numeric software, in C++, currently compiling it with Visual-C++ 2008.
Now using 'fast' floating point model (/fp:fast), various optimizations, most of them useful my case, but specifically:
a/b -> a*(1/b) Division by multiplicative inverse
is too numerically unstable for a-lot of my calculations.... | (Weird) solution which I have found: whenever dividing by the same value in a function - add some epsilon:
a/b; c/b
->
a/(b+esp1); c/(b+esp2)
Also saves you from the occasional div by zero
|
3,407,779 | 3,407,866 | Can someone decipher whether timeGetTime() or QueryPerformanceCounter/QueryPerformanceFrequency has lower overhead or/and accuracy? | The idea is that an existing project uses timeGetTime() (for windows targets) quite frequently.
milliseconds = timeGetTime();
Now, this could be replaced with
double tmp = (double) lpPerformanceCount.QuadPart/ lpFrequency.QuadPart;
milliseconds = rint(tmp * 1000);
with lpPerformanceCount.QuadPart and lpFrequency... | The accuracy of timeGetTime() is variable, based on the last used timeBeginPeriod. It will never be better than one millisecond. QueryPerformanceCounter is variable too, depending on hardware support. It will never be worse than about a microsecond.
Neither of them have notable overhead, QPC is probably a bit heavie... |
3,407,852 | 3,415,965 | Is it possible to match templated base in template specializations? | I could of course use is_base if the base class where not a template. However, when it is, I just don't see any way to generically match any derived type. Here's a basic example of what I mean:
#include <boost/mpl/bool.hpp>
template < typename T >
struct test_base
{
};
template < typename T >
struct check : boost::... | You just need to tweak your test a bit:
#include <iostream>
#include <boost/mpl/bool.hpp>
template < typename T >
struct test_base
{
};
template < typename T >
struct check_
{
template<class U>
static char(&do_test(test_base<U>*))[2];
static char(&do_test(...))[1];
enum { value = 2 == sizeof do_test(s... |
3,407,908 | 3,407,945 | How to identify decent C++ developers in an informal gathering | I am going to an annual Free software/Open Source convention. This event is very community oriented and the hallway meetings are very informal. Since the company I currently work for is looking for C++ developers (in a Linux environment), I printed on a T-shirt the words "We are recruiting C++ developers" in large lett... | I'd just ask them about what projects they've done in C++. If they have done anything non-trivial, and sound like they know what they are talking about, then they may be worth bringing in for a real interview.
I might ask what other languages they use, and when/how they learned C++. If they've been doing C++ for a wh... |
3,408,469 | 3,408,687 | Initializing static pointer in templated class | Consider a class like so:
template < class T >
class MyClass
{
private:
static T staticObject;
static T * staticPointerObject;
};
...
template < class T >
T MyClass<T>::staticObject; // <-- works
...
template < class T >
T * MyClass<T>::staticPointerObject = NULL; // <-- cannot find symbol staticPointerObject... | I have found two solutions. Neither of them are 100% what I was hoping for.
Explicitely initialize the specific instance, e.g.
int * MyClass<int>::staticPointerObject = NULL;
This is not convinient especially when I have a lot of different types.
Wrap the pointer inside the class, e.g.
template < class T >
... |
3,408,473 | 3,408,708 | Windows Mobile 6.5.3 preprocessor | Is there a preprocessor value I can use to detect when the program is being compiled for Windows Mobile 6.5.3? For example, I can use #if (_WIN32_WCE >= 0x501) to compile the code for Windows Mobile 5 and later, or #if _WIN32_WCE >= 0x502 to compile the code for Windows Mobile 6.
There are some new API that exist in W... | The version refers to the Windows CE version, which I don't believe matches the Windows Mobile version.
From what I recall, this version define is in the form of 0xXYZ where X is the major version, Y is the minor version, and Z is the revision. So if 0x502 refers to Windows Mobile 6 or later, it would mean Windows Mob... |
3,408,804 | 3,408,973 | c++ operator= method for const references | I am writing class with a const reference like this:
class B;
class foo {
const B& b;
foo(const B& newb): b(newb) { }
void operator=(const foo & foo2) {
// This does not work
foo.b = foo2.b;
}
};
I am trying to define a working operator= Obviously = does not work since I am not allowd to chan... | The term you're looking for is "rebind." As in "is it possible to rebind a reference?" The answer is "no, references are defined as not being rebindable." But you can use a pointer and change what it points to:
class B;
class foo {
B* b;
foo(const B& newb)
{
b = &newb;
}
void operator=... |
3,408,864 | 3,408,998 | How can I convert a binary file to another binary representation, like an image | I want to take a binary file (exe, msi, dll, whatever) and be able to actually "see" the binary code or whatever base I'd like (hexadecimal whatever). Figured the easiest way would be just to output the code into a txt so I can examine it.
Whats the best and easiest way to do this? Basically I am looking to convert the... | Here's a way to pack the bytes into an image... the fun part is if you record the original file length and use a lossless image format you could safely extract the binary data later.
Packed as ARGB...
var exefile = Directory.GetFiles(".", "*.exe").First();
var fi = new FileInfo(exefile);
var dimension = (int)Math.Sqrt... |
3,409,105 | 3,409,474 | C++ & DirectX - setting shader | Does someone know a fast way to invoke shader processing via DirectX?
Right now I'm setting shaders using D3DXCreateEffectFromFile calls, which create shaders in runtime (once per each shader) from *.fx files.
Rendering part for every object (every patch in my case - see further) then means something like:
// ---------... |
Actual geometry rendering takes ~35% and postprocessing - 5% of total rendering time
If you want to profile shader performance you need to use NVPerfHud or something similar. Using CPU profiler and measuring ticks is not going to help you - rendering is often asynchronous.
Do I need to implement my own shader contro... |
3,409,116 | 3,410,220 | Distribute prizes for a tournament system | I'm looking for a way to distribute a number across x units. I don't even know how to put this words so I'll give an example:
There's a tournament in which the total prize is $1000. I want that the top 20 winners/entrants will win something out of it.I need a mathematical algorithm/formula which will distibute it acros... | It's 1:15 AM here and I'm solving maths :)).
Using arithmetic progression.
I made all using defines so you can easily change them.
#include<iostream>
//using arithmetic progression
using namespace std;
FILE *g=fopen("output.out","w");
#define last_prize 10
#define total_prizes 20
int i;
float prizes[total_prizes+1];
fl... |
3,409,210 | 3,409,268 | Regex to parse C/C++ functions declarations | I need to parse and split C and C++ functions into the main components (return type, function name/class and method, parameters, etc).
I'm working from either headers or a list where the signatures take the form:
public: void __thiscall myClass::method(int, class myOtherClass * )
I have the following regex, which wor... | C++ is notoriously hard to parse; it is impossible to write a regex that catches all cases. For example, there can be an unlimited number of nested parentheses, which shows that even this subset of the C++ language is not regular.
But it seems that you're going for practicality, not theoretical correctness. Just keep i... |
3,409,234 | 24,673,186 | Format(line wrapping) constructor initializer list in Eclipse CDT | I tried to find a solution for now ~30min and couldn't find any.
I am trying to set up the code style in CDT so it gives me:
MyClass::MyClass() :
var1(1),
var2(2),
var3(3){
}
instead of
MyClass::MyClass() :
var1(1), var2(2), var3(3){
}
but I couldn't find an option to do so.
The only 'initializer list' op... | @Eric provides manual solution, but to make this setting auomatic, you need to edit eclipse preferences.
Click on:
Window -> Preferences
Go to:
C/C++ -> Code Style -> Formatter
Here, as first thing you have to create a new profile.
Select tab:
Line Wrapping
Go to:
Function declarations -> Constructor initializer list
... |
3,409,428 | 3,409,529 | Putting class static members definition into cpp file -- technical limitation? | one of my "favorite" annoyance when coding in C++ is declaring some static variable in my class and then looking at compilation error about unresolved static variable (in earlier times, I was always scared as hell what does it mean).
I mean classic example like:
Test.h
class Test
{
private:
static int m_staticVar;
... | Well, this is just the way it works. You've only declared the static member in the .h file. The linker needs to be able to find exactly one definition of that static member in the object files it links together. You can't put the definition in the .h file, that would generate multiple definitions.
UPDATE: C++17 can ... |
3,409,543 | 3,409,728 | Is it more efficient to use boost::asio::basic_stream_socket::async_read_some instead of boost::asio::async_read? | Is it better to use boost::asio::basic_stream_socket::async_read_some instead of boost::asio::async_read when it comes to high performance data throughput?
| boost::asio::async_read is a composed operation, which is well described in the documentation
This operation is implemented in terms
of zero or more calls to the stream's
async_read_some function, and is known
as a composed operation. The program
must ensure that the stream performs
no other read operations ... |
3,409,823 | 3,409,836 | what will be behavior of following code snippet? | What will be the behavior and output of the following code if i accidentally code so in C/C++,
float a = 12.5;
printf("%d\n", a);
printf("%d\n", *(int *)&a);
| Rubish and more rubish.
You would get something meaningful if you did the following though
printf("%d\n", (int)a);
|
3,409,926 | 3,409,944 | Why does stack overflow throw no error in Visual C++? | In Microsoft Visual C++ 2010 I created a program which delibrately causes a stack overflow. When I run the program using "start debugging" an error is thrown when stack overflow occurs. When I run it with "start without debugging" no error is thrown and the program just terminates silently as if it had successfully com... | C++ won't hold your hand as a managed enviroment does. Having a stack overflow means undefined behaviour.
|
3,410,218 | 3,410,232 | C++ location of main | If I put main on the top of the source file and invoke some custom functions, it will tell me that those functions are not found, but if I put main on the bottom of the source file, it will work.
Why? Is it because the compiler parse from top to bottom and breaks at the definiteion of main?
| It has nothing to do with main. C++ compilers work top to bottom, period.
Anything that you reference needs to be declared previously. The same goes for variables. In your case, you could do
void foo(); // <-- Forward declaration, aka prototype
int main() {
foo();
}
void foo() {
// Here is your foo implemen... |
3,410,324 | 3,410,707 | Linking Errors While creating a shared library | I currently have some C++ code that I want to compile into a shared library that I can dynamically link to a Java application during runtime using the Java Native Interface (JNI). The problem that I'm facing is - the C++ code that I'm trying to compile calls on another library itself, making use of a lot of classes and... | When you link a Windows DLL, you have to tell it where any symbols that it uses but does not define can be found. If you link against a static library, all the code for that library will be copied into your DLL. However, if you link against another DLL, the code for that library remains in the DLL, and all that is boun... |
3,410,514 | 3,410,745 | How to activate a window of an external application | I've used FindWindow to get a handle to a window of an external application. How can I use this handle to activate the window of the external application, if it is minimized or behind other applications on the windows desktop?
| To prevent focus-stealing (or at least make accidental focus-stealing harder), Windows puts up some roadblocks to one process bringing another process's window to the top.
Check MSDN for SetForegroundWindow (especially in the Remarks section) and AllowSetForegroundWindow.
You should either send a message to the process... |
3,410,637 | 3,410,714 | Mutually recursive classes | How do I implement mutually recursive classes in C++? Something like:
/*
* Recursion.h
*
*/
#ifndef RECURSION_H_
#define RECURSION_H_
class Class1
{
Class2* Class2_ptr;
public:
void Class1_method()
{
//...
(*Class2_ptr).Class2_method();
//...
}
};
class Class2
{
Class1* Class1_ptr;
... |
Forward-declare the classes (you could get away with forward-declaring only one of them, but for good form do both).
Forward-declare the methods (ditto).
class Class1;
class Class2;
class Class1
{
Class2* Class2_ptr;
public:
void Class1_method();
};
class Class2
{
Class1* Class1_ptr;
public:
void Class2_m... |
3,410,663 | 3,410,691 | Why does the following program give a error? | Why does the following program give a warning?
Note: Its obvious that sending a normal pointer to a function requiring const pointer does not give any warning.
#include <stdio.h>
void sam(const char **p) { }
int main(int argc, char **argv)
{
sam(argv);
return 0;
}
I get the following error,
In function `int ma... | This code violates const correctness.
The issue is that this code is fundamentally unsafe because you could inadvertently modify a const object. The C++ FAQ Lite has an excellent example of this in the answer to "Why am I getting an error converting a Foo** → Foo const**?"
class Foo {
public:
void modify(); // ma... |
3,410,688 | 3,410,716 | C++: Inheritance and Operator Overloading | I have two structs:
template <typename T>
struct Odp
{
T m_t;
T operator=(const T rhs)
{
return m_t = rhs;
}
};
struct Ftw : public Odp<int>
{
bool operator==(const Ftw& rhs)
{
return m_t == rhs.m_t;
}
};
I would like the following to compile:
int main()
{
Odp<int> od... | The problem is that the compiler usually creates an operator= for you (unless you provide one), and this operator= hides the inherited one. You can overrule this by using-declaration:
struct Ftw : public Odp<int>
{
using Odp<int>::operator=;
bool operator==(const Ftw& rhs)
{
return m_t == rhs.m_t;
... |
3,410,733 | 3,410,824 | Why is it dangerous to get rid of volatile? | In C++, volatile is treated the same way const is: passing a pointer to volatile data to a function that doesn't want the volatile modifier triggers a compile error.
int foo(int* bar) { /* snip */ }
int main()
{
volatile int* baz;
foo(baz); // error: invalid conversion from ‘volatile int*’ to ‘int*’
}
Why is ... | Not only can the compiler optimize away access to non-volatile variables, it can update them predictively/speculatively, as long as the sequential execution of the program is unaffected.
If spurious writes to your volatile variable don't break your design, it probably didn't need to be volatile in any context.
For exam... |
3,410,854 | 3,410,865 | C++: Using base class's private members in equality test | I would like the following to compile, but it does not:
template <typename T>
struct Odp
{
public:
operator*() const
{
return m_p;
}
T* operator->() const
{
return m_p;
}
T** operator&()
{
return &m_p;
}
private:
T* m_p;
};
struct Ftw : public Odp... | Odp overloads operator* to return m_p. You can invoke the operator on *this and rhs:
struct Ftw : public Odp<int>
{
bool operator==(const Ftw& rhs) const
{
return **this == *rhs;
}
};
The operator* overload is a bit unusual, however: it should probably return *m_p instead, since operator-> retur... |
3,410,857 | 3,410,957 | Need some help with C++ Trie data structures | I am trying to write a C++ function that matches whether a string is present in a dictionary . It can be a partial string or a complete string. SO I read each and every line into a trie
trie< std::string, int > dict;
dict.insert(make_pair(line,i++));
// when i search for a string it al... | If you're using this trie, this sample code indicates you need more template parameters in your declaration to tell it how to split up the keys so it can do the trie indexing and especially prefix searches:
trie< std::string, int, string_trie_e_access_traits<>, pat_trie_tag, trie_prefix_search_node_update> dict;
Also ... |
3,410,926 | 20,803,668 | Is there any website which offers C++ IDE to run the codes in the cloud? | Is there any website which offers C++ IDE to run the codes in the cloud? Something like this which is for Python and matlab (octave in fact);
| I'm not entirely sure what you are seeking. You speak about simply Running C++, like JSFiddle but for C++, but then you mention IDE implying more features than the basic "Run this code in the browser" options.
At any rate, Koding is a full suited "Cloud IDE", which can handle any language you want. It's basically an Ub... |
3,410,990 | 3,411,014 | LD_PRELOAD for C++ class methods | I need to interpose on a method call in a C++ program (the class resides in a separate shared library). I thought I could use LD_PRELOAD, but i am not sure how this would work (i only found examples of C functions): is there a way to setup interposition for a single method without copying over any code from the interpo... | It wouldn't be very portable, but you could write your interposing function in C and give it the mangled name of the C++ method. You would have to handle the this parameter explicitly, of course, but I think all ELF ABIs just treat it as an invisible first argument.
|
3,411,279 | 3,411,349 | Incremental Decision Tree C++ Implementation | Do anyone know any incremental implementation of decision tree classifier. Such that it could generate optimal decision tree classifier when you add new instance to training set with low computation and as quick as possible according existing decision tree classifier?
In other words I have an optimal decision tree clas... | The wikipedia article links to two codes. ITI is not open source, but the source is avalable, VMFL is open source and in C (mostly)
|
3,411,287 | 3,411,315 | Priority Queue Not Sorting | Im trying to implement my own Huffman Coding algorithm and the priority queue for the C++ STL does not seem to be working correctly. I am taking characters from a string and inserting them into a priority queue by order of their frequency in the string. The code compiles and runs without error, the only thing is the tr... | You are storing pointers in the priority_queue, so the elements are sorted by pointer value, not using your operator< overload.
You either need to store Node objects in the priority queue, or you need to write a custom comparison function for the priority queue that dereferences the stored pointers and compares the Nod... |
3,411,328 | 3,412,827 | API's similar to GLUTesselator? | I'm looking for an API that is open sourced and that can take contours of verticies as input and return verticies of triangles. I would also like it to support different winding rules. Thanks
| OpenSceneGraph has a GLU style tesselator, see http://www.openscenegraph.org/documentation/OpenSceneGraphReferenceDocs/a00854.html#_details for details.
Visualization Library also provides a tesselator, see http://www.visualizationlibrary.com/documentation/classvl_1_1_tessellator.html for further information.
Both libr... |
3,411,386 | 3,452,577 | Program won't run in NetBeans, but runs on the command line! | So, I'm starting a C++ class right now, and I've configured NetBeans (which I use normally for PHP and Java Development) to use the Cygwin compiler/debugger. This is my first structured experience with C++, and I'm running into a slight issue. When I attempt to run a program within NetBeans (F11 or the Green Triangle) ... | After tinkering a bit with the settings of my project in an attempt to fix it, it appears that the error was being caused by the Profiler in NetBeans. Since that only works on Linux/Solaris, and this is a Windows 7 box, disabling that caused no loss of functionality and solved the issue. Thanks for everyone who tried t... |
3,411,407 | 3,416,117 | Undefined reference problem when dynamic library is used | I was reading about static and dynamic libraries. To explore more I created three files 2 .cpp files and 1 .h file
demo.h
class demo
{
int a;
public:
demo();
demo(const demo&);
demo& operator=(const demo&);
~demo();
};
demo.cpp
#include "demo.h"
#include <iostream>
demo::demo():a()
{
std... | When compiling code for a .so (or .dll as you call it) that code needs to be position independent. Man gcc:
-shared
Produce a shared object which can then be linked with other objects
to form an executable. Not all systems support this option. For
predictable results, you must also specify the... |
3,411,438 | 3,411,466 | How do you declare a pointer to a function that returns a pointer to an array of int values in C / C++? | Is this correct?
int (*(*ptr)())[];
I know this is trivial, but I was looking at an old test about these kind of constructs, and this particular combination wasn't on the test and it's really driving me crazy; I just have to make sure. Is there a clear and solid understandable rule to these kind of declarations?
(ie: ... | The right-left rule makes it easy.
int (*(*ptr)())[];can be interpreted as
Start from the variable name ------------------------------- ptr
Nothing to right but ) so go left to find * -------------- is a pointer
Jump out of parentheses and encounter () ----------- to a function that takes no arguments(in case of C uns... |
3,411,439 | 3,411,476 | Is it possible to force an access violation when a specific address is accessed? | We have an array that is oversized for alignment purposes, such that off by one errors are not caught by the usual mechanisms.
Is it possible to protect a small, arbitrary region (16 bytes at the beginning and end of an array) in Windows, such that it causes an access violation? Language is C++.
| I believe that in the x86 architecture the finest granularity you can achieve in marking memory as protected is for a page (4K I think). You could set up the array such that the beginning or end falls across a page boundary (and have that page protected). But to have both ends fall across such boundaries would of cou... |
3,411,544 | 3,411,561 | std::fstream will not open current process's file, but open() will? | I am attempting to open the current process's executable file for read-write operations (I have additional data attached to the executable), however std::fstream will not open the file in ios::in | ios::out | ios::binary mode, even though open() will (with O_RDWR flag set).
Does anyone know why std::fstream will not op... | It most probably has to do with file sharing semantics. See this thread which deals with a similar question - and the answer there is "The concept of file protection, file sharing, file permissions is OS-specific, which is why it is not covered by standard C++".
|
3,411,570 | 5,048,274 | Receiving GLU_TESS_ERROR_5 from GLU Tesselator | Here is my issue. I'm tesselating complex, self intersection, multicontour polygons with hundreds of verticies. The GLU Tesselator crashes with null pointer 0x0000000 issue. It never ever crashes when I do not make self intersecting polygons. If it does not intersect, it will never crash no matter what the circumstance... | At least on Windows, GLU_TESS_ERROR_5 means that one of the coordinates was too large. Specifically, GLU requires that the coordinates are small enough to be multiplied together without overflow. The specification says that the limit is defined in the constant GLU_TESS_COORD_TOO_LARGE. If this constant exists, check th... |
3,411,646 | 3,411,691 | What happens when i throw an exception in c++ destructor? |
Possible Duplicate:
throwing exceptions out of a destructor
In C++ we should never throw an exception in the destructor . Does this code works as intended ?
struct a
{
~a( ) { }
};
struct b : public a
{
~b( )
{
throw 1;
};
};
bool c( )
{
a* d=new b;
try
{
dele... |
Does this code works as intended ?
Did you try running it yourself? Also have a look at this FAQ - according to that, yes, it will work in your simple case, but in general, you shouldn't do it. Again, it depends on how you define "work as intended" - the program will run without errors but you will possibly leak memo... |
3,411,815 | 3,411,827 | How to use a C++ string in a structure when malloc()-ing the same structure? | I wrote the following example program but it crashes with segfault. The problem seems to be with using malloc and std::strings in the structure.
#include <iostream>
#include <string>
#include <cstdlib>
struct example {
std::string data;
};
int main() {
example *ex = (example *)malloc(sizeof(*ex));
ex->data = "hel... | You can't malloc a class with non-trivial constructor in C++. What you get from malloc is a block of raw memory, which does not contain a properly constructed object. Any attempts to use that memory as a "real" object will fail.
Instead of malloc-ing object, use new
example *ex = new example;
Your original code can be... |
3,412,032 | 3,431,065 | How do you verify a public key was issued by your private CA? | I have created a CA cert, and used it to issue a public key.
At a date in the future, I need to verify that the certificate loaded was issued by my CA.
How do I do that with the OpenSSL API (c++)?
| I've reduced verify.c (in openssl/apps/) to the minimum functions required. Assumptions: cert and CA cert are both PEM format files. There are no CRLS or trusted list checks required.
Call verify() with the path to your cert and CA PEM files.
static int verify(const char* certfile, const char* CAfile);
static X509 *loa... |
3,412,074 | 3,412,089 | Corrupted Binary Files after Transfer libcurl | I am transferring a binary file (.exe) with FTP using libcurl, and saving it to a local file. The problem is that after the file is transferred, it is altered and is no longer a valid Win32 application, and doesn't run. Here's how I'm doing it:
CURL *curl;
curl = curl_easy_init();
FILE* f = fopen("C:\\blah.exe", "... | You forgot the binary flag.
This is the correct code:
FILE* f = fopen("C:\\blah.exe", "wb");
|
3,412,164 | 3,412,202 | references in c++ problem | I heard references in c++ can be intitalized only once but this is giving me 1 is my output and not returning any error!
struct f {
f(int& g) : h(g) {
h = 1;
}
~f() {
h = 2;
}
int& h;
};
int i() {
int j = 3;
f k(j);
return j;
}
| The destructor of f is called after the return value j is captured.
You might want something like this, if you wanted j to be 2:
int i( )
{
int j=3;
{
f k(j);
}
return j;
}
See C++ destructor & function call order for a more detailed description of the order of destruction and the retu... |
3,412,476 | 3,412,812 | C++ Templated Functor (based on Modern C++ Design) compile error | Based on chapter 5 (Generalized Functors) from the book "Modern C++ Design,"
I'm trying to write a Functor template. Before asking me "why don't I just use Boost's bind or Loki straight up?" the simple answer is "because I want to learn."
That being said, I have followed the book, and also used the example code as a re... | This problem has been solved.
It turns out that in FunctionHandler, having the apply() functions be virtual was causing the problems. Once I removed the virtual keywords, everything went smoothly.
I'm still not quite sure WHY this changed things so drastically, but it solved the problem.
My best guess to the reason is... |
3,412,623 | 3,412,727 | How to convert a sorted std::list of std::pair to a std::map | I have got a std::list< std::pair<std::string,double> >, which I know is sorted according to the std::string element.
Since I would like to do a lot of std::find_if based on the std::string element, I believe a std::map<string,double,MyOwnBinaryPredicate> with lower_bound and upper_bound would be more adequate.
The fa... | If you already have a sorted list, which is sorted according to the predicate Predicate, you can just do the following:
std::list< std::pair<std::string, double> > sorted_list;
std::map<string, double, Predicate> map(sorted_list.begin(), sorted_list.end());
The map constructor has linear time complexity if your list i... |
3,413,044 | 3,413,386 | Declaring and defining a function object inside a class member function | I wonder if and how it is possible to define a function object inside a classes member function to use it directly with, for example, the std::transform function.
I know the example is a bit stupid, it's just to show the problem I'm confronted with.
File "example.h"
class Example {
public:
//.. constructor and de... | As Alexandre already pointed out, you can't use an type with function scope (or no name at all) as a template parameter. You can however use a static member function of a local type as a functor parameter:
int main()
{
struct F {
static int fn(int x)
{
return x+x;
}
};
... |
3,413,050 | 3,414,239 | Initializing std::tuple from initializer list | I'm wondering whether the tuple can be initialized by initializer list (to be more precise - by initializer_list of initializer_lists)? Considering the tuple definition:
typedef std::tuple< std::array<short, 3>,
std::array<float, 2>,
std::array<unsigned char, 4>,
... | Initializer lists aren't relevant for tuples.
I think that you're confusing two different uses of curly braces in C++0x.
initializer_list<T> is a homogeneous collection (all members must be of the same type, so not relevant for std::tuple)
Uniform initialization is where curly brackets are used in order to constru... |
3,413,152 | 3,413,423 | How to add boost to my project? | I work on a cross-platform (Windows, Linux, Solaris) project. I want to use Boost's shared_ptr in this project.
How can I install it, and redistribute it with the project to the customers?
I don't have root permissions on Linux/Solaris, so I probably have to add Boost' sources to my sources, and build it together.
Also... | Just install the boost header files (you don't need to compile and install the libraries for shared_ptr, because it's header only). Don't forget to check if the include paths for boost are set up right inside your IDE, so it will be able to find the header file.
In your code file, include this header:
#include<boost/sh... |
3,413,166 | 3,413,215 | When does a process get SIGABRT (signal 6)? | What are the scenarios where a process gets a SIGABRT in C++? Does this signal always come from within the process or can this signal be sent from one process to another?
Is there a way to identify which process is sending this signal?
| abort() sends the calling process the SIGABRT signal, this is how abort() basically works.
abort() is usually called by library functions which detect an internal error or some seriously broken constraint. For example malloc() will call abort() if its internal structures are damaged by a heap overflow.
|
3,413,308 | 3,413,345 | When will the move ctor be invoked? | Given class:
class C
{
public:
C()
{
cout << "Dflt ctor.";
}
C(C& obj)
{
cout << "Copy ctor.";
}
C(C&& obj)
{
cout << "Move ctor.";
}
C& operator=(C& obj)
{
cout << "operator=";
return obj;
}
C& operator=(C&& obj)
{
... | The move constructor will be invoked when the right-hand side is a temporary, or something that has been explicitly cast to C&& either using static_cast<C&&> or std::move.
C c;
C d(std::move(c)); // move constructor
C e(static_cast<C&&>(c)); // move constructor
C f;
f=std::move(c); // move assignment
f=static_cast<C&&>... |
3,413,391 | 3,423,478 | Code polisher / reformater for C, C++ or Fortran | Suppose you have got a bunch of files written in C, C++ or Fortran, by different authors, with different opinions on formatting, how to comment, and so on. I think many people know situations like these.
Are there any free tools for ends like:
uniform format of code (indent, etc.)
create standard comment bodies
rename... | For Fortran there is plusFORT, which can do much more than what you ask for, such as reorganizing code and translating from FORTRAN 77 to Fortran 90. See http://www.polyhedron.com/pf-plusfort0html and http://www.polyhedron.com/pflinux0html
|
3,413,470 | 3,413,547 | What is std::move(), and when should it be used? |
What is it?
What does it do?
When should it be used?
Good links are appreciated.
| Wikipedia Page on C++11 R-value references and move constructors
In C++11, in addition to copy constructors, objects can have move constructors.
(And in addition to copy assignment operators, they have move assignment operators.)
The move constructor is used instead of the copy constructor, if the object has type "rva... |
3,413,686 | 3,413,756 | C++ - Sort multidimensional vector by its contained object property | I've got a bidimensional array of objects (a 2D vector containing GridCell instances) as in here:
typedef vector<GridCell> CellArray;
typedef vector<CellArray> TwoDCellArray;
TwoDCellArray CellArr2D;
I am currently drawing all the cells like this:
for (int i = 0; i < rows; i++){
for (int j = 0; j < cols; j++){
... | Create a vector of pairs (i,j) and sort it by size property.
typedef std::pair<int, int> int_pair_t;
typedef std::vector< int_pair_t > size_index_t;
namespace {
struct sort_helper {
sort_helper( const TwoDCellArray& arr ) : arr_(arr) {}
bool operator()( const int_pair_t& ind1, const int_pair_t& ind2 ) { ... |
3,413,775 | 3,413,831 | generate unique 5 digit number | i was told to write program which generate unique 5 digit number ( for example 12345 is unique and 11234 not)
i have write following code
#include <iostream>
#include <stdlib.h>
#include <map>
using namespace std;
using std::rand;
const int k=99999-10234;
bool unique(int t){
map<int,int>my;
map<int,in... | I think the line:
if ( it->second>0) {
Should be:
if ( it->second>1) {
Since when you find the first instance of a digit and put it in the map it'll have the value 1 for that digit in the map, not 0.
|
3,413,996 | 3,414,035 | How to convert a string to complex<float> in C++? | How do I easily convert a string containing two floats separated by a comma into a complex?
For instance:
string s = "123,5.3";//input
complex<float> c(123,5.3);//output/what I need
Is there an simpler/faster way than to split the string, read the two values and return thecomplex<float>?
| Just add the parentheses and the default operator>> will do it for you:
#include <iostream>
#include <string>
#include <complex>
#include <sstream>
int main()
{
std::string s = "123,5.3";//input
std::istringstream is('(' + s + ')');
std::complex<float> c;
is >> c;
std::cout << ... |
3,413,998 | 3,414,073 | Add automation support to MFC DLL | Is there a way to add automation to an existing MFC dll?
I know I can create a new project and select Automation during the wizard, but I already have a dll with ATL support which exposes a number of COM objects so I'd rather update that than have to recreated it.
| Article Adding automation to MFC applications should help you.
|
3,414,157 | 3,414,941 | How to optionally depend on a shared object with gcc? | First, I don't know if there is a solution to my problem at all.
I have the following situation:
I have developed a framework library that depends on several other libraries for specific hardware access, etc.
Until now this framework library was only statically linked against.
For the executable that uses the framewor... | From man ld
--as-needed
--no-as-needed
This option affects ELF DT_NEEDED tags for dynamic libraries mentioned on the command line after the --as-needed option. Normally,
the linker will add a DT_NEEDED tag for each dynamic library mentioned on the command line, regardless of whether the library is
... |
3,414,233 | 3,414,252 | Is an int the same as unsigned or signed? | Is an int the same type as unsigned or signed?
| Plain int is the same as signed is the same as signed int
|
3,414,509 | 3,549,915 | Date/Time parsing in C++ | While doing the data/time parsing in c++ (converting a string in any format to a date), i found the following useful methods
1) strptime() - here the %d, %m etc can have either 1 or 2 characters. The function will take care of that. As a result of this it will enforce that we use a separator between two conversion spe... | @AJ: Added another answer so the code gets formatted
#include <stdio.h>
#include <sys/time.h>
#include <time.h>
int
main(void)
{
struct tm tm[1] = {{0}};
strptime("Tue, 19 Feb 2008 20:47:53 +0530", "%a, %d %b %Y %H:%M:%S %z", tm);
fprintf(stdout, "off %ld\n", tm->tm_gmtoff);
return 0;
... |
3,414,621 | 3,414,744 | C++ boost forward declaration question | I spend some time examining boost:: libraries architecture and was interested with the following fact:
In some parts of the libraries a yyy_fwd.hpp idea is used pretty common (see boost/detail or boost/flyweight for examples).
These files obviously contain only forward declarations of some template-based classes and as... | Forward declarations are needed to reduce compile-time dependencies. For instance, when implementing Pimpl idiom.
One more case is that, for instance, boost::pool* depends on windows.h on Windows platform. When creating my interface I don't want to force the users of my class to include the system headers by using my i... |
3,414,639 | 3,414,691 | Where is the "virtual" keyword necessary in a complex multiple inheritance hierarchy? | I understand the basics of C++ virtual inheritance. However, I'm confused about where exactly I need to use the virtual keyword with a complex class hierarchy. For example, suppose I have the following classes:
A
/ \
B C
/ \ / \
D E F
\ / \ /
... | You have to specify virtual inheritance when inheriting from any of A, B, C, and E classes (that are at the top of a diamond).
class A;
class B: virtual A;
class C: virtual A;
class D: virtual B;
class E: virtual B, virtual C;
class F: virtual C;
class G: D, virtual E;
class H: virtual E, F;
class I: ... |
3,414,696 | 3,414,707 | How to stop a process using a "Stop Button" | I created a simple window with two buttons,
the first one calls a function that lasts a long time,
the second one sets the value of a variable "stop" to TRUE,
that was initially set to FALSE.
My intention is that, by pressing the first button it runs a long process,
that controls if the stop variable is set to TRUE or ... | You need to run the long process on a separate thread and your approach should work.
This is, instead of just calling longProcess function on Start Button Click, create a thread, and run the long process on it.
What's happening is that your long process is blocking your UI thread, which is responsible for handling UI ... |
3,414,834 | 3,417,007 | GCC std::thread not found in namespace std | I am using GCC 4.5.0 with the Eclipse IDE (if that matters) on Windows via MinGW.
I'm using the -std=c++0x flag.
I find that _GLIBCXX_HAS_GTHREADS still isn't defined, so thread for me still isn't a member of namespace std. -- or perhaps it is something else.
What does one do to get C++11 threading support with GCC?
P.... | Works fine on Linux (g++ -std=c++0x -lpthread with no additional defines).
However, this thread on Cygwin mailing list suggests that, at least as of 4.4, _GLIBCXX_HAS_GTHREADS was disabled by an autoconf test when building libstdc++ because pthread implementation of cygwin is missing pthread_mutex_timedlock. Perhaps M... |
3,414,860 | 3,421,443 | How to debug program with signal handler for SIGSEGV | I am writing a plugin for a application, occasionally a SIGSEGV would be throw out. However, the application catches the signal SIGSEGV. In other word, The plugin is a dynamical library. The error occurs in my plugin and dynamical library. But the applcation handle the sSIGSEGV and exit normally. So, it is quite diffic... | GDB will catch SIGSEGV before the application does.
What you described in comment to Logan's answer makes no sense.
I suspect what's really happening is that the application creates a new process, and only gets SIGSEGV in that other process, not the one you attached GDB to.
The following commands may be useful if my gu... |
3,414,985 | 3,468,327 | Extract useful file list (with path) from Visual Studio C++ project | I am working with a team on quite a few visual studio (2008) projects which share a lot of code. Some files are used by all projects, but some are only useful to 1 or 2.
I am looking for a way to extract all useful files for one particular project.
The principle we use is to share directories. Each project selects the... | I have written a small tool in python that does the job. The principle is to launch a "rebuild all" command in devenv for the to-be-archived solution+project, and to interpret its output.
This command is applied to a special configuration (in my case "ReleaseInclude") to which a couple of subtle changes (compared to "... |
3,415,007 | 3,415,054 | How to cope with "the application has failed to start because its side-by-side configuration is incorrect" error in vmware? | When I try to open released .exe file (which I wrote in Visual Studio 2008) in VMWare Workstation 6.5 with Windows Server 2008 32bit OS, got "The application has failed to start because its side-by-side configuration is incorrect." error all time even if the code is;
#include <stdio.h>
int main ()
{
printf ("HELLO\... | You probably forgot to deploy the runtime support DLLs or copied the Debug build of your program. For a small program like this without DLLs that export C++ classes or pointers it is better to link the static version of the CRT. Project + Properties, C/C++, Code Generation, /MTd. Repeat for the Release configuration... |
3,415,063 | 3,415,492 | issue returning CArray | I am trying to return a CArray from a function and trying to call the function from another class
short ListMaker::RetArray(CString szName, CArray<CString, CString&> &szarr_Names) {
szarr_Names.Add(szName);
return 0;
}
int main() {
//..
CArray<CString, CString&> myArray;
ListMaker LM;
short nC... | Erm, frist of all if RetArray is a member of ListMaker class and you call it from main(), you cannot call it like this: short nCode = RetArray(L"Name", myArray);
If RetArray is a static member, use short nCode = ListMaker::RetArray(L"Name", myArray);. It it's non-static, use instance, short nCode = listMakerInstance.Re... |
3,415,161 | 3,415,512 | How to speed-up loading of 15M integers from file stream? | I have an array of precomputed integers, it's fixed size of 15M values. I need to load these values at the program start. Currently it takes up to 2 mins to load, file size is ~130MB. Is it any way to speed-up loading. I'm free to change save process as well.
std::array<int, 15000000> keys;
std::string config = "confi... | You have two issues regarding the speed of your write and read operations.
First, std::copy cannot do a block copy optimization when writing to an output_iterator because it doesn't have direct access to underlying target.
Second, you're writing the integers out as ascii and not binary, so for each iteration of your wr... |
3,415,322 | 6,355,523 | Xcode debugger static member variables | Do you know how may I see the value of a static member variable from a class in xcode?
I can all the other variables except the static ones.
Thank you!
| To see Static Variable go to Globals in debugger.
under the library, select your project. To the right you should see your static variable. Tick the check box.
Now you can see the variable under Globals in debugger.
Cheers!
|
3,415,391 | 3,423,826 | Boost::Signals encapsulation over network | I am currently involved in the development of a software using distributed computing to detect different events.
The current approach is : a dozen of threads are running simultaneously on different (physical) computers. Each event is assigned a number ; and every thread broadcasts its detected events to the other and ... | Since I don't know any solution that will do that, other then Open MPI, if I had to do that, I would first use Google's Protocol Buffer as my message container. With it, I could just create an abstract base message with stuff like source, dest, type, id, etc. Then, I would use Boost ASIO to distribute those across th... |
3,415,399 | 3,415,564 | in X is it possible to detect when shift is pressed and released when it isn't modifying another key? | as in the title, it doesn't appear to generate an event unless another key/button is pressed at the same time. thanks,
james
| Running xev and pressing shift gives me this:
KeyPress event, serial 34, synthetic NO, window 0x5a00001,
root 0xf7, subw 0x0, time 1739516541, (174,173), root:(1021,367),
state 0x10, keycode 50 (keysym 0xffe1, Shift_L), same_screen YES,
XLookupString gives 0 bytes:
XmbLookupString gives 0 bytes:
... |
3,415,579 | 3,420,714 | Statically linking new libc symbols to use with a lower libc version | I have an app that uses eventfd and timerfd kernel syscalls. For that use you need a modern kernel and a libc that supports them, at least 2.8.
My current situation is, I have a system with the proper kernel but a 2.7.11 libc version which obviously does not support the required functions for the new syscalls.
But, as ... | It's probably more feasible to create your own conditionally-compiled versions that use syscall() to call them directly.
|
3,416,081 | 3,416,173 | virtual class in abstract class | Hello :) i would like to ask, if it's posible to make something like this:
i have base class (parent) A and three other classes (childs) B C D
in class A, i have virtual functions, that's ok.
but what if i need a virtual class ?
class A
{
public:
virtual int func1()=0;
virtual int func2()=0;
virtual class... | This is fundamentally impossible. A virtual function call is determined at runtime. A class changes the behaviour of the program at compile-time. You can't make a compile-time determination at runtime unless runtime and compiletime are the same time, i.e. using a JIT or other dynamic code generators. In standard C++, t... |
3,416,273 | 3,416,295 | map<T,T>::iterator as parameter type | I have a template class with a private map member
template <typename T>
class MyClass
{
public:
MyClass(){}
private:
std::map<T,T> myMap;
}
I would like to create a private method that accepts an iterator to the map
void MyFunction(std::map<T,T>::iterator &myIter){....}
However, this gets a compile error: ide... | The compiler doesn't know that std::map<T,T>::iterator is a type—it could be anything depending on what std::map<T,T> is. You must specify this explicitly with typename std::map<T,T>::iterator.
|
3,416,280 | 3,416,613 | Can I create a predicate that will accept both functions and functors as a parameter? | I'm working on a problem in C++ that involves lots of subset and transformation operations on a large quantity of data. To that end, I've created a map function and something like list comprehensions. I've found that a bunch of the predicates I'm writing also have inverses, so I'd need to write:
template <typename type... | Here's an example of your code made to work (I removed the foo member, so it would work with just doubles).
template <typename type_t>
bool HasTenFoo(const type_t &t) {
return t >= 10.0;
}
class HasEnoughFoo {
public:
HasEnoughFoo (double bar) { this->bar = bar; }
template<typename type_t>
bool operator()(cons... |
3,416,335 | 3,416,433 | How do you setup istream_iterator to not ignore blank lines | I'm having problems with istream_iterator reading a file because it ignores blank lines, but I need that those blank lines are included as "".
How should I modify the program below to get the 5 lines in my vector?
#include <sstream>
#include <string>
#include <iostream>
#include <vector>
#include <iterator>
using name... | The problem here isn't really with istream_iterator - it's with streams, which are set up to treat all runs of consecutive "white space" as a single delimiter.
As I outlined in a previous answer, there are a number of ways to get istream_iterator to read line-by-line though. Note that these will work a bit differently ... |
3,416,339 | 3,416,740 | template method specialisation problem | Can anyone help me with this code. I'm trying to specialise a method. At the moment it doesn't work with one specialisation (1) but I'd like to ultimately have lots of specialisations (2, 3, 4, 5 etc)
class X
{
public:
// declaration
template< int FLD >
void set_native( char *ptr, unsigned int length );
... | As Benoit proposed, you have to specialize the member function in the surrounding namespace:
struct X {
template<int N> void f() {}
};
template<> void X::f<1>() {} // explicit specialization at namespace scope
This is because of §14.7.3 (C++03):
An explicit specialization shall be declared in the namespace of wh... |
3,416,668 | 3,416,928 | Alternatives to expat for stream-oriented XML parsing in C++ | Are there alternatives to expat for stream-oriented XML parsing in C++? The data that I am dealing with arrives over a TCP connection and there are multiple XML documents to deal with, which means I have to reset the XML parser every time there is a new document. The parser doesn't need to be standards-compliant; I'm... | What about Xerces-C++?
|
3,416,728 | 3,417,467 | What exactly does "static" mean when declaring "global" variables in C++? | This is an expansion of the scope of a previous question of mine.
What exactly is "static", how is it used, and what is the purpose of using "static" when dealing with C++?
Thanks.
| The keyword static has different meanings in C++, depending on the context.
When declaring a free function or a global variable it means that the function is not to be available outside of this single translation unit:
// test.cpp
static int a = 1;
static void foo() {}
If the result of compiling that translation unit... |
3,416,988 | 3,417,085 | Trying to replace my boost::asio::read with boost::asio::async_read | So, the code I started with and which works (with important caveats below)
int reply_length = boost::asio::read(*m_socketptr, boost::asio::buffer((char*)reply, 6));
This works, I get the header which I then decode and follow up with another read which gets me my message and then I loop back to the top and read another... | I assume you have created an io_service somewhere in your code? You need to call its io_service.run() or io_service.run_one() to make it work. If you need it to be async, then run_one() is you man; put a call to it in you app's/thread's main loop.
|
3,417,182 | 3,417,299 | Perl system call causes core dump but $? remains zero | I've got a Perl script (running on Xubuntu Lucid Lynx within VirtualBox) that wraps around several C/C++ binaries feeding the inputs of one into the others. One of the lines consists of generally:
my $ret_code=`cat $input | c_binary`;
my $ret_val= $?;
For some input files the code causes a coredump, but both $ret_val ... | First, you've got a useless cat in your command line that could easily be replaced by a redirection.
I'd try changing the command to something like the following
my $command = "cd $STEPBYSTEP_HOME/collins-parser && code/parser $src models/model$model_num/grammar 10000 1 1 1 1 < models/model$model_num/events 1> $dest 2>... |
3,417,314 | 3,417,555 | Unused template functions in shared library | I have a template function in a shared library written in C++(the function is not called anywhere in the library, so it shouldn't be generated, am i wrong?) [g++, Linux]
I try to use this template function in the application but compiler gives link error.I searched the function using objdump but I can not see the funct... | Templates are hard to implement by compiler developers, and thus, most C++ compilers actually require you to put template code in header files, even complete class implementations (there are some exceptions and tricks to avoid this though).
For your case, all you need to do is move your function template to a header fi... |
3,417,567 | 3,417,583 | Problem with dynamic casting | This code returns me an error whenever I try to run this code. Can some one please help me.
struct m
{
virtual int s( )
{
return 1;
}
};
struct n : public m
{
int s( )
{
return 2;
}
};
int o( )
{
n* p=new m;
m* q=dynamic_cast<p>;
return q->s( );
}
| These C++ cast operators should be used as
dynamic_cast<newType>(variable)
In your case,
m* q = dynamic_cast<m*>(p);
BTW, are you confusing the role of m and n? n* p = new m is a syntax error because a base class instance cannot be implicitly converted to a derived class instance. In fact, base → derived is the situ... |
3,417,636 | 3,417,757 | Can we use a user defined class for the key in a STL map? | I need a key in the map, however, I found it should be multiple data. Can I put these data in one user defined class and put the whole class as a key in the map?
Will it impact the time efficiency?
What other concerns should be applied here?
| Any type can be used as a key as long as it is
Copyable
Assignable
Comparable, since the map is sorted by key
If your class is just a simple structure, then it's already copyable and assignable. For a class to be comparable, you must either implement operator<, or create the map with a custom comparison function to u... |
3,417,660 | 3,417,899 | QrCode C/C++ API For Windows | I have looked after, without luck, a free C/C++ API for Windows that can be used in a project I am about to start. There are libraries for Java and C# but the fact is there is no one for C/C++. I need an API that can be integrated in a vs project and we cannot use libraries that run in servers ( as CGI scripts or whate... | if you want to generate QRcodes have a look at libqrencode it works with cygwin on windows (not sure about VS).
If you want to decode QRcodes have a look at zxing
|
3,417,880 | 3,417,929 | Why does my debugger sometimes freak out and do things like not line up with my code? | When I'm using my debugger (in my particular case, it was QT Creator together with GDB that inspired this) on my C++ code, sometimes even after calling make clean followed by make the debugger seems to freak out.
Sometimes it will seem to be lined up with another piece of code's line numbers, and will jump around. Some... | There's 3 very common reasons
You're debugging optimized code. This rarely works - optimized code can be reordered/inlined/precomputed/etc. to the point there's no chance whatsoever to map it back to the source code.
You're not debugging, for whatever reason, the binary matching the current source code.
You've invoke... |
3,417,910 | 3,418,978 | Using <urlmon.h> and URLDownloadToFile to get HTTPS Web Resources | All,
I am making a programming that will be able to download content from various websites on and off of my local network.To do this, I must use the libs and c++ for compatibility reasons. So far I have been able to successfully access a normal HTTP page, and an HTTPS page on the web. Example:
HRESULT res = URLDownlo... | I think you need to check that the certificate chain is trusted in Internet Explorer.
Better, use libcurl :)
|
3,417,979 | 3,418,017 | Upcasting instance and Invoking a function on base class in C++ | class PureVirtual
{
public: virtual PureVirtual& Foo () = 0;
virtual ~PureVirtual () {}
};
class SemiVirtual : public PureVirtual
{
public: PureVirtual& Foo () { printf ("foo worked."); return *this; }
virtual ~SemiVirtual () {}
};
class NonVirtual : public SemiVirtual
{
public: NonVirtual& Bar () { p... | Because you initialized pv with reference to temporary object.
"Temporary object" will be automatically destroyed in the next line, after that all calls to non-static methods that use class members, and all virtual methods will crash the application.
Use pointers. Or this:
TEST (Virtualism, Tests)
{
NonVirtual v;
... |
3,418,231 | 3,418,285 | Replace part of a string with another string | How do I replace part of a string with another string using the standard C++ libraries?
QString s("hello $name"); // Example using Qt.
s.replace("$name", "Somename");
| There's a function to find a substring within a string (find), and a function to replace a particular range in a string with another string (replace), so you can combine those to get the effect you want:
bool replace(std::string& str, const std::string& from, const std::string& to) {
size_t start_pos = str.find(fro... |
3,418,273 | 3,421,479 | OpenGL Texture Mapping Error | Here's a BIG problem with my project:
I love the tutorials on the NeHe website, and Windows XP ran the programs perfectly. However, when I reformatted my computer, changed the OS to Windows Vista and reinstalled my Dev-C++ compiler, and then I tried to open any C++ program that used textures, the program crashed.
I rea... | Case Closed:
I was editing my bitmap (NeHe lesson7's Crate.bmp) when I realised the colours I painted on it did not show right. After creating a new 24-bit bitmap and marking colours on it, the white background went orange, but this was because of my previous glColor3f() call. I added a glColor3f(1.0f, 1.0f, 1.0f) call... |
3,418,524 | 3,418,990 | Buffer underrun logic problem, threading tutorial? | Ok, I tried all sorts of titles and they all failed (so if someone come up with a better title, feel free to edit it :P)
I have the following problem: I am using a API to access hardware, that I don't coded, to add libraries to that API I need to inherit from the API interface, and the API do everything.
I put in that ... | I believe that the solution with separate thread that will prepare data for the library so that it is ready when requested is the best way to reduce latency and solve this problem. One thread generates music data and stores it in the buffer, and the APIs thread is getting data from that buffer when it needs it. In this... |
3,418,610 | 3,418,681 | Decode wav file into raw on win32 | How can I decode a wav file (RIFF) containing PCM data on Windows into raw samples (so that I can feed it to ASIO) on win32?
I don't have time to reinvent the wheel. If there's a library out there that does the whole "play a wav file into ASIO" thing at once, that would be nice. ASIO is simple enough, though, and has... | The .wav header-file is dead simple (a tutorial), and the PCM encoded data can probably be fed directly to ASIO once you locate them (by parsing a few simple fields of the header)
|
3,418,700 | 3,418,737 | How to idiomatically call C++ functions based on variable value? | Suppose I have a data type enum TreeTypes { TallTree, ShortTree, MediumTree }.
And I have to initialize some data based on one particular tree type.
Currently I have written this code:
int initialize(enum TreeTypes tree_type) {
if (tree_type == TallTree) {
init_tall_tree();
}
else if (tree_type == S... | Your code is OK for two or three values, but you are right, you need something more industrial strength when you have hundreds of them. Two possible solutions:
use a class hierarchy, not enums - you can then use virtual functions and have the compiler work out which actual function to call
create a map of enum -> func... |
3,418,922 | 3,419,008 | union consisting of float : completely insane output | #include <stdio.h>
union NumericType
{
float value;
int intvalue;
}Values;
int main()
{
Values.value = 1094795585.00;
printf("%f \n",Values.value);
return 0;
}
This program outputs as :
1094795648.000000
Can anybody explain Why is this happening? Why did the value of the float Values.value inc... | First off, this has nothing whatsoever to do with the use of a union.
Now, suppose you write:
int x = 1.5;
printf("%d\n", x);
what will happen? 1.5 is not an integer value, so it gets converted to an integer (by truncation) and x so actually gets the value 1, which is exactly what is printed.
The exact same thing is ... |
3,419,265 | 3,419,296 | C++ templates and object code instantiation | With this question I'd like to better understand how C++ templates system works with regards to this question.
As far as I know, template-based classes and functions are usually placed into header files. This is due to the technical issue of managing generic data types, which characterstics are unknown in principle. As... | You're stuffed, in short. The Standard did define an "export" keyword, that was supposed to export instantiable (i.e., the raw form, not a specific type) templates from a file. However, the reality is that virtually no major compilers support it and said that they would never support it. Therefore, it was removed from ... |
3,419,283 | 3,419,349 | pthread_create ENOMEM around 32000 threads | The process running get stuck around 32 000 (± 5%)
~# cat /proc/sys/kernel/threads-max
127862
~# ulimit -s
stack size (kbytes, -s) 2048
free memory available : 3,5 Go
Further more when I try basic command while the process is stuck like "top", I get the bash message : can't fork, not enough memory.
Even i... | Threads are identified with Thread IDs (TIDs), which are just PIDs in Linux, and...
~% sysctl kernel.pid_max
kernel.pid_max = 32768
PIDs in Linux are 16-bit, and 32768 is already the maximum value allowed. With that many threads, you have just completely filled the operating system process table. I don't think you wil... |
3,419,322 | 3,419,678 | General Socket Question - Transferring C++ Structs from Java to C++ | I have a general socket programming question for you.
I have a C struct called Data:
struct data {
double speed;
double length;
char carName[32];
struct Attribs;
}
struct Attribs {
int color;
}
I would like to be able to create a similar structure in Java, create a socket, create the da... |
Be weary of endianness if you use binary serialization. Sun's JVM is Big Endian, and if you are on an Intel x86 you are on a little endian machine.
I would use Java's ByteBuffer for fast native serialization. ByteBuffers are part of the NIO library, thus supposedly higher performance than the ol' DataInput/OutputStre... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.