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,272,708 | 3,272,731 | Does std::vector use the assignment operator of its value type to push_back elements? | If so, why? Why doesn't it use the copy constructor of the value type?
I get the following error:
/usr/lib/gcc/i686-pc-cygwin/3.4.4/include/c++/bits/vector.tcc: In member functio
n `ClassWithoutAss& ClassWithoutAss::operator=(const ClassWithoutAss&)':
/usr/lib/gcc/i686-pc-cygwin/3.4.4/include/c++/bits/vector.tcc:238: ... | The C++03 standard says elements must be copy-constructible and copy-assignable to be used in a standard container. So an implementation is free to use whichever it wants.
In C++0x, these requirements are put on a per-operation basis. (In general, elements must be move-constructible and move-assignable.)
To get what y... |
3,272,810 | 3,272,825 | question about auto_ptr::reset | please can anybody explain this code from C++ Reference site:
#include <iostream>
#include <memory>
using namespace std;
int main () {
auto_ptr<int> p;
p.reset (new int);
*p=5;
cout << *p << endl;
p.reset (new int);
*p=10;
cout << *p << endl;
return 0;
}
| auto_ptr manages a pointer. reset will delete the pointer it has, and point to something else.
So you start with auto_ptr p, pointing to nothing. When you reset with new int, it deletes nothing and then points to a dynamically allocated int. You then assign 5 to that int.
Then you reset again, deleting that previously ... |
3,272,822 | 3,272,867 | does adding a dummy parameter to constructors of a class to solve calling ambiguity, violate any rule? | take following class and two object definitions:
class Rect{
public:
enum centimeter;
enum meter;
Rect(double len,double wid,enum centimeter){
length=(len/100);
width=(wid/100);
}
Rect(int len,int wid,enum meter){
length=len;
width=wid;
}
//rest of implementation
private:
double length;//i... | STL uses that idiom to differentiate iterator types in lieu of concepts.
|
3,273,155 | 3,273,721 | Perspective and Bilinear transformations | I'm making a vector drawing application and noticed that Anti Grain Geometry have an example that does exactly what I want. http://www.antigrain.com/demo/index.html then below there is an example on perspective for Win32. I don't understand their cpp file. Based on this example. If I have a bunch of verticies to form a... | From that very page you posted, there's a link to the source
code. I'll explain the bilinear transformation in
http://www.antigrain.com/__code/include/agg_trans_bilinear.h.html
The idea here is to find a transformation of the form:
output_x = a * input_x + b * input_x * input_y + c * input_y + d
output_y = e * input_x ... |
3,273,354 | 3,273,448 | Accessing a static member that has the same name as an inner type | I have a few classes that define sequences whose values must be available both at compile-time through a value member and at runtime as an actual instance of the type. So my base types for an arithmetic sequence looks a little like this,
template<int A, int D>
struct ArithmeticSequence : public Sequence {
Arithmeti... | The names of enumerators, function and objects hide the names of enumerations and classes that are declared in the same scope. In your case, the data member name hides the name of the struct. You can access the hidden type name by special lookups:
The name prior to :: is looked up by ignoring object-, function- and en... |
3,273,430 | 3,273,699 | A boot loader in C++ | I have messed around a few times by making a small assembly boot loader on a floppy disk and was wondering if it's possible to make a boot loader in c++ and if so where might I begin? For all I know im not sure it would even use int main().
Thanks for any help.
| If you're writing a boot loader, you're essentially starting from nothing: a small chunk of code is loaded into memory, and executed. You can write the majority of your boot loader in C++, but you will need to bootstrap your own C++ runtime environment first.
Assembly is really the only option for the first stage, as ... |
3,273,455 | 3,273,485 | c++ multithreaded task queue for scheduled tasks | I need to develop a module which will execute scheduled tasks.
Each task is scheduled to be executed within X milliseconds.
The module takes as a parameter an amount of worker threads to execute the tasks.
The tasks are piled up in a queue which will probably be a priority queue, so a thread checks for the next-in-queu... | If you don't mind a Boost dependency, threadpool might fit your needs.
|
3,273,504 | 3,273,571 | Is it possible to transform the types in a parameter pack? | Is it possible to transform the types of a parameter pack and pass it on?
E.g. given the following:
template<class... Args> struct X {};
template<class T> struct make_pointer { typedef T* type; };
template<class T> struct make_pointer<T*> { typedef T* type; };
Can we define a template magic or something similar so... | Yes we can do that
template<template<typename...> class List,
template<typename> class Mod,
typename ...Args>
struct magic {
typedef List<typename Mod<Args>::type...> type;
};
|
3,273,621 | 3,274,702 | C++ CppUnit Test (CPPUNIT_ASSERT) | I'm trying to do up a screen scraping assignment. My cpp works, but I don't know how to integrate my unit testing. I tried to do a bool check unit test for the file validity but it's giving me this error:
error: cannot call member function 'bool ScreenScrape::getFile()' without object
screenscrape.cpp:
#include "scree... | bool ScreenScrape::getFile() is not static, so cannot be called as a static function. You'll need to either (a) declare it as static or (b) create an instance of ScreenScrape and call getFile() from it.
Looking at the code, it's not obvious why this function is a method of the class but perhaps it's still in the early ... |
3,273,654 | 3,276,231 | ostream showbase does not show "0x" for zero value | PSPS: (a Pre-scripted Post-script)
It has just come to mind that a more prescient question would have included the notion of: Is this non-display of "0x"(showbase) for zero-value integers a standard behaviour, or is it just a quirk of my MinGW implementation?
It all began on a pleasant Sunday morning... I want to d... | I found this on https://bugzilla.redhat.com/show_bug.cgi?id=166735 - this is copy/paste straight from there.
Doesn't sound like a bug to me.
ISO C++98, 22.2.2.2.2/10 says std::showbase means prepending # printf conversion
qualifier. 22.2.2.2.2/7 says std::hex means the printf conversion specifier is
%x.
So th... |
3,273,729 | 3,323,769 | Call C++ from an assembly bootloader | I have a small assembly bootloader that I got from this Tutorial. The code for the boot loader can be found here. I want to know if its possible to run c++ from this boot loader. I want to run a simple thing like this:
#include <iostream>
using namespace std;
int main () {
cout << "Hello World!\n";
return 0;
}
But as... | To call a C function from your assembly code, here's a schematic. Using g++ in place of gcc should allow you to use C++ code. But I wonder how much of 'C++' you'd be able to write since you cannot use the library functions, as some of the earlier replies to your question clearly point out. You may end up writing assemb... |
3,273,794 | 3,273,817 | what's bubble sort good at? |
Possible Duplicate:
What is a bubble sort good for?
I'am sure every algorithm has its advantage and disadvantage, so how about buble sort compared to other sorting algorithm? (ofcourse I hope the answer is other than "easy to learn")
|
It is easy to implement for linked lists, since you always swap adjacent nodes while traversing left to right repeatedly.
Bubble sort is a stable sort.
|
3,273,993 | 3,274,025 | how do I validate user input as a double in C++? | How would I check if the input is really a double?
double x;
while (1) {
cout << '>';
if (cin >> x) {
// valid number
break;
} else {
// not a valid number
cout << "Invalid Input! Please input a numerical value." << endl;
}
}
//do other stuff...
The above code infinitel... | Try this:
while (1) {
if (cin >> x) {
// valid number
break;
} else {
// not a valid number
cout << "Invalid Input! Please input a numerical value." << endl;
cin.clear();
while (cin.get() != '\n') ; // empty loop
}
}
This basically clears the error state, then reads and discar... |
3,274,092 | 3,274,150 | Creating a class with static pointers to explicitly loaded DLL functions | I want to have multiple instances of a DLLInterface class but as each object will have pointers to the same DLL functions I want these to be static.
The below code doesn't compile. (I do have a reason for needing multiple instances containing the same pointers which the stripped down code below doesn't illustrate.)
//... | One trick I can think of is to use templates. The idea is you make the class the includes the static data a template class and then derive your actual class from it with some specific type:
template <class T>
class DLLInterfaceImpl;
{
private:
static HINSTANCE hinstDLL;
public:
static DLLFunction Do;
};
templ... |
3,274,441 | 3,274,567 | Help Understanding these equations? | I asked a question regarding Bi linear transformations and received this answer:
From that very page you posted, there's a link to the source
code. I'll explain the bilinear transformation in
http://www.antigrain.com/__code/include/agg_trans_bilinear.h.html
The idea here is to find a transformation of the form:
output_... | That's a terrible explanation you've found. Hopefully I can help you understand what's going on under the bonnet.
What you want to do is map a rectangular area (one quadrilateral) into another (arbitrarily shaped) quadrilateral. Let's start with a simpler case: Linear interpolation (finding values that lie along a line... |
3,274,445 | 3,277,168 | Is object orientation bad for embedded systems, and why? | Many embedded engineers use c++, but some argue it's bad because it's "object oriented"?
Is it true that being object oriented makes it bad for embedded systems, and if so, why is that really the case?
Edit: Here's a quick reference for those who asked:
so we
prefer people not to use divide ..., malloc ..., or othe... | Whilst I'm not sure it answers your question, I can summarise the reasons my previous companies source code was pure C.
It's firstly worth summarising the situation:
we wanted to write a large amount of "core" code that would be highly portable across a large number of ARM embedded systems (mostly mid-range mobile pho... |
3,274,463 | 3,294,965 | Why does the chip control the language to choose | I've asked the question before what language should I learn for embedded development. Most embedded engineers said c and c++ are a must, but also pointed out that it depends on the chip.
Can someone clarify? Is it a compiler issue or what? Do chips come with their own specific compilers (like a c compiler or c++ compi... | It "depends on the chip" in three possible ways:
Some very constrained architectures are not suited to C++, or at least C++ provides constructs not suited to such architectures so offers no benefit over C. Most 8 bit devices fall into this category, but by no means all; I have seen useful C++ code implemented on Mega... |
3,274,582 | 3,274,610 | What c++ features should be avoided for embedded development | I'm interested in compiling a list of c++ features that are not advisable for use in embedded systems (and which may cause people to recommend c over c++). Please try to add why if you know, or add your why to others' answers.
Here's one for a start (the only one I know)
Dynamic polymorphism, don't know why, but some... | Certain features require run-time support, so if you miss the required support, you should avoid those features. In particular, the following features usually need extra run-time support:
exceptions
RTTI
dynamic memory allocation
virtual inheritance (a bit unsure about this one)
People also usually mention templates,... |
3,274,761 | 3,274,973 | An example of an embedded project for a single person | I've been trying to wrap my head around embedded. Since I will be self-taught in this specific niche, I realize it will be harder to get a job in the field, so I'm hoping to add a completed project to my resume to prove to potential employers that I've done it and can do it again for them.
Can someone suggest a project... | Are you looking specifically at embedded software development, or are you interested in circuit board design as well?
If it's just software, then I would suggest getting hold of an ARM development board (Possibly the Philips LPC range - sparkfun have some nice ones) that you can program via a bootloader over usb and st... |
3,274,781 | 3,275,394 | Why can CImg achieve this kind of effect? |
The compilation is done on the fly :
only CImg functionalities really used
by your program are compiled and
appear in the compiled executable
program. This leads to very compact
code, without any unused stuffs.
Any one knows the principle?
| CImg is a header-only library, and they use templates liberally, which is what they're referring to.
If they used a precompiled library of some kind (.dll/.lib/.a/.so) the library file would have to contain the entire CImg library, regardless of which bits of it you actually use.
In the case of a statically linked libr... |
3,274,813 | 3,274,820 | Rounding to nearest number in C++ using Boost? | Is there a way to round to the nearest number in the Boost library? I mean any number, 2's, 5's, 17's and so on and so forth.
Or is there another way to do it?
| int nearest = 5;
int result = (input+nearest/2)/nearest*nearest;
|
3,274,836 | 3,274,851 | Why should files be mounted in Linux | I got an old library which does some manipulation with files on floppy\ CD (transferring the files on network paths).
This library has a thread which checks on each second whether the file (e.g. the floppy diskette\ the CD disk) is mounted.
Why? What operations can be done only on mounted files?
Thanks a lot.
| To access a file in any way - read, write, execute, delete - you need to be able to specify its location. The location of a file is always its position in the directory tree, where Unix has just a single directory tree starting at a single root.
Unless the device your file is on (and hence its own (sub)directory tree) ... |
3,274,946 | 4,450,671 | Sending parameters to a DLL to be boost::bind'ed | I have a DLL which has a function which accepts a function pointer converts it to a boost::function. This is then stored and then called from inside the DLL.
I want to add a function to the DLL to handle member functions in a similar way. I know I need to use boost::bind to wrap the member function pointer and the obje... | you're warned by @Kylotan, so you can try something like this:
__declspec(dllexport) void store_mem_fn(void(Your_class::*mem_fn)(void), Your_class& instance)
{
std::vector<boost::function<void(void)> > container;
container.push_back(boost::bind(mem_fn, instance));
}
|
3,275,031 | 3,275,050 | Input terminal problems and map | I am using map to count the occurence of words. Here is the code.
#include <iostream>
#include <map>
#include <string>
using namespace std;
int main() {
map<string,int>wordcount;
string s;
while (cin>> s && s!="red")
++wordcount[s];
while (cin>>s && s!="red")
cout << s << " " << wordco... | Too groggy to write here, but I'll try a second time. :)
If you write a lot of words, it will count them up until you write "red".
The second loop will print the count for the words you input, but if you put "red" right away it will simply terminate the program without printing anything.
Try running the program with th... |
3,275,252 | 3,275,260 | Is there an equivalent to python's urllib in c/c++? | any c/c++ library out there that provides functions like getUrl, urlopen, post etc. ?
| There are some libraries, libcurl and libwww amongst others.
libcurl website even lists some other alternatives.
|
3,275,353 | 3,275,377 | C aliasing rules and memcpy | While answering another question, I thought of the following example:
void *p;
unsigned x = 17;
assert(sizeof(void*) >= sizeof(unsigned));
*(unsigned*)&p = 17; // (1)
memcpy(&p, &x, sizeof(x)); // (2)
Line 1 breaks aliasing rules. Line 2, however, is OK wrt. aliasing rules. The question is: why? Does the comp... | The C Standard is quite clear on it. The effective type of the object named by p is void*, because it has a declared type, see 6.5/6. The aliasing rules in C99 apply to reads and writes, and the write to void* through an unsigned lvalue in (1) is undefined behavior according to 6.5/7.
In contrast, the memcpy of (2) is... |
3,275,483 | 3,275,510 | question about map sort | for example we have map
map<char,int>mymap;
mymap['a']=101;
mymap['c']=45;
mymap['b']=76;
mymap['d']=98;
i know that if we iterate through map it will print element according to following way
a>=101;
b>=76;
c>=45;
d>=98;
how do such that small keys refer small values? or
a-45
b-76
c-98
d-101
?
thanks
| If I'm understanding you correctly, you do not want to permanently associate values at all, you're wanting to order two different sets of values, and then line them up together at some point. In which case, do not use a std::map. You want two different std::set (or multiset if you want to allow duplicate values) which ... |
3,275,601 | 3,275,700 | Architectural C++/STL question about iterator usage for O(1) list removal by external systems | This is a pretty straightforward architectural question, however it's been niggling at me for ages.
The whole point of using a list, for me anyway, is that it's O(1) insert/remove.
The only way to have an O(1) removal is to have an iterator for erase().
The only way to get an iterator is to keep hold of it from the ini... | The one problem I see with storing the iterator in the object is that you must be careful of deleting the object from some other iterator, as your objects destructor does not know where it was destroyed from, so you can end up with an invalid iterator in the destructor.
The reason that push* does not return an iterator... |
3,275,612 | 3,275,632 | What is the explicit keyword for in c++? |
Possible Duplicate:
What does the explicit keyword in C++ mean?
explicit CImg(const char *const filename):_width(0),_height(0),_depth(0),_spectrum(0),_is_shared(false),_data(0) {
assign(filename);
}
what's the difference with or without it?
| It's use to decorate constructors; a constructor so decorated cannot be used by the compiler for implicit conversions.
C++ allows up to one user-provided conversion, where "user-provided" means, "by means of a class constructor", e.g., in :
class circle {
circle( const int r ) ;
}
circle c = 3 ; // implicit co... |
3,275,793 | 3,278,004 | Are there specialities within the embedded fields | I've started learning embedded and its 2 main languages (c and c++). But I'm starting to realize that despite the simple learning requirements, embedded is a whole world in and of itself. And once you deal with real projects, you start to realize that you need to learn more "stuff" specific to the hardware used in the ... | Here are a few sub-specialities I can think of:
Assembly Language Specialist
Yep. You need to know C and C++. But some people also specialize in assembly. These are the experts that are called up to port a RTOS to a new chip, or to squeeze every drop of performance from a highly constrained embedded system (usually... |
3,275,821 | 3,275,831 | Anyone knows what `cimg::exception_mode() = 0;` does? | const unsigned int omode = cimg::exception_mode();
cimg::exception_mode() = 0;
Never see this kinda syntax before.
| exception mode might be returning a reference, and it is being set to 0. For example:
unsigned int& exception_mode() { return mode; };
So, the second line would be equivalent to:
void set_exception_mode( uint v ) { mode = v; };
BTW, it is really ugly! I would avoid this kinda syntax as much as I could.
|
3,275,904 | 3,275,954 | Why can the code between ifndef/endif still get run here? | #define cimg_use_jpeg 2
#ifndef cimg_use_jpeg
//code goes here
#endif
I really don't understand...
| Every time things similar to this (so-called impossible things) happen me, the reason is: The code I see in my editor is not the code that runs. This can happen in many ways.
forgetting to make
forgetting to save
saving a copy of the code
running in a different evironment from the one you compiled to
the new code ran ... |
3,275,983 | 3,276,019 | QT: Is it a good idea to base my domain objects on QObject? | I'm reasonably new to using the QT framework in combination with C++. I was wondering: Is it a good idea to base my domain classes on QObject? Or should I only do this for classes higher up in the hierarchy? (closer to the user interface level). The QT documentation isn't clear on this:
Taken from the QT documentation:... | In general, unless there is a "compelling need," you are better off keeping your domain classes "vanilla." That gives you the most flexibility in the future (e.g. re-using them in a non-Qt environment).
|
3,276,001 | 3,276,056 | STL erase-remove idiom vs custom delete operation and valgrind | This is an attempt to rewrite some old homework using STL algorithms instead of hand-written loops and whatnot.
I have a class called Database which holds a Vector<Media *>, where Media * can be (among other things) a CD, or a Book. Database is the only class that handles dynamic memory, and when the program starts it... | This is why you should always, ALWAYS use smart pointers. The reason that you have a problem is because you used a dumb pointer, removed it from the vector, but that didn't trigger freeing the memory it pointed to. Instead, you should use a smart pointer that will always free the pointed-to memory, where removal from t... |
3,276,235 | 3,379,328 | relation between access specifiers and using initializer lists for POD types in c++0x | take two following classes:
class Test1{
public:
Test1()=default;
Test1(char in1,char in2):char1(in1),char2(in2){}
char char1;
char char2;
};
class Test2{
public:
Test2()=default;
Test2(char in1,char in2):char1(in1),char2(in2){}
private:
char char1;
char char2;
};
I know in c++0x both of these class... | class Test{
public:
Test()=default;
Test(char in1,char in2):char1(in1),char2(in2){}
char char1;
private:
char char2;
};
considering above class following syntax is valid in c++0x:
Test obj={'a','b'};//valid in c++0x
The final proposal is here.
|
3,276,284 | 3,276,343 | I'm doing funky things with placement new, and things are failing. Workarounds? | I have a very large, spread out class that is essentially a very contrived two dimensional linked list. I want to be able to "compile" it, by which I mean I want to finalize the list, so that only read accesses may be made, and then move all the elements into contiguous memory spaces. My rough solution is this:
#inclu... | Are you calling delete on one of the objects in your array? Or are you manually invoking the destructor to mirror the placement new?
Since you have one call to non-placement new, you should only have one call to delete. And since you have n-calls to placement-new, you should manually invoke the destructor n times.
So... |
3,276,341 | 3,276,362 | Solving a system of equations programmably? |
Possible Duplicate:
System of linear equations in C++?
I have the following 2 systems of equations:
For a,b,c,d:
0 = a * r1_x + b * r1_x * r1_y + c * r1_y + d
1 = a * r2_x + b * r2_x * r2_y + c * r2_y + d
0 = a * r3_x + b * r3_x * r3_y + c * r3_y + d
1 = a * r4_x + b * r4_x * r4_y + c * r4_y + d
For e,f,g,h:
0 = e ... | You can map it to a matrix system, A x = b, where A is the coefficient matrix, b is the solution vector, and x are the unknowns. You can either implement Gaussian elimination, or use a well known library. If you use LAPACK, the routine you want it dgesv.
|
3,276,372 | 3,276,389 | Freeing dynamically allocated memory | In C++, when you make a new variable on the heap like this:
int* a = new int;
you can tell C++ to reclaim the memory by using delete like this:
delete a;
However, when your program closes, does it automatically free the memory that was allocated with new?
| Yes, it is automatically reclaimed, but if you intend to write a huge program that makes use of the heap extensively and not call delete anywhere, you are bound to run out of heap memory quickly, which will crash your program.
Therefore, it is a must to carefully manage your memory and free dynamically allocated data ... |
3,276,390 | 3,283,069 | OpenGL Hemisphere Texture Mapping | I need to have a hemisphere in opengl. I found a drawSphere function which I modified to draw half the lats (which ends up drawing half of the sphere) which is what I wanted. It does this correctly.
However, I don't know what i should do with glTexCoordf to get the textures to map properly onto this half sphere. I'm ... | Basically, you shouldn't need anything fancy there. The texture coordinate space ranges from zero to one. So pick some intermediate values for the vertices in between. I can't explain it more thoroughly without image, so the best I can do is to point You to this article: UV mapping, it's a good starting point. Hope thi... |
3,276,479 | 3,435,210 | Using member of template class to instantiate template default parameter in MSVC++ | The following piece of code is a reduced sample from the large project I'm trying to port from GCC/G++ to Microsoft Visual C++ 2010. It compiles fine with G++, but with MSVC++, it throws errors, and I'm having trouble understanding why.
template <typename A, typename B = typename A::C::D> // line 1
struct foo
{
t... | I reported this as a bug with Microsoft as per jpalecek's suggestion, and Microsoft has confirmed that it is indeed a fault in their compiler:
https://connect.microsoft.com/VisualStudio/feedback/details/576196
|
3,276,486 | 3,276,548 | question about templates | i have following code
#include <iostream>
#include <utility>
using namespace std;
namespace rel_ops{
template<class t>bool operator!=(const t& x, const t& y){ return !(x==y);}
template <class t>bool operator>(const t& x,const t& y){ return y<x;}
template <class t>bool operator <=(const t& x,const t& y){ re... | You just need to add:
using namespace rel_ops;
Note that rel_ops is already defined in std. You do not need to redefine this namespace and its contents in your code. To use the definition already present in std, you use just:
#include <utility>
using namespace std::rel_ops;
|
3,276,576 | 3,276,584 | C++/STL: XOR of two set | Given two STL sets, I want to find out the XOR of them. Is there an easy, pre-existing way to do that?
| You can use std::set_symmetric_difference from the C++ standard library.
|
3,276,589 | 3,276,615 | question about class |
Possible Duplicates:
Why should I prefer to use member initialization list?
C++ - what does the colon after a constructor mean?
here is following code
class vector2d {
public:
double x,y;
vector2d (double px,double py): x(px), y(py) {}
i dont understand this line
vector2d (double px,double py): x(px), y(py) {}... | Yes, it's the same in your example. However, there's a subtle difference: x(px) initializes x to px, but x=px assigns it. You'll not know the difference for a doublevariable, but if x where a class there would be a big difference. Let's pretend that x is a class of type foo:
x(px) would call the foo copy constructor, f... |
3,276,596 | 3,277,100 | Dependent Non-Type Template Parameters | Consider the following class:
class Foo
{
enum Flags {Bar, Baz, Bax};
template<Flags, class = void> struct Internal;
template<class unused> struct Internal<Bar, unused> {/* ... */};
template<class unused> struct Internal<Baz, unused> {/* ... */};
template<class unused> struct Internal<Bax, unused> {/* ... *... |
How can I fix this (i.e., keep internal pseudo-explicit specializations in a templated Foo) on VC++ 2010?
You can make the enumeration type non-dependent by declaring it in a non-template base class (C++03 made nested classes dependent in #108 but that doesn't include enumeration, but even if, such code would still b... |
3,276,778 | 3,276,815 | Mapping class to instance | I'm trying to build a simple entity/component system in c++ base on the second answer to this question : Best way to organize entities in a game?
Now, I would like to have a static std::map that returns (and even automatically create, if possible).
What I am thinking is something along the lines of:
PositionComponent ... | Maybe this?
std::map< std::type_info*, Something > systems;
Then you can do:
Something sth = systems[ &typeid(PositionComponent) ];
Just out of curiosity, I checked the assembler code of this C++ code
#include <typeinfo>
#include <cstdio>
class Foo {
virtual ~Foo() {}
};
int main() {
printf("%p\n", &typeid(... |
3,276,835 | 3,276,886 | Declaring two variable in a conditional? | Can I declare two variables in a conditional in C++. The compiler gave an error but still I think I should get an opinion:
int main()
{
double d1 = 0;
if((double d2 = d1) || (double d3 = 10))
cout << "wow" << endl;
return 0;
}
| You can only do that for one variable
if(double d2 = d1)
cout << "wow" << endl;
else
if(double d3 = 10)
cout << "wow" << endl;
But i would declare them outside of the conditions. If you are scared about the scope, you can always limit it:
{
double d2 = d1;
double d3 = 10;
if(d2 || d3)
cout << "wow" ... |
3,276,906 | 3,276,964 | istream_iterator leaking memory | All right, you guys were very helpful with my last question, so I'll try another one. This is also homework and while the last one was quite old, this has been submitted and is waiting to be marked. So if there's anything that will bite me it'll probably be this problem. I've obfuscated the class names and such since i... | Here's the first thing occurring to me. I don't know whether that's the issue you're hunting for:
friend istream &operator>>(istream &is, ObjectPtr &op) {
std::string tmp;
while (std::getline(is, tmp)) {
if (tmp == "Object1") {
op.o_ = new Object1;
In that last line, what happens to the ol... |
3,276,951 | 3,276,970 | Diamond sub-problem: non-multiple inheritance in side branch still require class constructor | Strange problem occurred when I tried to "solve" usual diamond problem in a usual way - using virtual inheritance:
A
/ \* both virtual
B C
\ /
D
However my base class A doesn't have default constructor, so I was to call it manually from D. However when I try to add a class E into this diamond as C-inherited
... |
Is it possible to solve this issue without calling constructor of A from E? I need C to do it properly :-).
The constructor for the most derived class (in this case, E) is responsible for calling the constructor for any virtual base classes.
The constructor of C cannot call the constructor of A because C is not the... |
3,276,971 | 3,284,154 | Xerces-C++ DOM node line/column number location | I'm writing a custom XML validator using Xerces-C++. My current approach loads the document into a DOM, and then checks are performed on it. What I need is a way to access the line/column number of a node in the DOM. I've been reading the API docs and googling, but I'm coming up short. Is it possible to somehow retriev... | A possible solution can be found here.
|
3,276,973 | 3,763,151 | How to show (printer) dialog boxes in Windows CE Direct-X app? | This page says you need to call PrintSetupDlg, but this code
PAGESETUPDLG printDialog;
ZeroMemory(&printDialog, sizeof(printDialog));
printDialog.lStructSize = sizeof(printDialog);
printDialog.hwndOwner = hwnd; //or = NULL
PageSetupDlg(&printDialog);
freezes the program on the call to PageSetupDlg - it becomes unresp... | Turns out that, for some crazy reason, dialog boxes only get drawn to the original front buffer, even if that buffer has been swapped and the original back buffer is now the front buffer (being shown on the screen).
The solution was to keep track of how many times the buffer has been swapped, and swap it again if the n... |
3,277,058 | 3,277,094 | How to rollback lines from cout? | I'm coding a task monitoring, which updates tasks' progress using cout. I'd like to display one task progress per line, therefore I have to rollback several lines of the console.
I insist on "several" because \b does the job for one line, but does not erase \n between lines.
I tried std::cout.seekp(std::cout.tellp() - ... | You can do cout << '\r'; to jump to the beginning of the current line, but moving upwards is system-specific. For Unix, see man termcap and man terminfo (and search for cursor_up). On ANSI-compatible terminals (such as most modern terminals available on Unix), this works to move up: cout << "\e[A";.
Don't try seeking i... |
3,277,121 | 3,277,149 | include objective-c header in c++ file | Is there a way to include an objective-c header from a cpp? Because when I try to #include "cocos2d.h" from a cpp .h file, a lot of errors complaining about @'s and -'s are showing up.
Can c++ files include obj-c headers like that?
| It is possible, but you need to use Objective-C++ (e.g. by making the file extension .mm) to mix the languages, plain C++ sources don't work.
To make that clear:
.m files only allow Objective-C sources
.cpp files only allow C++ sources
.mm allow mixed Objective-C++ sources - i.e. both Objective-C and C++ with some lim... |
3,277,172 | 3,277,183 | Using pair as key in a map (C++ / STL) | I want to use a pair from STL as a key of a map.
#include <iostream>
#include <map>
using namespace std;
int main() {
typedef pair<char*, int> Key;
typedef map< Key , char*> Mapa;
Key p1 ("Apple", 45);
Key p2 ("Berry", 20);
Mapa mapa;
mapa.insert(p1, "Manzana");
mapa.insert(p2, "Arandano");
return 0;
}
But the... | std::map::insert takes a single argument: the key-value pair, so you would need to use:
mapa.insert(std::make_pair(p1, "Manzana"));
You should use std::string instead of C strings in your types. As it is now, you will likely not get the results you expect because looking up values in the map will be done by comparin... |
3,277,179 | 3,277,195 | Problems importing a .lib into another project | I'm using Visual Studio 2008 under Windows 7. I have a .lib and accompanying .h files (which make use of wxWidgets if that makes a difference) which compile without any issues.
I'm trying to import that library into a GUI project but when I do, the main class I'm interested in doesn't appear to be there?
I've added #i... | Maybe are you referencing an old version of the library? Are you sure the linked libraries in the project settings are set to the right path?
|
3,277,376 | 3,277,400 | Is Python-based software considered less-professional than C++/compiled software? | I'm working on a plugin for some software that I'm planning on selling someday. The software I'm making it for has both a C++ SDK and a Python SDK.
The C++ SDK documentation appears incomplete in certain areas and isn't documented that well.
The Python SDK docs appear more complete and in general are much easier to wor... |
A lot of programmers out there don't even considered writing Python to be real "programming".
A lot of "programmers" out there are incompetent, too.
Do you think that potential customers might say "Why would I pay money for a measly little Python script?"?
I'm sure it depends on the type of software, but I can tell... |
3,277,717 | 3,277,779 | C++ WinAPI: handling long file paths/names | I'm looking at handling longer file paths in my windows application.
Currently, I have a text box (edit box) in which a user can type an absolute file path. I then read that typed file path, using GetWindowText, into a string declared like so: TCHAR FilePath[MAX_PATH];
Obviously, here i'm relying on the MAX_PATH consta... | There are a number of limitations with respect to file paths on Windows. By default, paths cannot be longer than 260 characters, which is what the MAX_PATH constant is for.
However, you can access longer paths - with certain limitations - by prefixing the path with "\\?\". However, the limitations of using the "\\?\" p... |
3,277,756 | 3,277,773 | C++ noob question: pointers and overloaded [] | I've been staring at this for a while and not getting very far. FruitBasketFactory, FruitBasket, and Fruit are three classes from an API I'm using. My goal is to make a fruit basket and then retrieve the fruit. According to the FruitBasketFactory.hpp:
const FruitBasket* getFruitBasket() const;
and then in the Frui... |
But here I get an error error C2248: 'FruitBasket::FruitBasket' : cannot access private member declared in class 'FruitBasket'.
The copy constructor for FruitBasket is inaccessible. Have you declared the copy constructor for this class as private or protected? Does this class have any bases or members that are not ... |
3,277,823 | 3,277,833 | Appropriate use of friend? Container class designed to manipulate objects of specific type | Lets say you have a FooManager made to manage multiple objects of type Foo. The FooManager needs to see some parts of its Foos to evaluate their current state. Before I was using a few accessors in Foo to see these parts, until I realized that FooManager is the only class actually using these. I decided to make FooMana... | Unless there is a different and cleaner way to achieve what you're trying to achieve, this sounds like a fair approach.
With regards to encapsulation, see: http://www.parashift.com/c++-faq-lite/friends.html#faq-14.2.
|
3,277,842 | 3,277,953 | How to get rid of padding bytes between data members of a struct | I have a binary file with "messages" and I am trying to fit the bytes inside the right variable using structs. In my example I used two types of messages: Tmessage and Amessage.
#include <iostream>
#include <fstream>
#include <stdlib.h>
#include <string>
#include <iomanip>
using namespace std;
struct Tmessage
{
... | The compiler is probably inserting pad bytes between members of your struct. One way you can get around this is to use pragma pack. Note that this is non-standard, but it works on g++ and visual C++.
#pragma pack (push, 1)
struct Amessage
{
unsigned short int Length;
char MessageType;
unsigned int Timestamp... |
3,277,961 | 3,277,970 | How can I safely (and easily) count *all* instances of a class within my program? | I would like to be able to instantiate a particular (and otherwise normal) class (the source of which I can modify) and count the number of times the class has been instantiated (e.g. like this). But I would like to include all instances in my total count, even some which are created via the copy constructor in standar... | Think of the static class variable as a global variable which is just in the namespace of the class. Incrementing or doing other things with it will not have any side effects on other code, i.e. your constructors and other operators will behave exactly as before.
I.e., you are right: Just increment in all constructors ... |
3,278,036 | 3,278,059 | What are the problems with this producer/consumer implementation? | So I'm looking at using a simple producer/consumer queue in C++. I'll end up using boost for threading but this example is just using pthreads. I'll also end up using a far more OO approach, but I think that would obscure the details I'm interested in at the moment.
Anyway the particular issues I'm worried about are
S... |
It is perfectly valid to allocate memory in one thread and free it in another if both threads are in the same process.
Using a mutex to protect access to the deque should provide the correct memory access configuration.
EDIT: The only other thing to think about is the nature of the producer and consumer. Your synth... |
3,278,314 | 3,278,346 | How to marshall c++ char* to C# string using P/INVOKE | I'm new to C++. I'm calling a C++ function from C# using a PINVOKE and wanting to get a string back as an out parameter. However I just get an empty string back. The int out parameter works fine.
Importing:
[DllImport ( @"UnamanagedAssembly.dll", CharSet = CharSet.Ansi)]
public static extern int Activate(ref int numA... | [DllImport ( @"UnamanagedAssembly.dll", CharSet = CharSet.Ansi)]
public static extern int Activate(
ref int numActivated,
[MarshalAs(UnmanagedType.LPStr)]StringBuilder eventsActivated);
|
3,278,600 | 3,278,657 | Do I need to define `operator==` to use my class with standard containers? | I'd like clarification on the C++ standard, specifically where it says (my interpretation) in section 20.1.3 that "for class T and an instance of class T called x, T(x) must be equivalent to x" for the class to work with standard containers.
I couldn't find a definition of 'equivalent'. Does this mean that I have to d... | Equivalent is purposefully vague. (To avoid things like implying operator== must be defined; it doesn't in a general case.)
However, conceptually two things are equivalent if their data represents the same object. If a class has data that might be different when "copied", then you do need to make an operator== (and pos... |
3,278,625 | 3,278,636 | When do we have to use copy constructors? | I know that C++ compiler creates a copy constructor for a class. In which case do we have to write a user-defined copy constructor? Can you give some examples?
| The copy constructor generated by the compiler does member-wise copying. Sometimes that is not sufficient. For example:
class Class {
public:
Class( const char* str );
~Class();
private:
char* stored;
};
Class::Class( const char* str )
{
stored = new char[srtlen( str ) + 1 ];
strcpy( stored, str );... |
3,278,862 | 3,283,815 | Any obvious problems or improvements for my producer consumer queue | I asked a previous question about producer/consumer code that was overly general (though the answers were certainly helpful). So I've taken the suggestions from an earlier SO question by another author and converted them to C++ and boost. However I'm always a bit concerned about multithreaded code - so if anyone can se... | If you're worried about potential pitfalls in your implementation, you can try using Anthony Williams' (maintainer of the Boost.Thread library) excellent thread-safe, multiple-producer, multiple-consumer queue.
|
3,278,864 | 3,278,924 | What is the difference between header file and namespace? | I want to know the exact difference between Header file (as in MyHeader.hpp) and a namespace in c++?
| Header files are actual files - stored in the file system, referenced by file name, and #include'd in other files (at least, in C/C++ or other languages using the M4 macro preprocessor). Header files typically group pieces of code that are all interdependent parts of the same specific item together. For instance, a gam... |
3,279,014 | 3,279,360 | Trying to understand the C preprocessor | Why do these blocks of code yield different results?
Some common code:
#define PART1PART2 works
#define STRINGAFY0(s) #s
#define STRINGAFY1(s) STRINGAFY0(s)
case 1:
#define GLUE(a,b,c) a##b##c
STRINGAFY1(GLUE(PART1,PART2,*))
//yields
"PART1PART2*"
case 2:
#define GLUE(a,b) a##b##*
STRINGAFY1(GLUE(PART1,PART2))
//yi... | cases 1 and 2 have no defined behavior since your are tempting to paste a * into one preprocessor token. According to the association rules of your preprocessor this either tries to glue together the tokens PART1PART2 (or just PART2) and *. In your case this probably fails silently, which is one of the possible outcome... |
3,279,095 | 3,279,313 | C++ Multiple Callback functions | I have a dll which requires me to set a callback function for it (actually it's a camera sdk and it will callback my function when it receives a picture).
I want to have multiple (user input) cameras but I can't.
Since I should make unknown number of callback functions.
The easy way is to make a class (camera) which ha... | Does camera SDK support multiple cameras connection? If not, you need to talk with SDK provider.
If SDK supports multiple connection, it must provide the way to recognize the camera in callback function. But actual answer is in SDK itself. What is the "image" type, maybe it contains camera ID? Maybe camera ID is suppli... |
3,279,158 | 3,279,336 | C++: How to implement (something like) JSON | Not sure how to explain it - I'm pretty new to C++, but... let me try:
Let's say I have 300+ names (Jeff, Jack...) with 300+ int values (0 or 1). In JS I would use JSON. Something like this:
var people = {"person": [
{"name": "Jeff","val": 0},
{"name": "Jill","val": 1},
{"name"... | If you can have duplicate names you can't use a map, so you could use something like this:
struct Person
{
Person( const std::string & n, int v ) : name(n), val(v) {}
std::string name;
int val;
};
int main()
{
std::vector<Person> people;
people.push_back( Person( "Jeff", 0 ) );
people.push_back( Person( "Jill",... |
3,279,319 | 3,279,343 | Determine inheritance at compile time | I have some code that behaves like this:
class Base {};
class MyClass : public Base {};
MyClass* BaseToMyClass(Base* p)
{
MyClass* pRes = dynamic_cast<MyClass*>(p);
assert(pRes);
return pRes;
}
Is there a way to add a compile time check so I can catch calls to this function where p is not an instance of MyClas... |
Is there a way to add a compile time check so I can catch calls to this function where p is not an instance of MyClass?
Generally, if you want to check this at compile-time, you'd take the derived class as an argument.
However, if the only thing you have is a Base* or a Base&, then you cannot know whether it refer... |
3,279,733 | 3,280,304 | ofstream doesn't write buffer to file | I'm trying to write the contents of buf pointer to the file created by ofstream.
For some reason the file is empty, however the contents of buf is never empty... What am I doing wrong?
void DLog::Log(const char *fmt, ...)
{
va_list varptr;
va_start(varptr, fmt);
int n = ::_vscprintf(fmt, varptr);
cha... | Many problems can be solved by getting rid of the hairy stuff, like manual allocation management.
Never use new T[N] in your code: instead use std::vector<T> v(N);. Simply this alone might solve your problem, because the pointer stuff isn't in the way:
void DLog::Log(const char *fmt, ...)
{
va_list varptr;
va_... |
3,279,781 | 3,309,137 | Forward declaring classes in namespaces | I was rather surprised to learn that I couldn't forward declare a class from another scope using the scope resolution operator, i.e.
class someScope::someClass;
Instead, the full declaration has to be used as follows:
namespace
{
class someClass;
}
Can someone explain why this is the case?
UPDATE: To clarify, I a... | Seems as though the answer lies in the C++ specification:
3.3.5 "Namespace scope" in the standard.
Entities declared in a namespace-body
are said to be members of the
namespace, and names introduced by
these declarations into the
declarative region of the namespace
are said to be member names of the
namesp... |
3,279,869 | 3,281,369 | why is this syntax exclusively used to initialize string literals and can't be used for an array of characters? |
Possible Duplicate:
initializing char arrays in a way similar to initializing string literals
below is a sample of initializing a string literal in which a terminating null character is added at the end of string, necessarily:
char reshte[]="sample string";
I wonder why can't we initialize an array of characters wi... | I don't understand why you need the string without the terminating character so badly. Storage/performance wise, it doesn't make it an issue. You can just work knowing there's a null character at the end you don't need for your application, if you want to use that instantiation.
Or you could maybe do something like:
ch... |
3,279,897 | 3,279,926 | Convert vector<char> buf(256) to LPCSTR? | Is there a way to convert the above?
If so what is the best way?
I guess you can loop through the vector and assign to a const char*, but I'm not sure if that is the best way.
| std::string s(vec.begin(), vec.end());
// now use s.c_str()
I think this should be fairly safe.
|
3,280,197 | 3,383,899 | What's the best way to demonstrate the effect of affinity setting? | Once I noticed that Windows doesn't keep computation-intensive threads on a specific core -
it keeps switching cores instead. So I speculated that the job would be done faster, if
the thread would keep access to the same data caches. And really, I was able to observe
a stable ~1% speed improvement after setting the thr... | default affinity:
(source: dreamhosters.com)
affinity set to core #4
(source: dreamhosters.com)
Now, this is an archiver. Do you really think that the worker thread going
all around the cpu is ok?
|
3,280,410 | 3,280,465 | Why doesn't delete destroy anything? | I'm playing a little with memory dynamic allocation, but I don't get a point. When allocating some memory with the new statement, I'm supposed to be able to destroy the memory the pointer points to using delete.
But when I try, this delete command doesn't seem to work since the space the pointer is pointing at doesn't ... | It's time to learn what undefined behavior is. :)
In C++, when you do something illegal/nonsensical/bad/etc. the standard often says that "it leads to undefined behavior." This means that from that point forward, the state of your program is completely non-guaranteed, and anything could happen.
At the point where you d... |
3,280,541 | 3,280,574 | Perform vector operation | I'm using the vector container to store an array of doubles. Is there any quick
way of multiplying each element in my vector by some scalar without using a loop.
For example:
vector<double> Array(10,1);
will initialise an array of 10 doubles with initial value 1. To multiply this
array by 0.5 I would write:
fo... | You could do this:
std::transform(Array.begin(), Array.end(), Array.begin(),
std::bind2nd(std::multiplies<double>(), 0.5));
In response to getting the sum of elements:
double sum = std::accumulate(Array.begin(), Array.end(), 0.0);
And in response to getting sqrt'ing each element:
std::transform(Array.... |
3,280,562 | 3,282,124 | ctype and strings and containers | Is there any reason that the ctype facet functions (is,scan_is,scan_not only support plain char pointer, and not iterator based containers, like std::string or even a std::vector...
then one could write:
const ctype<char>& myctype = use_facet<std::ctype<char> >(locale(""));
string foo_str = "hi there here is a number: ... | The main reason is that the Standard Library wasn't developed as a single coherent whole, but incorporates several libraries that were popular at the time.
Iterators were a concept from the "Standard Template Library", which was the basis for the standard Containers, Iterators and Algorithms libraries. The Strings and ... |
3,280,738 | 3,280,845 | How to write a makefile for a C++ project which uses Eigen, the C++ template library for linear algebra? | I'm making use of Eigen library which promises vectorization of matrix operations. I don't know how to use the files given in Eigen and write a makefile. The source files which make use of Eigen include files as listed below, these are not even header files (They are just some text files)-
<Eigen/Core>
<Eigen/Dense>
<E... | According to Eigen's website, this is a header-only library.
This means there is nothing to compile or link it to. Instead, as long as you have the header files in a standard location (/usr/local/include on *nix/Mac), then all you have to do is add that location to your preprocessor build step.
Assuming that you are ru... |
3,280,828 | 3,280,859 | What does void(U::*)(void) mean? | I was looking at the implementation of the is_class template in Boost, and ran into some syntax I can't easily decipher.
template <class U> static ::boost::type_traits::yes_type is_class_tester(void(U::*)(void));
template <class U> static ::boost::type_traits::no_type is_class_tester(...);
How do I interpret v... | * indicates a pointer, because you can access its contents by writing *p. U::* indicates a pointer to a member of class U. You can access its contents by writing u.*p or pu->*p (where u is an instance of U).
So, in your example, void (U::*)(void) is a pointer to a member of U that is a function taking no arguments and ... |
3,280,864 | 3,280,900 | Source IP from UDP packet in c under window OS | I want to get the source IP of UDP packet kindly guide me so that I can make it possible. I am working in c under windows platform.
| Use the recvfrom function. It has a from parameter that points to a sockaddr structure that will receive the source address.
|
3,281,205 | 3,564,588 | Using IMFSourceResolver::CreateObjectFromByteStream | I am trying to use the IMFSourceResolver::CreateObjectFromByteStream method to create a IMFMediaSource instance for a DRM protected WMA file. I am adapting the ProtectedPlayback sample from the Windows SDK as a playground. The end goal I wish to achieve is to have the playback process fed by a custom implementation i... | @pisomojado
Thanks for the response, I totally forgot I had posted this question.
The problem was, if I remember correctly, that CreateObjectFromByteStream needs a way to identify the content type. You can either do this by passing in a URL as well as the byte stream instance (pwszURL parameter) or by making the byte ... |
3,281,465 | 3,281,506 | question about algorithm complexity | i have tried implement two methods recursive and dynamic method and both took 0 second it means that no one is better in my computer or something is wrong in code? here is these methods
1// recursive
#include <stdio.h>
#include <time.h>
#include <iostream>
using std::cout;
void print(int n){
if (n<0) return... | A second clock resolution is not suitable for measuring such fast operations.
I suggest you execute your code many times (something like 1 million times; use a for loop for this), estimate the overall time and then compute an average value.
This way you'll get more reliable results.
Just a quick note: I see you use cou... |
3,281,555 | 3,281,640 | How do I convert QMap<QString, QMap<QString, int> > to a QVariant? | QVariant (needed for QSettings class) supports creation from QMap<QString, QVariant>
But trying to initialise something like this:
QMap<QString, QVariant(QMap<QString, QVariant>)> i;
Gives the error:
function returning a function.
So then I tried the QMap<QString, QVariant> overload for QVariant() and got
error: no... | The error being reported is that QVariant(...) is not a type, but a function (c-tor).
You should have just used: Map<QString, QVariant> i; and used QVariant(QMap<QString, QVariant>) only when assigning values to the map. The point is QVariant is anything really. So a map of QVariants, can have an int in one position ... |
3,281,659 | 3,281,717 | Mixing post- and pre- increment/decrement operators on the same variable |
Possible Duplicate:
Why is ++i considered an l-value, but i++ is not?
In C++ (and also in C), if I write:
++x--
++(x--)
i get the error: lvalue required as increment operand
However (++x)-- compiles. I am confused.
| Post- and pre-increment operators only work on lvalues.
When you call ++i the value of i is incremented and then i is returned. In C++ the return value is the variable and is an lvalue.
When you call i++ (or i--) the return value is the value of i before it was incremented. This is a copy of the old value and doesn't ... |
3,281,666 | 3,281,673 | What is "operator<<" called? | I know the names of most of the operators but not sure what operator<< and operator>> are called.
i.e.
operator=() // the assignment operator
operator==() // the equality of comparison operator
operator++() // the increment operator
operator--() // decrement operator etc.
operator<() // the less-than operator
and so f... | << left shift
>> right shift
|
3,281,925 | 3,281,953 | What is default storage class for global variables? | What is default storage class of a global variable?
While searching on web I found, some sites say it is static. But, static means internal linkage and the variable can not be available outside the file scope i.e it should not be available to other object files. But, they still can be accessed to other files using decl... | The default storage duration is static, but default linkage is external. You're not the only one to find it a bit confusing. The C Book (always a good reference) says:
"You'll probably find the interactions
between these various elements to be
both complex and confusing: that's
because they are!"
The section ... |
3,281,984 | 3,282,632 | Passing objects of different types with the same interface | I have a number of class, all with exactly the same interface. This interface defines a few methods, some of which are templated (the class itself may or may not be).
So the interface looks something like this
class MyClass
{
public:
void Func1();
template <typename T>
void Func2(T param);
};
I have a number o... | What's not entirely clear to me is how you're resolving the parameter T to Func2, do you need some kind of dynamic dispatch on that too, or is it known at compile time at the call site?
In the former case, it sounds like multimethods. In the latter, how about this variation on your interface idea:
#include <iostream>
... |
3,282,133 | 3,282,175 | Writing Unicode Characters to an OStream | I'm working with unicode/wide characters and I'm trying to create a toString method (Java ::toString equiv). Will ostream handle wide characters, if so is there a way to warn the consumer of the stream that it is unicode coming out of it?
| Neither ostream nor the rest of C++ know anything about Unicode. Usually you write a string conversion in C++ as follows:
template<typename Char, typename Traits>
std::basic_ostream<Char, Traits>&
operator<<(std::basic_ostream<Char, Traits>& stream, const YourType& object) {
return stream << object.a << object.b; ... |
3,282,608 | 3,282,638 | Another C++ learning moment: returning strings from functions | I've got some basic questions about C++. Consider the following code in which I attempt to return a string.
const std::string&
NumberHolder::getValueString() {
char valueCharArray[100];
sprintf_s(valueCharArray,"%f",_value);
std::string valueString(valueCharArray);
return valueString;
}
I'm attempting... | You're defeating the point of having a std::string by allocating it on the heap!
Just return it by value like this:
std::string NumberHolder::getValueString()
{
char valueCharArray[100];
sprintf_s(valueCharArray,"%f",_value);
return std::string(valueCharArray);
}
Just about every compiler nowadays wil... |
3,282,712 | 3,283,327 | What is the equivalent type in C for REAL(KIND=real_normal) in Fortran? | I have a problem with passing of an array from Fortran to a c function:
In the fortran the array is defined as
REAL(KIND=real_normal) , DIMENSION(:), ALLOCATABLE :: array
call cFunc(array)
If define the cFunc as
void cFunc(double *data){...}
Than the data contains only "garbage" values. Where is the problem in this... | @High Performance Mark's suggestions are very good, and I highly recommend the ISO_C_Binding of Fortran 2003 (supported by numerous Fortran compilers) for interoperability between Fortran and C -- there is a larger issue here that makes the ISO_C_Binding more useful: Fortran allocatable arrays are more complicated the... |
3,282,728 | 3,282,744 | Automatic locking/unlocking using scope in C++ (from C# background) | I've been using C# for the last few years and I am currently bug fixing in C++.
In C# I could use lock on an object to make my code thread safe with:
lock(lockObject)
{
// Do some work
}
This would unlock the lockOject if there was an exception within the // Do some work
Is there something similar in C++? At the m... |
But I don't like the curly braces just to scope my AutoLock.
That's how it's done in C++.
Note that you don't need to have a separate scope block for each AutoLock; the following is fine too:
{
AutoLock lock1;
AutoLock lock2;
// more code goes here
} // lock2 gets destroyed, then lock1 gets destroyed
It ... |
3,282,885 | 3,282,906 | Standard predicates for STL count_if | I'm using the STL function count_if to count all the positive values
in a vector of doubles. For example my code is something like:
vector<double> Array(1,1.0)
Array.push_back(-1.0);
Array.push_back(1.0);
cout << count_if(Array.begin(), Array.end(), isPositive);
where the function isPositive is defined as
bo... | std::count_if(v.begin(), v.end(), std::bind1st(std::less<double>(), 0)) is what you want.
If you're already using namespace std, the clearer version reads
count_if(v.begin(), v.end(), bind1st(less<double>(), 0));
All this stuff belongs to the <functional> header, alongside other standard predicates.
|
3,283,021 | 3,283,057 | Compile a Standalone Static Executable | I'm trying to compile an executable (ELF file) that does not use a dynamic loader. I built a cross compiler that compiles mips from linux to be used on a simulator I made. I asserted the flag -static-libgcc on compilation of my hello.cpp file (hello world program). Apparently this is not enough though. Because ther... | Try using the -static flag?
|
3,283,060 | 3,283,146 | How do I run my code from the command line? | i have following code
#include <iostream>
using namespace std;
int main(int argc,char arg[]){
int a=arg[1];
int b=arg[2];
int c=a+b;
cout<<c<<endl;
return 0;
}
i am using windows 7 microsoft visual c++ 2010
how run it from command line?
| Navigate to the directory where the executable (.exe) is located. Then type the executable's name followed by two integer parameters.
C:\TestProg\> TestProg 5 6
The problems in your original example are corrected here:
#include <iostream>
#include <sstream>
int main(int argc, char *arg[])
{
std::stringstream sa... |
3,283,562 | 3,283,832 | Where on internet can we learn Secure Programming in c/c++ | I am starting to learn everything about security and secure programming.
I have always heard about things like buffer overflow vulnerability.
But I don't know yet how such vulnerabilities are exploited.
And how can we program securely enough to make sure that our code is robust.
When I say all this, my programming lang... | Check out CERT C Secure Coding Standard & CERT C++ Secure Coding Standard.
|
3,283,587 | 3,328,506 | QWidget - resize animation | Say I have a QHBoxLayout where there are 2 QTextEdits and between them a button with an arrow to the right. When you click on the button, the right-side QTextEdit gradually closes by moving the left border until it meets the right one. Simultaneously, the right border of the left QTextEdit takes the place which the rig... | Here what I wanted:
Header file
class MyWidget : public QWidget
{
Q_OBJECT
QTextEdit *m_textEditor1;
QTextEdit *m_textEditor2;
QPushButton *m_pushButton;
QHBoxLayout *m_layout;
QVBoxLayout *m_buttonLayout;
int m_deltaX;
bool m_isClosed;... |
3,283,592 | 3,283,618 | Is it not necessary to define a class member function? | The following code compiles and runs perfectly,
#include <iostream>
class sam {
public:
void func1();
int func2();
};
int main() {
sam s;
}
Should it not produce a error for the lack of class member definition?
| If you don't call the member functions, they don't have to be defined. Even if you call them, the compiler won't complain since they could be defined in some other compilation unit. Only the linker will complain. Not defining functions is accepted and common to force an error for undesired behavior (e.g. for preventing... |
3,283,778 | 3,283,795 | Why can I not push_back a unique_ptr into a vector? | What is wrong with this program?
#include <memory>
#include <vector>
int main()
{
std::vector<std::unique_ptr<int>> vec;
int x(1);
std::unique_ptr<int> ptr2x(&x);
vec.push_back(ptr2x); //This tiny command has a vicious error.
return 0;
}
The error:
In file included from c:\mingw\bin\../lib/gcc/m... | You need to move the unique_ptr:
vec.push_back(std::move(ptr2x));
unique_ptr guarantees that a single unique_ptr container has ownership of the held pointer. This means that you can't make copies of a unique_ptr (because then two unique_ptrs would have ownership), so you can only move it.
Note, however, that your cur... |
3,283,804 | 3,283,826 | c++ get milliseconds since some date | I need some way in c++ to keep track of the number of milliseconds since program execution. And I need the precision to be in milliseconds. (In my googling, I've found lots of folks that said to include time.h and then multiply the output of time() by 1000 ... this won't work.)
| See std::clock()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.