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,786,632 | 3,788,058 | C++ standard - how "array of unknown bound of T" is treated | I've got confused by the fact that this code works:
struct S
{
char c[];
};
S s;
According to C++ standard, chapter 8.3.4:
"If the constant
expression is omitted, the type of the
identifier of D is
“derived-declarator-type-list array of
unknown bound of T”, an incomplete
object type."
But I cannot figure... | You've said the code you posted will compile in VS10. Turn off language extensions, and then it won't. Project>Properties>C/C++>Language>Disable Language Extensions = Yes. This is compiling because you are using a MS-specific extension to the C++ language.
In short, according to the standard, your code should not ... |
3,786,639 | 3,788,021 | What is the better way to generate test report in a file using BOOST.Test? | I know by default report is directed to standard-error, and so one has to redirect it to a file.
My question is shall we do this inside a global fixture? Which isn't seem to be working for me some how.
This is what i tried -
struct MyConfig
{
MyConfig()
: testReport("fileName.log")
{
if(!testReport.fail())
... | You could try this alternative, adapted from here and alleged to work on Boost 1.34.1. This seems to be more as Boost intends - see the usage of a results stream overrider.
//
// run_tests.cc
//
#define BOOST_AUTO_TEST_MAIN
#include <iostream>
#include <fstream>
#include <cassert>
#include <boost/test/auto_unit_test.... |
3,786,647 | 3,786,756 | Difference between a C++ exception and Structured Exception | Can someone explain the difference between a C++ exception and a structured exception in MFC?
| You actually have three mechanisms:
C++ exceptions, implemented by the compiler (try/catch)
Structured Exception Handling (SEH), provided by Windows (__try / __except)
MFC exception macros (TRY, CATCH - built on top of SEH / C++ exceptions - see also TheUndeadFish's comment)
C++ exceptions usually guarantee automati... |
3,786,736 | 3,786,757 | Template type deduction of reference | I've been playing around with type deduction/printing using templates with code of the form:
#include <iostream>
template <typename T>
class printType {};
template <typename T>
std::ostream& operator<<(std::ostream& os, const printType<T>&)
{
os << "SomeType"; return os;
}
template <typename T>
std::ostream& op... | There is no way to work this around. An expression p, where p names a reference, always has the type the reference refers to. No expression ever has type T&. So you cannot detect whether an expression originated from a reference or not.
This cannot be done with C++0x either. It's a deep principle of C++ that there are... |
3,786,742 | 3,786,830 | error C2065: 'MIIM_STRING' : undeclared identifier | While Trying to create a Menu to SubMenu using InsertMenuItem:
MENUITEMINFO mii = { sizeof(MENUITEMINFO) };
mii.fMask = MIIM_SUBMENU | MIIM_STRING | MIIM_ID;
mii.wID = uCmdID++;
mii.hSubMenu = hSubmenu;
mii.dwTypeData = _T("Net&Work Drive Solution");
// InsertMenu ( hmenu, uMenuIndex, MF_BYPOSITION | MF_POPUP,
... | You must define WINVER to be at least 0x0500. MIIM_STRING is defined like this:
#if(WINVER >= 0x0500)
#define MIIM_STRING 0x00000040
...
|
3,786,744 | 3,786,848 | Case of names for template typename | Given a C++ template class (or function) definition:
template<typename T>
struct Foo {
T member;
};
-- if in a more complicated case I want to make the typename more expressive, what case naming conventions are accepted or shunned (and why). Examples:
template<typename MORE_EXPRESSIVE_NAME>
struct More {
MORE_EXPR... | The main thing about naming convention is consistency. Whatever the convention you adopt, please keep it throughout the project, and therefore if you jump in on a project where there is already one adopted, stick to it (if there is none, rename).
That being said, ALL caps are normally reserved for macros in most of the... |
3,786,759 | 3,786,795 | what is the correct way to define a struct inside a class? | I have a class called SparseMatrix which contain a private vector of type Cell.
Cell is a structure that should hold x,y coords and a double value.
In addition, I would like that a different class called RegMatix will be able to declare a vector of type Cell also.
this is the struct:
struct Cell {
Cell(int row,int... | If you declare Cell inside of SparseMatrix, you have to scope it to be inside SparceMatrix.
For example:
std::vector<SparceMatrix::Cell>::const_iterator start,end;
You currently have it globally scoped.
As to the best place, if you only use Cell in SparceMatrix, I would declare it in there.
|
3,786,853 | 3,786,916 | Why use an initialization method instead of a constructor? | I just got into a new company and much of the code base uses initialization methods instead of constructors.
struct MyFancyClass : theUberClass
{
MyFancyClass();
~MyFancyClass();
resultType initMyFancyClass(fancyArgument arg1, classyArgument arg2,
redundantArgument arg3=TODO... | Since they say "timing", I guess it's because they want their init functions to be able to call virtual functions on the object. This doesn't always work in a constructor, because in the constructor of the base class, the derived class part of the object "doesn't exist yet", and in particular you can't access virtual f... |
3,786,878 | 3,786,936 | Which of the following is not allowed according to inheritance usage? | From here,
Using inheritance, which of the following is not allowed
a) Changing implementation of operation in parent by the subclass
b) Using implementation of operation in parent class by the subclass
c) Using attributes in parent class by the subclass
d) Having operations is subclass which do not exist in parent cla... | The answer is e) none.
|
3,787,074 | 3,787,088 | Convert std::vector to array | I have a library which expects a array and fills it. I would like to use a std::vector instead of using an array. So instead of
int array[256];
object->getArray(array);
I would like to do:
std::vector<int> array;
object->getArray(array);
But I can't find a way to do it. Is there any chance to use std::vector for this... | Yes:
std::vector<int> array(256); // resize the buffer to 256 ints
object->getArray(&array[0]); // pass address of that buffer
Elements in a vector are guaranteed to be contiguous, like an array.
|
3,787,350 | 3,787,453 | C++ templates and inheritance | can I mix inheritance and templates this way ? :
template <class T>
class AbstractType { // abstract
//....
}
template <class T>
class Type1 : public AbstractType<T> {
//....
}
And later on, can I use these classes like this:
AbstractType<SomeClass>* var1 = new Type1<SomeClass>();
Thx for help.
| You can, but it's not going to be as useful as you may think. You can define the structures like this:
#include <string>
#include <vector>
using namespace std;
template<typename Val>
class Base
{
public:
virtual Val DoIt() const = 0;
};
template<typename Val>
class Derived : public Base<Val>
{
public:
Derive... |
3,787,845 | 3,787,930 | Unqualified lookup and (maybe-)dependent base classes | Consider the following program:
template <typename T>
struct t
{
struct base { void f1(); };
struct derived : base
{
void f2()
{
f1();
}
};
};
In derived::f2, unqualified lookup is used to find f1. Will base be searched? Will base::f1 be found? Is base a dependent ty... | Yes, base is dependent so f1 is not found. In C++03 this was clearified by the addition 14.6.1/2d (which did not exist in C++98) and in C++0x this is directly stated by 14.6.2.1/6 (n3126).
Dependency of it is important, because the following is possible
// for T = int, f1 does not exist.
template<> struct t<int>::base... |
3,788,005 | 3,788,075 | Deleting object from a stack | Is it bad/illegal C++ to delete manually objects from a stack or there are situation when it is acceptable?
Edit
Constructor(pointer parent, pointer left, pointer right):parent_(parent),left_(left), right_(right)
{ }
~Constructor()
{
delete parent_;
delete left_;
delete right_;
... | Yes, it is bad to delete automatic variables (ie, objects on the stack). I suppose there is still no "never" in programming, but I can't think of a time/reason why you would want to do this.
What scenario are you thinking of?
EDIT: Actually, not only is it bad, it is illegal:
5.3.5 Delete
1: The delete-expression op... |
3,788,117 | 3,788,780 | Using program as library that contains main function | I am planning to write a program that makes calls to cdrecord. (I am a beginner, a beginner trying to "scratch an itch") The program would be written in C++. I have identified that I need to be able to run cdrecord in order for this to work.
cdrecord is written in C. However the documentation on using it is from the co... | system() is generally a nice way to go, just be careful not to inject arbitrary untrusted values into the string you execute. For example, if you have a web frontend where with a padsize option defaulted to 0, and someone types in not a number but "0; rm -rf *;", make sure you don't end up calling "cdrecord padsize=0;... |
3,788,126 | 3,788,156 | declaring a pointer to a two dimension array of void* | I'm having trouble figuring out how to declare a pointer to an array of arrays of void*. (I can't use STL containers and the like because it's an embedded system.)
I have some data that I'm trying to group together in a structure. Mostly built-in data types, but then are these two arrays. The first one,
char *testpanel... | Make life a bit simplier and use typedefs
identity<void*[4]>::type *panelDesc;
Or equivalent
typedef void *type[4];
type *panelDesc;
I doubt you know what the following means, but suffice it to say it's equivalent too
void *(*panelDesc)[4];
Note that based on type, it is not a "a pointer to a two dimension array of ... |
3,788,135 | 3,788,150 | What do the * and & operators operate on if the argument is complex? | Simply, is
&someObject->someAttribute.someMember;
equivalent to
&(someObject->someAttribute.someMember);
or
(&someObject)->someAttribute.someMember;
or
(&(someObject->someAttribute)).someMember;
Or should you really put explicit parenthesis there just to be safe?
| It is equivalent to:
&((someObject->someAttribute).someMember)
The -> and . have equal precedence and are left-associative. The unary-& has lower precedence.
If you have very complex expressions, then you should certainly use parentheses to group things and clarify your code. This isn't particularly complex, though;... |
3,788,198 | 9,054,439 | Something like boost::multi_index for Python | I have come to appreciate a lot boost::multi_index in C++. It happens that I would happily use something like that in Python; for scripts that process data coming out from numerical intensive applications. Is there such a thing for Python? I just want to be sure that it doesn't exist, then I would try to implement it m... | To answer your question of whether a similar thing exists in Python, I would say no.
One useful feature of Boost.MultiIndex is that elements can be modified in-place (via replace() or modify()). Python's native dict doesn't provide such a functionality and requires the key to be immutable. I haven't seen other implem... |
3,788,298 | 3,788,375 | Looking for a good book covering CURL library under c++ | are there any good books/tutorials decscribing how to use CURL library under C++ to implement FTP / SFTP clients ? Thx for help.
| For the C++ bindings for CURL, see the docs at http://curlpp.org/ . There are extensive examples there; no need to get a book (in all likelihood).
|
3,788,386 | 3,788,453 | reading char by char | my question is a little bit strange, but how is it possible to read some string from keyboard char by char without using scanf() and getchar() only by using operator<<, for example I want to change every letter a which I read by * thanks in advance
| char c;
std::string output;
while(std::cin >> c)
{
if(c == 'a')
c = '*';
output += c;
}
|
3,788,391 | 3,788,422 | Return Array from Class | I need to return 3 values. X, Y, Z.
I've tried something like this, but it does not work, can anyone help me a bit? I've looked here: Return a float array in C++ and I tried to do same thing, except with 1 dimensional array to return.
class Calculate
{
float myArray[3][4], originalArray[3][4], tempNumbers[4];
float r... | Instead of returning a pointer, it's usually better practice to accept a pointer and write out the results there. That way someone can allocate a regular array on the stack and have it initialized by your Calculate.
Something like:
class Calculate
{
float myArray[3][4], originalArray[3][4], tempNumbers[4];
public:
C... |
3,788,424 | 3,855,086 | VS2010 C++ does not include paths to .pdb is my compiled .dlls according to dumpbin | Visual Studio compiles the projects into dlls as I want it to, but when I inspect these dlls with dumpbin, then they do not have an entry for their pdbs, which is probably the reason why I cannot debug any of those dlls if I load them at runtime and their pdbs are never loaded. How can I get VS to write these paths?
Vi... | If dumpbin /headers shows no entry in the Debug Directories, it is probably because you did not enable debug information generation at compile and link time. You should check the C++/General/Debug Information format and the Linker/Debugging/Generate Debug Info options.
If these options are set, you may check if the dll... |
3,788,769 | 3,788,974 | Getting started with a cross platform C++ project | I am starting a c++ project which I would like to compile equally well in Eclipse (Linux) and vs2010 from the same repository and could use some help getting started. While many of the aspects can individually be Google'd, I was hoping for advice on how to approach the problem on a whole.
For example, where to keep th... | I have done cross platform projects that used the "native" build systems on both platforms (vsproj files on windows and makefiles on linux), but it was definitely a pain to maintain both project files. So, yes, I would agree with the other suggestions that you should try to start with a solid cross platform build utili... |
3,788,921 | 3,789,288 | Reusing interfaces throughout your application | I am currently busy refactoring big parts in my application. The main purpose is to remove as much as possible dependencies between the different modules. I now stumble on the following problem:
In my application I have a GUI module that has defined an interface IDataProvider. The interface needs to be implemented b... | Why don't you do an intermediate implementation? Have some class implement recurring parts of IDataProvider (as in the 1st case) in a factored-out library (or other layer). Also, everyone is required to "implement" their own IDataProvider (as in the 2nd case). Then, you can re-use your IDataProvider implementation all ... |
3,789,150 | 3,789,184 | null terminator problem while comparing identical char* | i try to compare between 2 char* identical strings,but one of them contains a null terminator at the end.
i've been looking through the internet and understood that it's not recommendable to remove the null terminator char cause it will make the string unstable.
what other methods can i use?
the comparing function:
int... | You are using strlen which requires a null terminator at the end of the string. If one of the strings you pass doesn't have a terminator, you are guaranteed to fail.
|
3,789,340 | 3,789,553 | Combining C++ and C - how does #ifdef __cplusplus work? | I'm working on a project that has a lot of legacy C code. We've started writing in C++, with the intent to eventually convert the legacy code, as well. I'm a little confused about how the C and C++ interact. I understand that by wrapping the C code with extern "C" the C++ compiler will not mangle the C code's names,... | extern "C" doesn't really change the way that the compiler reads the code. If your code is in a .c file, it will be compiled as C, if it is in a .cpp file, it will be compiled as C++ (unless you do something strange to your configuration).
What extern "C" does is affect linkage. C++ functions, when compiled, have the... |
3,789,503 | 3,789,532 | invalid cast to type 'float' | I'm having problem with my class. I'm going to make comparision operators of my class.
Some code:
CVariable::operator float ()
{
float rt = 0;
std::istringstream Ss (m_value);
Ss >> rt;
return rt;
};
bool CVariable::operator < (const CVariable& other)
{
if (m_type == STRING || other.Type() == STRIN... | Your conversion operator is non-const but the object other refers to is const-qualified. You have to add const to the conversion operators like this:
operator int () const;
operator float () const;
operator std::string () const;
This const also needs to be added to the definitions.
|
3,789,560 | 3,789,639 | Calling 64-bit COM control from 32-bit app | We have a situation where one of our products is a 32-bit app, but needs to communicate with instruments via 64-bit COM control (which wraps a 64-bit device driver). For various reasons, we don't want to compile this app as a 64-bit app, but we DO want to run it on a 64-bit OS. Since the drivers and COM control must b... | May work fairly directly, as long as the COM interface only uses types which can be automatically marshaled by the COM subsystem (eg: automation compatible).
You will need to make sure the other COM object is running in it's own process space; if it's not designed to do so, putting it inside a [server type] COM+ applic... |
3,789,678 | 3,789,814 | is it possible for set to have std::vector as underlying storage for storage of its elements? | For small collections std::vector is almost certainly the best container whatever the operations applied to it are. Is it possible to have std::vector as underlying storage for the elements set container instead red-black tree involving a lot of heap allocations (maybe boost has something?) or do I have to invent it my... | There is no way to specify the underlying structure of an STL set. At best you can write an allocator that uses a vector to provide the memory used by set which may or may not be what you want.
|
3,789,706 | 3,790,060 | C++ Pointer Question | I apologize since this is rather a n00bish question, but I can't figure this one out.
class View //simplified
{
public:
ROILine* ROI() {return _roi;} //setter does some control stuff...
private:
ROILine *_roi;
}
class ROI : public eq::Object
{
public:
//virtual ROI(ROI* copy) = 0;
virtual ~ROI() {};
... | Assuming that everything in your copy constructor for ROILine is working correctly, then here is a possibility: Something has overwritten a few bytes of the ROILine instance returned by View::ROI().
Most likely, the first several bytes of a ROILine object contain a pointer to the virtual function table for that class. ... |
3,790,023 | 3,790,074 | C++: how to access a multidimensional array with pointers? | Given: (In C++)
int main () {
int* ptr;
int ary [10][2];
ptr = ary;
return 0;
}
How would I access ary[0][1] with ptr?
| You can't, because the type of ptr is wrong. The variable should be declared as int(*)[2] (pointer to an array of size 2 of integers). Then you could just use ptr[0][1].
#include <cstdio>
int main () {
int (* ptr) [2]; // <--
int ary [10][2];
ptr = ary;
ary[0][1] = 5;
printf("%d\n", ptr[0][1])... |
3,790,082 | 3,790,307 | C++ boost variant question | I know that boost::variant uses boost::mpl stuff behind it and has a mpl-compatible typedef types.
Let's say I have a simple typedef: typedef boost::variant<bool, int> Variant;
Now I have another template function, let's say:
template <typename T> T function() {
// ...
}
I want this function to act differently for... | It is indeed possible, Variant::types meets the requirement of a Mpl.Sequence type and therefore can be queried like any sequence.
Therefore, using boost::mpl::contains from here:
// using C++0x syntax to demonstrate what CONDITION should be replaced with
template <typename T>
using Condition = boost::mpl::contains<Var... |
3,790,199 | 3,790,483 | Are there standard restrictions on C++ features? | I am about to start a new realtime project. Now there is (again) the debate about c vs c++. Yes I read about Linus and all the other threads on SO.
First I was tending more towards to use C but then I read an answer that C++ includes C. Then I read on the internet about "Embedded C++".
According to this article EC++ ... | I develop professional software for an embedded platform (ARM). We use C++.
We do have a number of common and reasonable guidelines, but nothing that is specifically there because of embedded systems. We have no restrictions on C++ features (no exception ban etc).
A "feature guideline" might help you but will not elimi... |
3,790,403 | 3,790,830 | Can I debug a core generated by a C++ binary without debug symbols using the same binary recompiled with debug symbols | I am trying to debug a core file generated by a C++ binary without debug symbols. In order to do effective debugging, I need the debug symbols, so I've recompiled the same code with -g option in order to generate debug symbols in the recompiled binary. Can I now debug the same core file generated by the first binary ... | If you compiled original executable with e.g. g++ -O2 ..., you can not (as you probably have discovered) use a new executable built with g++ -g ... to debug the core -- GDB needs the symbols to match, and they would not (due to difference in optimization levels).
What you can do is build the new executable with the sam... |
3,790,452 | 3,790,492 | Floating point comparison - Result between different runs | I know that I can not compare two floating point or double numbers for absolute equality on C++/C. If for some reason, I write a if condition which uses the absolute equality, is it guaranteed that the if condition will return the same result on different runs of the program for same data? Or it is purely non-determini... | For the same compiled binary and on the same PC, results should be the same. If you use another compiler or another PC, results may vary.
|
3,790,613 | 3,790,661 | How to convert a string of hex values to a string? | Say I have a string like:
string hex = "48656c6c6f";
Where every two characters correspond to the hex representation of their ASCII, value, eg:
0x48 0x65 0x6c 0x6c 0x6f = "Hello"
So how can I get "hello" from "48656c6c6f" without having to create a lookup ASCII table? atoi() obviously won't work here.
| int len = hex.length();
std::string newString;
for(int i=0; i< len; i+=2)
{
std::string byte = hex.substr(i,2);
char chr = (char) (int)strtol(byte.c_str(), null, 16);
newString.push_back(chr);
}
|
3,790,713 | 3,790,789 | directx rotation c++ | Okay this is a hard question. I'm creating a cube and a pyramid in one vertex array. My problem is to rotate only pyramid vertex not the cube vertex but I don't know any function that can rotate some vertex. If I try to rotate the vertex I'll get pyramid and cube rotated.
| Either
put the cube and the pyramid in
different vertex arrays and use
different transforms to render each array
or
apply the rotations in a vertex
shader, and pass in some auxiliary
per-vertex info which lets the vertex
shader decide whether each vertex
should be treated as part of the cube or the pyramid (ie apply... |
3,790,865 | 3,790,911 | What is the correct type for this parameter? | This one is for all you ALSA guys. I need a sanity check here. I am using the the alsa-lib api to play sounds and the function that I am using to write the data to the driver is
snd_pcm_sframes_t snd_pcm_writei (snd_pcm_t* pcm,
const void* buffer,
snd... | According to the documentation, it's the amount of frames, not bytes.
In the example you linked to the values just happen to be the same because it's using 8-bit samples and one channel, and one frame of one channel 8-bit data is one byte.
|
3,791,022 | 3,791,050 | Using equal(),find() on a vector<complex <double> > | This is a pretty straightforward thing, but I've been bashing my head trying to understand. I'm trying to compare the elements of a vector<complex <double> > vec with a complex <double> num to check if num already exists on vec. If it does, it is not added. I tried to use the equal() and algorithm, with no success. Doe... | The std::equal algorithm is used to compare 2 iterator ranges. So you would use it to compare, for example, 2 vectors to see if both vectors contain the same elements.
In your case, where you only need to check if a single element is inside the vector, you can just use std::find
if (std::find(vec.begin(), vec.end(), s... |
3,791,085 | 3,791,685 | Passing a structure as a template-parameter - How can I fix this code? | I'm trying to compile the following code under VC2010.
struct CircValRange
{
double a,b; // range: [a,b)
};
template <struct CircValRange* Range>
class CircVal
{
// todo
};
const CircValRange SignedDegRange= {-180., 180.};
CircVal<SignedDegRange> x;
I'm getting
error C2970: 'CircVal' : template parameter ... | Someone has recommended a constructor parameter, which I second. But you can still do it as originally desired
struct CircValRange
{
double a,b; // range: [a,b)
};
template <CircValRange const& Range>
class CircVal
{
// todo
};
extern const CircValRange SignedDegRange= {-180., 180.};
CircVal<SignedDegRange>... |
3,791,259 | 3,791,624 | Where does the word "pragma" come from? | So I know what pragma is, and what it's used for, but what is the meaning of the word itself? I've used it many times in code, but I never really knew what the word actually means or stands for.
| According to a US Government-owned(!) document describing the design of Ada: Rationale for the Design of the
Ada® Programming Language :
A pragma (from the Greek word meaning
action) is used to direct the actions
of the compiler in particular ways,
but has no effect on the semantics of
a program (in general).
... |
3,791,296 | 3,791,318 | Is there any difference between a public nested class and a regular class? | Let's say I have:
class A {
public:
class B {
};
};
Is there any difference between that public nested class and just a regular B class which is defined in its own cpp file, except for the fact that A::B must be used in the first option?
| There is essentially no difference, except that A::B is a member of A, and so has all the access rights to private members of A that any other member would have.
|
3,791,517 | 3,791,580 | Enumerated type with arbitrary integer values | I want something like
enum EnumType {val1 = -1, val2 = 1};
enum EnumType2 {val1 = 1, val2 = -1};
In particular, val1 and val2 depend on the enumerated type--EnumType or EnumType2.
So I eventually want to be able to say something like
EnumType x = val1;
EnumType2 y = val1;
and have x and y have different values.
Is th... | I may be mistaken but I think the ambiguity in your example can be resolved with EnumType::val1 and EnumType2::val1
|
3,791,521 | 3,791,555 | shared_ptr allocation optimization | Somewhere I saw a post about an optimized way of creating a boost shared_ptr so that it allocated the ptr plumbing and the pointee at the same time. I did a SO search but there are a lot of posts on shared_ptr and I could not find it. Can somebody smart please repost it
edit:
thanks for answer. extra credit question. W... | See boost::make_shared():
Besides convenience and style, such a function is also exception safe and considerably faster because it can use a single allocation for both the object and its corresponding control block, eliminating a significant portion of shared_ptr's construction overhead. This eliminates one of the maj... |
3,791,591 | 3,792,853 | OpenGL ES render bitmap glyph as texture positioning issues | I'm just testing this stuff out, so I don't need an alternate approach (no GL extensions). Just hoping someone sees an obvious mistake in my usage of GLES.
I want to take an bitmap of a glyph that is smaller than 32x32 (width and height are not necessarily powers of 2) and put it into a texture so I can render it. I've... | The mapping between vertex coordinates and texture coordinates seems to be mixed up. Try changing your vertex coordinates to:
const GLfloat vertices[] = {
x, y + bitmap.height(),
x + bitmap.width(), y + bitmap.height(),
x, y,
x + bitmap.width(), y
};
As an aside:
I don't think you need to go the route via ver... |
3,791,726 | 3,791,773 | How do I learn Visual C++? | I'm interested in learning how to program using Microsoft's Visual C++ for Windows. In particular, I want to know how to make applications for the Windows platform.
I'm already a professional programmer. I know the C and C++ languages as well as many other languages in depth, I just haven't done any Windows programming... | WPF is the latest UI framework from Microsoft, it has lots of advantages over System.Windows.Forms which is its predecessor in .NET. It might be easiest to learn C# and do the UI stuff in WPF, and call out to native C++, only as needed. If you want to stick to only C++, you can also use managed C++ (C++/CLI) with bot... |
3,791,761 | 3,791,809 | C++ common interface for "cin" and "File" | Is there a common interface for cin and file input?
I want to make a program that has an optional parameter
prog [input-file]
If an input file is specified, then it should read from the file, and if not, it should read from cin.
From what I can tell, they both implement istream. How would you set up it so that I could... | #include <iostream>
#include <fstream>
int main(int argc, char **argv)
{
std::ifstream f;
if (argc >= 2) {
f.open(argv[1]);
}
std::istream &in = (argc >= 2) ? f : std::cin;
// use in here
}
You could shift some of this work into a helper class to make it clearer what's going on (note that... |
3,791,976 | 3,814,317 | is the MSVC++2010 debugger limited? | i'm trying to check what's in my set in the debugger,
i have 170 objects in it but i can only see 99 of them,
is the debugger limited?
he can show only 99 objects?
can i see all the objects?
thanks.
| VS2010 RC - only 100 std::map elements in debugger
|
3,792,277 | 3,792,283 | compiling crash - using a member function within another member function | I am attempting a simple time display program in C++.
Edited
#include <iostream>
#include <cstdlib>
#include <iomanip>
#include <string>
using namespace std;
class vClock
{
public:
// constructor
vClock(int = 0, int = 0);
// mutable member functions
void set_time(int, int);
... | That's because time_notation returns void. A void cannot be printed as it is an incomplete type.
Not sure though why IDE should crash.
Fix probably is to change time_notation to return 'string' type.
|
3,792,279 | 3,792,289 | Testing C/C++ source code |
Possible Duplicates:
Suggestion for UnitTest tools for C++
Choosing a C++ unit testing tool/framework
Unit Testing C Code
This is something I've been wondering now that we have to use C/C++ as base language for some of our university projects :
In Java there's JUnit,
In PHP there's PHPUnit
etc.
How are unit testing ... | Boost has an excellent unit test library.
|
3,792,303 | 3,792,959 | Boost C++ Libraries: Unit Test Assertion on % Processor Usage | I'm writing a unit test with Boost.Unit, and the code I'm testing must not exceed 50% of a single CPU during a portion of the unit test. How could I make this assertion from within the source code?
| Use the times call - according to the man page:
NAME
times - get process times
SYNOPSIS
#include <sys/times.h>
clock_t times(struct tms *buf);
DESCRIPTION
times() stores the current process times in the struct tms that buf points to. The struct
tms is as defined in :
struct tms... |
3,792,319 | 3,792,448 | Boost C++ Libraries: Unit Test Assertion on Deadlocks | I'm writing a unit test with Boost.Unit, and I would like to include basic tests for deadlocks in the code I'm testing. My first idea was to set a deadline timer in one thread while running the test in another that is expected to finish well before the deadline. When the timer goes off, assert that the thread is not ru... | One question is, are you testing for actual deadlocks (i.e. to see if a deadlock HAS happened) or potential deadlocks (i.e. to see if a deadlock COULD happen)?
If you only care about detecting actual deadlocks, then something like what you describe can work. However, I'm not sure that will be all that useful, since n... |
3,792,412 | 3,792,427 | const and static specifiers in c++ | #include<iostream>
using namespace std;
class A
{
private:
const int a=9;
public:
void display()
{
cout<<a;
}
};
int main()
{
A a;
a.display();
return 0;
}
Why does initialization const int a=9 ... | Use constructor initializer list to initialize non-static constant members.
ISO C++03 says the following things about static data members.
[class.static.data]
9.4.2 Static data members
1 A static data member is not part of the subobjects of a class. There is only one copy of a static data member shared by all the ob... |
3,792,600 | 3,792,615 | Erase-remove idiom with std::set failing with constness-related error | Can someone help me out here?
Compiling this code:
void test()
{
std::set<int> test;
test.insert(42);
test.erase(std::remove(test.begin(), test.end(), 30), test.end()); // <- Line 33
}
Is generating the following error when compiling:
$ make
g++ -c -Wall -pedantic-errors -Wextra -Wunused -Werror a_star.cpp
/usr... | In std::set, the elements are not modifiable. So, the std::set::iterator is also unmodifiable. From this tutorial, section 27.3.2.1:
In simple associative containers,
where the elements are the keys, the
elements are completely immutable; the
nested types iterator and
const_iterator are therefore the same.
He... |
3,792,736 | 3,792,929 | How to convert this code to use string | char * recursivecombo(char *str, int choices, int level)
{
int len = strlen(str);
level++;
if( level == choices)
{
for (int i = 0; i < len -2; i++)
{
printf("%c", str[i]) ;
}
}
else
{
for (int i = 0; i < len - 2... | std::string recursivecombo(const std::string& str, int choices, int level)
{
level++;
for (int i = 0; i < str.length() -2; ++i)
{
cout<<str.at(i) ;
if( level != choices)
recursivecombo(str.substr(1),8,/*Missing choce*/ level);
}
/*Missing return value*/
}
This is just a m... |
3,792,800 | 3,792,834 | Simple Operator question. += | So my friend gave me some source code to start out with so I could review and understand it and I have a question about it, but since he's not online I thought I would try here, mainly I don't quite understand this line.
num += i;
Essentially, this is the same as
num = num + i
right?
If you need more details pleas... | From ISO C++03 (Section 5.17/7)
The behavior of an expression of the form E1 op= E2 is equivalent to E1 = E1 op E2 except that E1 is evaluated only once.
|
3,792,817 | 3,792,921 | directx tutorials c++ | im searching for full directx tutorials i found directxtutorial.com but it only gave me the basic. couldn't find others that were full tutorials.
have you find any or know any?
| I presume you mean Direct3D, in which case you can find some good stuff over at the MSDN.
http://msdn.microsoft.com/en-us/library/ee416804%28v=VS.85%29.aspx
|
3,792,856 | 3,793,575 | Eliminating temporaries in operator overloading | Note: as noted by sellibitze I am not up-to-date on rvalues references, therefore the methods I propose contain mistakes, read his anwser to understand which.
I was reading one of Linus' rant yesterday and there is (somewhere) a rant against operator overloading.
The complaint it seems is that if you have an object of ... | If you're thinking about a custom, move-enabled string class, the proper way to exploit every combination of argument value categories is:
S operator+(S const& lhs, S const& rhs);
S operator+(S && lhs, S const& rhs);
S operator+(S const& lhs, S && rhs);
S operator+(S && lhs, S && rhs);
The functions re... |
3,792,906 | 3,792,915 | What gets converted to what when comparing a double to an integer for identity? | OK, so I know you're generally not supposed to compare two floating-point numbers for equality. However, in William Kahan's How Futile are Mindless Assessments of Roundoff in Floating-Point Computation? he shows the following code (pseudo-code, I believe):
Real Function T(Real z) :
T := exp(z) ; ... | Yes and yes.
For 32-bit ints, double can represent every value precisely. When you compare a double to a 64-bit int, however, there will be potential roundoff error if the int is greater than 2^52. You can use long double, though, which has at least 64 bits of mantissa.
Of course, the best way is just to use a floating... |
3,792,923 | 3,792,925 | How to make function return string in c++ |
Possible Duplicate:
How to convert this code to use string
I have a function like this:
char *foo()
{
}
How can I make it return a string instead? I tried
string foo()
{
}
but the compiler complains.
| Did you do this:
#include <string>
using std::string;
And additionnally, do you use gcc or g++? Even if gcc now can compile C++ code, it is advised to use g++.
|
3,793,030 | 3,793,170 | Mapping Languages to Paradigms | I recently read Eric Steven Raymond's article "How To Become A Hacker" and I like his suggestion of learning 5 key languages (he suggests Python, C/C++, Lisp, Java, and Perl) as a way of covering the main programming paradigms in use today.
His advice is that it's not so important which specific languages a programmer ... | I think you're approaching it wrong. As esr himself says, it's not the language that matters, it's the paradigm. So when you say that
Perl is a functional language
It's great for quick text substitutions in multiple files from the command line
you are missing one of the main points of a functional language which i... |
3,793,063 | 3,793,086 | what is the difference between friend function and friend class? | what is the difference between friend function and friend class? and where should be use of friend keyword?
| In short, one is a class and one is a function. For the function, just that one function gets access to private members. For a class, the whole class and all its functions get access to the private members of the befriended class.
The friend keyword is used to grant access to private data members. At times you may need... |
3,793,116 | 3,793,201 | How to make this function recursive | void print_combinations(const std::string &str)
{
int i, j, k;
int len = str.length();
for (i = 0; i < len - 2; i++)
{
for (j = i + 1; j < len - 1; j++)
{
for (k = j + 1; k < len; k++)
// show combin... | Here is a try:
#include <iostream>
#include <string.h> // for strlen
#include <stdlib.h> // for atoi
#include <sstream>
void expand_combinations(const char *remaining_string, std::ostringstream& i, int remain_depth)
{
if(remain_depth==0)
{
std::cout << i.str() << std::endl;
return;
}
fo... |
3,793,151 | 3,793,212 | Templates :Name resolution:Dependent template arguments : -->can any one tell some more examples for this statement? | This is the statement from ISO C++ Standard 14.6.2.4:
Dependent template arguments :
A type template-argument is dependent if the type it specifies
is dependent.
An integral non-type template-argument is dependent if the constant
expression it specifies is value dependent.
A non-integral non-type templat... | This is what I understand. I have marked the individual code snippets in the code inline marked according to the line numbers in the OP.
struct A{
void f(){}
};
template<class T> struct B{};
// The template argument B<T> is TYPE depdent on the template parameter T (1)
template<class T, class ... |
3,793,410 | 3,793,423 | Benchmarking math.h square root and Quake square root | Okay so I was board and wondered how fast math.h square root was in comparison to the one with the magic number in it (made famous by Quake but made by SGI).
But this has ended up in a world of hurt for me.
I first tried this on the Mac where the math.h would win hands down every time then on Windows where the magic nu... | There are several problems with your benchmarks. First, your benchmark includes a potentially expensive cast from int to float. If you want to know what a square root costs, you should benchmark square roots, not datatype conversions.
Second, your entire benchmark can be (and is) optimized out by the compiler because i... |
3,793,634 | 3,793,694 | Is it preferred to access the first dimension first than to access the second dimension of a 2 dimension array? | Here is the code,
int array[X][Y] = {0,};
// 1 way to access the data
for (int x = 0; x < X; x++)
for(int y = 0; y < Y; y++)
array[x][y] = compute();
// the other way to access the data
for (int y = 0; y < Y; y++)
for (int x = 0; x < X; x++)
array[x][y] = compute();
Is it true that the first way is more ... | You'll understand this better if you draw a picture of your array in memory:
Y ->
X xxxxx ...
| xxxxx
v xxxxx
.
.
The adress you access will grow linear in Y direction (345, 345+1, 345+2...), but jumps wildly in X direction if Y is large (345, 345+X, 345+X*2). As the cache loads blocks of memory, you'll jump out... |
3,793,716 | 3,793,732 | Beginner C++ Using accessors / getters to pull data from a private member variable (2D array) | total noob here with about 2 months of C++ experience (no other background) so go easy on me.
I am writing a battleship game for a programming assignment. The game grid is 15X20 and I am trying to have the grid as a private member variable of the class player.
My question is:
If the class player has a private member... |
Is there any reason why an accessor
function, defined as:
char getgrid(int index1, int index2)
{
return playgrid[index1][index2];
}
wouldn't work?
Yes. A function declared like this would not be a member function of a class. You probably meant
char player::getgrid(int index1, int index2)
{
// ...
}
|
3,793,773 | 3,793,793 | Accurate benchmark under windows | I am writing a program that needs to run a set of executables and find their execution times.
My first approach was just to run a process, start a timer and see the difference between the start time and the moment when process returns exit value.
Unfortunately, this program will not run on the dedicated machine so man... | You can take a look at GetProcessTimes API.
|
3,793,809 | 3,793,842 | Removing the command prompt | In C++, what is the standard way to remove the command prompt, without using WinMain()? This is hopefully a simple question. I am using MSVC.
| First you need to set /SUBSYSTEM:WINDOWS (as opposed to /SUBSYSTEM:CONSOLE), you can do this in GUI (right click the project, properties, Linker, System, Subsystem).
Then you have to either
define WinMain, or
define main and set the entry point to mainCRTStartup (properties, Linker, Advanced, entry point).
|
3,794,036 | 3,794,322 | How can I parse different structures with Boost.Spirit.Qi? | In this example, employee structs are parsed in the form "employee{int, string, string, double}".
I would like to know whether it is possible to modify this example to also parse different types of structs, like "intern{int, string, string}".
Specifically, I would like to then pass the structure to a function overloade... | Sure, that's possible. Create a rule for each of the types you want to parse:
rule<Iterator, std::string()> s = ...;
rule<Iterator, intern()> intern_r = int_ >> s >> s;
rule<Iterator, employee()> employee_r = int_ >> s >> s >> double_;
and combine those into an alternative:
rule<Iterator> r =
intern_r [phoe... |
3,794,174 | 3,794,198 | c++ string: is there good way to replace a char inside a string | I want to replace all the occurances of ' in a string to ^, but i saw string.replace is not the right function for me, do I need to write my own? It's boring.
| You can use std::replace from <algorithm> instead of using string::replace from <string>
Sample code
#include <iostream>
#include <algorithm>
int main()
{
std::string s = "I am a string";
std::replace(s.begin(),s.end(),' ',',');
std::cout<< s;
}
Output : I,am,a,string
|
3,794,252 | 3,794,292 | Strange stack/string behaviour | stack <char> stck;
string str;
stck.push('0');
str.append("test:");
//test:
cout << str << endl;
str.append(&stck.top());
//test:0═══════════════¤¤¤¤▌▌▌▌,╘╥XЕ┤
cout << str << endl;
Why is this happening?
| Maciej Hehl is correct about why you're getting unwanted behavior.
To get the behavior that you want, you need to append the character itself, not a pointer to it. You are correct in saying (in your comment to Kalim's answer) that there is no override of std::string::append that takes just a char. However, there is an ... |
3,794,358 | 3,794,396 | how to parse HTTP POST(file upload) stream? | I am using actionscript engine to upload a file, the engine will select the file and send the file over network thru HTTP POST command, the document says the POST message is like:
POST /handler.cfm HTTP/1.1
Accept: text/*
Content-Type: multipart/form-data;
boundary=----------Ij5ae0ae0KM7GI3KM7ei4cH2ei4gL6
Use... | No, there is no encoding. The body of each subpart of the multipart message is included as verbatim bytes. Consequently you have to be careful to choose a boundary string that doesn't occur anywhere in the file data.
To parse a multipart/form-data form submission you will enough of a MIME parser to parse the headers, p... |
3,794,463 | 3,794,472 | What is the order of evaluating boolean sentence? |
Possible Duplicate:
Is short-circuiting boolean operators mandated in C/C++? And evaluation order?
Is there any defined by standard or math rules order of eveluating boolean sentences? For example:
if (firstTrue && secondTrue)
{
}
can I be sure that firstTrue will be checked first?
| Yes. && and || are short circuiting operators. The order of evaluation of operands is well defined (left to right).
&& is also a sequence point.
So writing if( ++i && i) { } is perfectly fine.
ISO C++03 (5.14/1) says:
The && operator groups left-to-right. The operands are both implicitly converted to type bool (claus... |
3,794,649 | 3,794,884 | Qt events and signal/slots | In the Qt world, what is the difference of events and signal/slots?
Does one replace the other? Are events an abstraction of signal/slots?
| The Qt documentation probably explains it best:
In Qt, events are objects, derived
from the abstract QEvent class, that
represent things that have happened
either within an application or as a
result of outside activity that the
application needs to know about.
Events can be received and handled by
any i... |
3,794,821 | 3,796,099 | Qt: How to put collection of GUI-Elements into independent SubClass (with seperate *.ui file) | I'm trying to collect an often used subset of GUI-Elements together into one Subclass, which can be "included" into the real GUIs later without rewriting the given functionality (don't ask why, I wanna learn it for later use). The Subclass should use it's own *.ui-File and should be put into an QWidget resding in the r... | So, the answer is in the real GUI class. The Constructor:
testLogger::testLogger(QMainWindow *parent) : QMainWindow(parent){
setupUi(this);
myLog = new logger(widget_loggerArea);
}
In main.cpp:
QApplication app(argc, argv);
testLogger window;
window.show();
And in constructor of logger, setupUi works with "t... |
3,794,931 | 3,794,970 | iostream and sstream for Objective-C | I'm trying to port some C++ code to Objective-C. It includes iostream and sstream, but Objective-C does not recognize these. What should be done?
| You can use iostream and sstream in Objective-C++.
Just make sure your source code file ends with .mm instead of .m and you will be able to use any standard C++ library you might need. Including <stream>.
|
3,794,945 | 3,795,117 | Help needed with container for a generic item in C++ | I wonder if it is possible to define a generic C++ container that stores items as follows:
template <typename T>
class Item{
typename T value;
}
I am aware that the declaration needs the definition of the item type such as:
std::vector<Item <int> > items;
Is there any pattern design or wrapper that may solve this iss... | With 9 types, your best shot is to use boost::variant, in comparison to boost::any you gain:
type safety (compile time checks)
speed (similar to a union, no heap allocation, no typeid invocation)
Just use this:
typedef boost::variant<Type0, Type1, Type2, Type3, Type4,
Type5, Type6, Type7, Type8... |
3,794,949 | 3,795,079 | How to change this code? | #include <iostream>
#include <string.h> // for strlen
#include <stdlib.h> // for atoi
#include <sstream>
void expand_combinations(const char *remaining_string, std::ostringstream& i, int remain_depth)
{
if(remain_depth==0)
{
std::cout << i.str() << std::endl;
return;
}
for(int k=0; k < ... | The following is your code with string in place of ostringstream. Normally I'd refactor the code but since your question was pretty specific I'll leave it alone.
#include <iostream>
#include <string>
#include <stdlib.h>
using namespace std;
void expand_combinations(const char *remaining_string, string const & s, int ... |
3,795,114 | 3,795,179 | Why do I need a Forward Iterator to implement my customized std::search | I am studying the book "Accelerated C++" from Koenig & Moo.
Exercise 8-2 ask me to implement on my own some templatized functions from <algorithm> and <numeric>, and to specify what kind of iterator does my implementation require.
When trying to implement std::search, I determined that I need only "input" iterators.
H... | With an input iterator, you are only allowed to pass through the range once. That is, once you've dereferenced and incremented the iterator, you can't go back and dereference it again.
This class of iterators is quite useful for many things. For example, if you are reading from a stream of some kind, once you've read... |
3,795,213 | 3,795,226 | Objective-C appropriate use of autorelease? | I'm learning Objective-C and I'm trying to write a Vector3D class.
In C++ or Java the function I want to implement would look something like this:
Vector3D
{
Vector3D crossProduct(Vector3D in)
{
Vector3D result;
result = ... // maths involving this classes variables and the input Vectors variables.
ret... | Yes, this is exactly an appropriate usage of autorelease and in fact most people using your code would fully expect that cross, normalize, and multiply return an autoreleased object.
|
3,795,326 | 3,795,483 | Using Insert Iterators when reading from file | can you use Insert Iterators while reading from a file to put the data into STL container?
for example:
FILE *stream;
fread(back_inserter(std::list), sizeof(int), 1, stream);
| C++ streams are not compatible with C stdio streams. In other words, you can't use C++ iterators with FILE* or fread. However, if you use the C++ std::fstream facilities along with istream_iterator, you can use an insertion iterator to insert into a C++ container.
Assuming you have an input file "input.txt" which con... |
3,795,383 | 3,795,603 | OpenGL Buffer Object internal workings? | I've started to use Pixel Buffer Objects and while I understand how to use them and the gist of what they're doing, I really don't know what's going on under the hood. I'm aware that the OpenGL spec allows for leeway in regards to the exact implementation, but that's still beyond me.
So far as I understand, the Buffer ... | I can't tell you in what memory the buffer object will be allocated. Actually you mostly answered that question yourself, so you can hope that a good driver will actually do it this way.
glMapBuffer can be implemented the same way as memory mapped files. Remember the difference between physical memory and virtual addre... |
3,795,567 | 3,795,887 | Visual Studio 2010 not autolinking static libraries from projects that are dependencies as it should be supposed to |
Create a new solution with a C++ console command-line project
Create a new project, a C++ static library
Make the command-line project depend on the library
Make sure "Link Library Dependencies" is turned on in Configuration => Linker => General (it is by default)
Visual Studio will still not link the library.
How ca... | This still works, but was changed in VS 2010:
"With VS2010, we stopped supporting project dependencies defining implicit references and we also introduced a new way of defining project dependencies at the project level. Since a project reference and a project dependency are close concepts, both applying to a project, ... |
3,795,625 | 3,795,663 | Pointers vs auto_ptr vs shared_ptr | I was recently introduced to the existence of auto_ptr and shared_ptr and I have a pretty simple/naive question.
I try to implement a data structure and I need to point to the children of a Node which (are more than 1 and its) number may change. Which is the best alternative and why:
class Node
{
public:
//... | You're right that auto_ptr doesn't work for arrays. When it destroys the object it owns, it uses delete object;, so if you used new objects[whatever];, you'll get undefined behavior. Perhaps a bit more subtly, auto_ptr doesn't fit the requirements of "Copyable" (as the standard defines the term) so you can't create a c... |
3,795,717 | 3,795,730 | Why does void setOutputFormat(ostream out, int decimal_places) cause an error? | If I change it to void setOutputFormat(ostream& out, int decimal_places),
with a call by reference, it works. I don't understand why though?
What is the difference between a struct and a class, besides struct members are by default public, and class members are by default private?
| You're right that there is no difference between class and struct, except the default private vs private.
The problem here is that ostream doesn't have a copy constructor, so you can't pass it by value.
|
3,795,944 | 3,926,585 | DirectX 9 "Loading textures" progress bar | It doesn't need to look like a progress bar.
All I need it to say is "Loading images..." while the texture is loading, then saying "Done" when it's done loading.
I have no idea, how to do it?
| I've done something like this in a DirectX application I was working on.
The idea behind it is to use the D3DXSPRITE interface to draw text to the screen. Begin drawing the scene with the Direct3D device, begin drawing with the sprite, call the sprite's DrawText function, and then end the sprite and the device scene.
N... |
3,795,964 | 3,795,976 | Problem implementing pure virtual class in C++ | I have the following class:
#include <string>
#include <stack>
#include <queue>
#include "map.h"
using namespace std;
#ifndef CONTAINER_H_
#define CONTAINER_H_
struct PathContainer {
int x, y;
string path;
};
class Container {
public:
virtual void AddTile(string, FloorTile *) = 0;
virtual void Clear... | typeid(NeighborTile *) != typeid(FloorTile *). The signatures differ, so they don't count as "the same" method even if NeighborTile inherits from FloorTile.
|
3,796,052 | 3,796,071 | std::vector resize() works only after clear() | I have a vector object:
std::vector<std::vector<MyClass>> _matrix;
It is 2d array with some data.
When i trying to resize the dimensions with:
_matrix.resize(_rows, std::vector<MyReal>(_colms)); //_rows and _colms are ints
this command simply does nothing to the object.
So to resize it i have to call first to:
_matri... | From the docs for vector::resize:
_Val: The value of new elements added to the vector if the new size is larger that the original size.
Only the new rows get vectors with additional columns (std::vector<MyReal>(_colms)). resize will not change the existing rows.
Update: To resize the entire vector properly, iterate o... |
3,796,090 | 3,796,244 | Compiler PDB file and the Linker PDB file | I am getting confused as to what is the difference between the compiler and linker PDB files respectively (i.e. in Visual Studio, Project Properties > C/C++ > Output Files > Program Database File Name vs Project Properties > Linker > Debugging). I have tried to find the answer online and so far I know (may be wrong) th... | I honestly don't know what exactly the .pdb file generated by the compile step is used for - I assume that it's some intermediate information the gets pulled into the final .pdb file by the linker.
However, the bottom line is that for debugging purposes all you need is the .pdb file that is produced by the linker.
Upd... |
3,796,142 | 3,796,145 | C++: Trouble Using String as Argument of a Function | Okay, I am having trouble with the following piece of code (in a header file):
#ifndef XML_H_INCLUDED
#define XML_H_INCLUDED
#include "libxml/parser.h"
#include "libxml/xmlwriter.h"
#include <string>
class XmlFile{
public:
XmlFile(string filename){
file = xmlParseFile(filename);
}
xmlDocPtr file... | file = xmlParseFile(filename.c_str());
|
3,796,181 | 3,796,196 | C++ Passing Pointer to Function (Howto) + C++ Pointer Manipulation | I am a little confused as to how passing pointers works.
Let's say I have the following function and pointer, and...
EDIT:
...I want to use a pointer to some object as an argument in the function.
i.e.:
void Fun(int Pointer){
int Fun_Ptr = ---Passed Pointer---;
//So that Fun_Ptr points to whatever ---Passed ... | There is a difference in the * usage when you are defining a variable and when you are using it.
In declaration,
int *myVariable;
Means a pointer to an integer data type. In usage however,
*myVariable = 3;
Means dereference the pointer and make the structure it is pointing at equal to three, rather then make the poi... |
3,796,260 | 3,796,265 | What does this line of code do? | void expand_combinations(const char *remaining_string, string const & s, int rema
in_depth)
{
if(remain_depth==0)
{
std::cout << s << std::endl;
return;
}
for(int k=0; k < strlen(remaining_string); ++k)
{
string str(s);
str.append(1, remaining_string[k]);
exp... | remaining_string is not a string; it's a pointer to a character. Therefore adding an integer to it simply moves the pointer.
For example, if char *blah = "hello", then blah+1 would point to "ello".
|
3,796,323 | 3,796,330 | Need some help with initializing an array of pointers to member functions | I'm very new to programming & came across a program in a book i'm reading.I get a compile error in it.
The error says "variable-sized object 'ptrFunc' may not be initialized".(it points to the end of the array)
Please advise,what is wrong in it.Thanks in advance.
#include<iostream>
using namespace std;
class cDog
{
... | void (cDog::*ptrFunc[noOfFunc])() const = {
noOfFunc is not const-qualified; you would need to declare it as a const int to use it as an array size (the size of an array has to be known at compile time).
However, when you declare an array like an initializer as you do here, you can omit the size; the compiler will det... |
3,796,328 | 3,796,902 | C++ Relating inheritance hierarchy | There is a C code, which we are trying to convert into C++ code. There were two inheritance hierarchies, which were managed by C through switch..case. That has been converted to use virtual functions in C++. Now at one point these two hierarchies have to get related. For example class A relates to A1, class B relates t... | If you dont want to create objects at run time. You can use the following method. with only one time object creation.
As you dont need to access members of the classes, single object will do your work;
class A
{
public:
virtual f()
{
printf("A");
}
static A* behaveLikeA();
static A* behaveLikeB();
};
class... |
3,796,416 | 3,796,573 | Is a class a namspace | the following code will help me illustate my question to you directly:
#include<iostream>
class foo {
public:
class bar {
public:
bar(int a) : m_a(a) {}
void say() { std::cout << m_a << std::endl;}
private:
int m_a;
};
};
int main()
{
foo::bar b(3);
b.say();
}
as you see, to decl... | The class is not a namespace, it is a scope. You already used this term yourself. Namespace is a scope. Class is a scope as well. The :: operator is a scope resolution operator. Scope, not namespace, is the fundamental term that can act as a "common denominator" in this case. Scope is the reason why you can use the :: ... |
3,796,452 | 3,796,517 | How do I display/draw a .ply object in OpenGL? | I'm trying to make OpenGL draw the figure that I'm loading with OPENFILENAME. What I've got right now is: I can display the comments, vertex, how many faces, etc., but I cannot draw the figure and I'm not sure how to do it. I can draw other predetermined figures, but not the ones I'm trying to open.
This is where I'm ... | You only specify one vertex between your begin/end.. you need at least 3 to specify a triangle. And many more if you want a whole buncha triangles. You need something more along the lines of this:
void Figure::Parameters(float x, float y, float z)
{
m_vertices.push_back(myVertex(x, y, z));
}
void Figure::Draw()
{
... |
3,796,555 | 3,796,585 | Error C2079, what order to define classes in | I'm getting a compiler error with this header file:
#ifndef GAME1_H
#define GAME1_H
#include "GLGraphics.h"
#include "DrawBatch.h"
class GameComponent;
class Game1 {
private:
GLGraphics graphics;
GameComponent components;
void updateDelegates();
void Run();
};
class GameComponent {
priva... | Think about the computer's memory for a second here.
class B;
class A {
byte aa;
B ab;
};
class B {
byte bb;
A ba;
};
A x;
Now the question the compiler needs to answer is How much space should I reserve for x?
Let's see. The first byte of x is byte aa;. Easy enough. That's 1 byte.
Next comes B ab;.... |
3,796,631 | 3,796,632 | C++ recursive data types | A bit of a noob question:
I need classes A and B such that A has a B* member and B has an A* member.
When compiling I get "error: ISO C++ forbids declaration of ‘B’ with no type". How can I get around this?
| Forward declare B (or A )
class B; //forward declaration of B
class A
{
B *b;
};
class B
{
A *a;
};
|
3,796,681 | 3,796,687 | Graph better than Google charts? |
Possible Duplicate:
Generate line graph for any benchmark?
What services do you recommend to generate graphs for benchmark results, like the following?
http://developer.studivz.net/wp-content/uploads/2009/03/splminheap_rw_mixed.png
Some of the web services I had used were dodgy at best to make these graphs.
| Google Charts is the nicest, I've seen. I mean c'mon, how easy is <img src="http://chart.apis.google.com/chart?cht=lc&chs=200x125&chd=t:40,60,60,45,47,75,70,72">
http://chart.apis.google.com/chart?cht=lc&chs=200x125&chd=t:40,60,60,45,47,75,70,72
|
3,797,107 | 3,797,129 | Using '>>' across gcc and visual c++ | We are writing an application that compiles with both gcc and Visual C++. Some team members only use Visual C++/Windows, and others only use gcc/linux. Due to differences between compilers the build sometimes breaks. I have "fixed" several scenarios that lead to build breaks using compiler options to enable/disable war... | GCC currently (since version 4.3) supports this via:
g++ --std=c++0x -o output file1.cpp file2.cpp ...
You have to explicitly specify that your source code is written in C++0x standard.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.