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,830,951 | 3,840,736 | How to create an array to hold C++ classes (not instances) to be used iteratively in a template function | I need to repeatedly make calls to a template function with different classes defined elsewhere in the code, like so:
MyTemplateFunction<ClassOne>( &AnotherTemplateFunction<ClassOne> );
MyTemplateFunction<ClassTwo>( &AnotherTemplateFunction<ClassTwo> );
MyTemplateFunction<ClassThree>( &AnotherTemplateFunction<ClassThre... | Something like this should suffice
template<typename I, typename N> struct cons { };
struct nil { };
template<typename T, typename U>
void call(cons<T, U>) {
MyTemplateFunction<T>(&AnotherTemplateFunction<T>);
call(U());
}
void call(nil) { }
typedef cons<ClassA, cons<ClassB, cons<ClassC, nil> > > conses;
int mai... |
3,831,126 | 3,831,166 | Deduce return type of operator/function for templates | Is something like this possible?
// We can even assume T and U are native C++ types
template<typename T, typename U>
magically_deduce_return_type_of(T * U) my_mul() { return T * U; }
Or would somebody have to hack up a return_type struct and specialize it for every pair of native types?
| Heard of decltype?
In C++0x you can do
template<class T, class U>
auto mul(T x, U y) -> decltype(x*y)
{
return x*y;
}
|
3,831,133 | 3,831,160 | Convert axes coordinates to pixel coordinates | I'm looking for an efficient way to convert axes coordinates to pixel coordinates for multiple screen resolutions.
For example if had a data set of values for temperature over time, something like:
int temps[] = {-8, -5, -4, 0, 1, 0, 3};
int times[] = {0, 12, 16, 30, 42, 50, 57};
What's the most efficient way to trans... | Assuming you're going from TEMP_MIN to TEMP_MAX, just do:
y[i] = (int)((float)(temps[i] - TEMP_MIN) * ((float)Y_MAX / (float)(TEMP_MAX - TEMP_MIN)));
where #define Y_MAX (600). Similarly for the x-coordinate. This isn't tested, so you may need to modify it slightly to deal with the edge-case (temps[i] == TEMP_MAX) p... |
3,831,279 | 3,831,484 | How to be sure if a processor is 32bits or 64bits ? Are dual core processors 32 or 64 bits? | Having a Macbook Pro with windows installed thanks to bootcamp, I have several questions:
Under windows, I see that processes only use 50% maximum of the CPU charge, is that because the processor is a dual core and because the process is not multi-threaded ? Should I install windows xp version 64 bits instead, to have... |
Yes 50% is maximum use for a single thread. No 64 bits won't change anything to that.
All Core 2 and Core i* processors are 64 bits. All Atoms are 32 bits. Your sizeof is correct, though it won't help if you compile as 32 bits app on a 64 bits system.
2x 32 bits doesn't equal 64 bits. A 64 bits processor has 64 bits c... |
3,831,289 | 3,831,313 | Inserting a "£" sign in an output string in C++ | I have the following code:
cout << "String that includes a £ sign";
However, the £ sign is not being recognised by the compiler, and instead an accented u is being displayed. I'm able to insert one using the following method:
cout << "String that includes a " << char(156) << " sign";
where 156 is the ASCII code of th... | £ does not have an "ASCII code" - ASCII is 7 bits (0..127). There are various extended 8 bit characters sets which include £ but there is no single standard for this and the £ symbol may have various different values in different environments. You should probably be using Unicode if you need international symbols with ... |
3,831,370 | 3,831,429 | Creating clone of an object not working with virtual base class | #include<iostream>
using namespace std;
class Something
{
public:
int j;
Something():j(20) {cout<<"Something initialized. j="<<j<<endl;}
};
class Base
{
private:
Base(const Base&) {}
public:
Base() {}
virtual Base *clone() { return new Base(*this); }
virtual void ID() { cout<<"BASE"<<endl; }... | Well, your copy constructor does nothing, so your clone method does nothing in the way of copying.
See line Derived(const Derived&) {}
EDIT: if you add code to copy by assignment all members of Derived, it will become a shallow copy. If you also copy (by making a new instance) your instance of Something, it will become... |
3,831,508 | 3,831,519 | why is RAND_MAX a macro in C++? | Why is it not a const? I think this is not a clear C++ way.
Perhaps there is a more C++ way to generate random numbers, is there?
| If you're looking for a "more C++-way", you could use boost::random.
Anyway, RAND_MAX is a macro, because it comes from "legacy C" rand() function, where using preprocessor symbols for declaring constants was a de-facto standard.
|
3,831,572 | 3,831,647 | Differences between tr1::shared_ptr and boost::shared_ptr? | Are there any difference between tr1::shared_ptr and boost::shared_ptr? If so, what?
| No, the documentation of boost shared_ptr says:
This implementation conforms to the
TR1 specification, with the only
exception that it resides in namespace
boost instead of std::tr1.
|
3,831,782 | 3,831,839 | create a simple dll file with JNI | Im trying to create a simple dll file.Im following the tutorial
http://java.sun.com/docs/books/jni/html/start.html
when i try to compile the c program i get following error :
Warning W8057 HelloWorld.c 10: Parameter 'env' is never used in function Java_He
lloWorld_print
Warning W8057 HelloWorld.c 10: Parameter 'obj' i... | That's because most JNI functions don't need to reference the env, and some don't need to reference the object. In other words, ignore it.
|
3,831,788 | 3,831,933 | Is it possible to use attributes in unmanaged code? | I have an unmanaged C++ application (unmanaged meaning: not using anything of the the fancy .Net stuff). I want to extend it with some meta information, and it looks like I could use the concept of attributes.
What I actually try to achieve is the following.
Starting from something a simple class like this:
class Book... | Visual C++ for a while supported a similar attribute notation when defining COM objects. I think support was eventually dropped because programmers use C++ for COM implementation when they want complete control, and the compiler doing things magically outside the programmer's control runs counter to that.
OTOH IDL doe... |
3,831,923 | 3,833,087 | How to test winsock apps with bound connect AND listen sockets? | I am trying to connect two of the same app with winsock, but the connecting side has to use ConnectEx() which requires a bound socket. So the problem is that when I try to loop back using ip 127.0.0.1, I get error 10048(WSAEADDRINUSE).
Is there any way around this problem?
Thanks for any help
| Although ConnectEx() requires a bound socket you don't need to select a port and explicitly bind it you can bind to a wildcard address simply leave the port as 0 and the OS will select one for you as it normally does with outbound connections.
|
3,831,928 | 3,832,017 | returning an object (or a struct) in c++ | hey, i got an question about what is going on in the next code:
typedef struct {
double re,im;
} Complex;
Complex ComplexCreate(double r=0.,doublei=0.)
{
Complex c;
c.re=r;
c.im=i;
return c; // problem with this line
// my question is : is c getting duplicated and returning or ... | C is going to be duplicated and you will get it. You can check it by yourself :
#include <iostream>
typedef struct T {
double a;
int b;
} T;
T f() {
T newT = {10.0,5};
std::cout << "Temporary address : " << &newT << std::endl;
return newT;
}
int main(int argc,char* argv[]) {
T retT = f();
std::... |
3,832,087 | 3,841,059 | #import ADOX conflict with managed dll using ADO | I have a legacy C++ application using /clr calling a managed dll (written in C#)
The app uses #import to reference ADOX. The dll also references ADOX.
Everything is fine until I add a reference to my dll to the C++ project. Then I get hundreds of errors when compiling STDAFX.CPP related to msadox.tli and msadox.tlh. So... | I got round the problem by removing the dll reference from the C++ project references and using #using "my_managed.dll" in a single cpp file (the only one that refers to the dll).
Then the compiler warned me that it was unable to import some ADOX symbols from the dll because they had already been defined (by the #impor... |
3,832,090 | 3,832,130 | Memory Handling C++ using Normal Pointer | I have a situation like below in which I have some problem in freeing the memory. Basically I have a vector that holds pointer to objects from classA. I have another classB that store the pointer of classA from the vector. It would make use of the objB. The problem is I need to operate on the vector to erase the pointe... | At least offhand, it sounds like you're looking for shared_ptr.
|
3,832,290 | 3,832,428 | Altering DLL search path for static linked DLL | I've searched for any hints how I can do this, but all I found was how to redirect a SxS DLL to the local application folder.
Here is what I want to accomplish:
The (C++) Application.exe is linked to a DLL, Plugin.DLL (dependant project). This DLL is not placed inside the application directory, but in a subfolder calle... | My first thought is, if you are statically linking a dll, it isnt a plugin. Just put the dll in the EXE folder and be done with it. That is the deployment configuration supported by windows for statically loaded DLLs.
That said, there are ways to achieve what you want. But they are mostly stupid, or complicated for no ... |
3,832,420 | 3,869,212 | About downcasting from base class to subclass pointer | A static check tool shows a violation on the below code:
class CSplitFrame : public CFrameWnd
...
class CVsApp : public CWinApp
CWnd* CVsApp::GetSheetView(LPCSTR WindowText)
{
CWnd* pWnd = reinterpret_cast<CSplitFrame*>(m_pMainWnd)->m_OutputBar.GetChildWnd(WindowText);
return pWnd;
}
Error Message: Class 'CSplitFr... | Let us go through some of the downcasting example in MFC:
CButton* from CWnd*
CWnd* wnd = GetDlgItem(IDC_BUTTON_ID);
CButton* btn = dynamic_cast<CButton*>(wnd);
CChildWnd* from CFrameWnd*
CChildWnd * pChild = ((CSplitFrame*)(AfxGetApp()->m_pMainWnd))->GetActive();
There are indeed some of the limitation of MFC desi... |
3,832,613 | 3,832,636 | Access private elements of object of same class | Is this legal? If not, will the following code allow this?
class Foo
{
friend class Foo;
}
| That's redundant. Foo already has access to all Foo members. Two Foo objects can access each other's members.
class Foo {
public:
int touchOtherParts(const Foo &foo) {return foo.privateparts;}
private:
int privateparts;
};
Foo a,b;
b.touchOtherParts(a);
The above code will work just fine. B will access a's privat... |
3,832,681 | 3,832,711 | Is there a way of applying a function to each member of a struct in c++? | You have a simple struct, say:
struct rect
{
int x;
int y;
int width;
int height;
};
And you want to multiply each element by a factor. Is there a more concise way of performing this operation, other than multiplying each member by the value?
| Not really. Programatically obtaining a list of the elements of a struct requires reflection, which C++ does not support.
Your two options are to just give the struct a method that does this the long-winded way and then use that method in all other places, or to manually mimic reflection, for example by giving the stru... |
3,832,905 | 3,835,229 | Howto organize Vim buffers, windows and tabs when working with many files | I used VIM whole my life but recently I am a bit tired of it because I am lost in buffers, windows, and tabs when working simultaneously with 20 files or so in a big project (with 500k LOC, and hundreds files).
Whenever i do :make, :grep, etc, new buffers are jumping out in the current window.
The same happens for the ... |
Use :hide to get rid of all windows unless you really need them open.
I'm not sure why tags are creating a new window for you, CTRL+] should re-use the current window.
nnoremap + 4<C-W>+ and nnoremap - 4<C-W>- make it much easier to resize windows, along with the standard <C-W>_ and <C-W>|.
Get a 22" monitor (minimum)... |
3,832,964 | 3,833,251 | calling operator<< in gdb | How do you call operator<<(std::ostream &os, const ClassX &x) from inside gdb ?
In other words, how do you print an object in gdb ?
call std::cout<<x or call operator<<(std::cout, x) don't seems to work for me!
Any ideas?
| The only way I found was this:
call 'operator<<(std::ostream&, myclass&)'(mycout, c)
Since std::cout wasn't visible to gdb for some reason, I had to resort to creating my own like this:
std::ostream mycout(std::cout.rdbuf());
You haven't stated any reasons for wanting to do this but won't print yourvariable be easi... |
3,833,077 | 3,833,130 | Why is a variable length array not declared not as a pointer sometimes? | I see this in code sometimes:
struct S
{
int count; // length of array in data
int data[1];
};
Where the storage for S is allocated bigger than sizeof(S) so that data can have more space for its array. It is then used like:
S *s;
// allocation
s->data[3] = 1337;
My question is, why is data not a pointer? Wh... | If you declare data as a pointer, you'll have to allocate a separate memory block for the data array, i.e. you'll have to make two allocations instead of one. While there won't be much difference in the actual functionality, it still might have some negative performance impact. It might increase memory fragmentation. I... |
3,833,261 | 3,833,333 | Find out if a received pointer is a string, ushort or array | I am interposing the memcpy() function in C because the target application uses it to concatenate strings and I want to find out which strings are being created. The code is:
void * my_memcpy ( void * destination, const void * source, size_t num )
{
void *ret = memcpy(destination, source, num);
// printf ("[MEM... | As void* represents a raw block of memory, there is no way to determine what actual data lies there.
However, you can make a "string-like" memory dump on every operation, just give the resulting output some sort of the "upper output limit".
This could be implemented the following way:
const size_t kUpperLimit = 32;
vo... |
3,833,291 | 3,833,322 | How to avoid problems with size_t and int types in 64bit C++ builds? | Today I made a 64bit build of my project for the first time. Basically it compiled, linked and ran ok, except for warnings complaining about incompatibility between the new, 64bit size_t type and the simple int type. This mostly occurs in situations like this in my code:
void func(std::vector<Something> &vec)
{
int... | Do an explicit cast to int, e.g.
void outsideLibraryFunc(int n);
void func(std::vector<Something> &vec)
{
outsideLibraryFunc(static_cast<int>(vec.size()));
}
It doesn't eliminate any of the potential problems with converting size_t to int, but it does tell the compiler that you're doing the conversion on purpose,... |
3,833,410 | 3,833,450 | How to convert a user defined type to primitive type? | Let's say we have a class called Complex which represents a complex number.
I want to convert this object to a double object.
The other way around i can do by implementing a copy ctor in Complex:
Complex(const double &d);
However, i can't implement i copy ctor in double which will receive a Complex.
How do i do this? I... | Implement a conversion operator on your Complex class:
class Complex
{
// ...
operator double() const
{
double ret = // magic happens here
return ret;
}
};
If for whatever reason you don't want to muck about with this, you can provide a global conversion function:
double convert_to_double(const Complex... |
3,833,416 | 3,833,471 | Segmentation Fault when deleting complete linked list | I'm trying to delete whole linked list but getting segmentation fault and not able to detect what is the real problem. When I tried debugging using gdb, it is able to remove the first node but throw segmentation fault when deleting second node. Please suggest me what can be the possible reason.
#include <iostream>
usin... | Because in the listNode d'tor it's deleting the next node. So, when it goes to delete the second node in the list, it's already deleted.
~listNode ()
{
delete next;
}
Change it to...
~listNode ()
{
}
|
3,833,736 | 3,833,975 | Why would I need conversion? | In this code:
template<class T>
struct Side
{
};
template<class T>
struct LeftSide : public Side<T>
{
};
template<class T>
struct RightSide : public Side<T>
{
};
Side<int>* f(int left, int right)
{
return left < right ? new LeftSide<int> : new RightSide<int>;//<---Here I'm returning either left or right side
}
i... | The problem is not with the conversion from either LeftSide or RightSide to Side<T>. As you originally thought, this conversion would be fine.
Rather, the problem is with this expression:
left < right ? new LeftSide<int> : new RightSide<int>
Let's break this down a little. The ternary operator (properly referred to ... |
3,834,336 | 3,834,473 | Why Does C++ Support Hex Assignment, But Lack Binary Assignment? How best to store flags? | I have a set of bit flags that are used in a program I am porting from C to C++.
To begin...
The flags in my program were previously defined as:
/* Define feature flags for this DCD file */
#define DCD_IS_CHARMM 0x01
#define DCD_HAS_4DIMS 0x02
#define DCD_HAS_EXTRA_BLOCK 0x04
...Now I've gather that #defin... | Prior to C++14, binary literals had been discussed off and on over the years, but as far as I know, nobody had ever written up a serious proposal to get it into the standard, so it never really got past the stage of talking about it.
For C++ 14, somebody finally wrote up a proposal, and the committee accepted it, so if... |
3,834,366 | 3,834,629 | General approach to missing DLL's | I guess everyone has run into missing dll's issues from time to time. What I am trying to get is the 'recommended' method to find and install the dll's. Finding out which dll's are missing is easy enough using depends.exe.
| Don't use depends.exe anymore, it hasn't kept up with developments in the Windows core and deployment strategies like the side-by-side cache. Trying to fix the warnings it gives will actually mess up your machine pretty badly. Only use it for hints if a program actually fails to start.
|
3,834,489 | 3,839,322 | Improve use of alternative parser | I extended the Mini XML example from the spirit manual.
The grammar describes a xml tag that can be closed with '/>' and has no child nodes or which is closed like in the example with a closing tag '' and can optionally have children.
#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/phoenix_core.hp... | You should be able to write:
xml %= startTag[_a = &_1]
>> attributes
>> ( "/>" >> eps
| ">" >> *node > endTag(*_a)
)
;
That leaves the vector attribute unchanged (and empty).
|
3,834,508 | 3,834,886 | expanded parameter list for variadic template | I'm working on an Event based architecture for a research project. The system currently uses Qt signalling, but we are trying to move away from Qt, so I need something that will work almost as well as the Qt event loop and signals across threads.
Probably against my better judgement, I've chosen to use variadic templat... | Hm. I think I got something nasty. The code is not very pretty or good, but you probably get the idea. You should be able to use templates to recursively store objects of any type, and also recurse through them when calling the function.
#include <iostream>
template<typename first_arg, typename... args>
class Event
{
... |
3,834,608 | 3,834,745 | String literal to basic_string<unsigned char> | When it comes to internationalization & Unicode, I'm an idiot American programmer. Here's the deal.
#include <string>
using namespace std;
typedef basic_string<unsigned char> ustring;
int main()
{
static const ustring my_str = "Hello, UTF-8!"; // <== error here
return 0;
}
This emits a not-unexpected compla... | Narrow string literals are defined to be const char and there aren't unsigned string literals[1], so you'll have to cast:
ustring s = reinterpret_cast<const unsigned char*>("Hello, UTF-8");
Of course you can put that long thing into an inline function:
inline const unsigned char *uc_str(const char *s){
return reinte... |
3,834,609 | 3,834,655 | What type of sort is this? | The C++ book I'm reading described a sort algo, saying it is the Bubblesort yet I cannot find a single variation of bubblesort just like it. I understand the differences are minor, but is it exactly as efficient as a regular bubblesort ?
BubbleSort(int A[], int length)
for (j=0; j < length-1; j++)
for (i=j+1; i < len... | This is selection sort. On each pass you find the i'th smallest element and put it in position i. After the first pass, it is not necessary to look at A[0] anymore, and so on. Selection sort is worst-case O(n2) and best-case O(n), just like bubble sort, but it has a smaller constant factor than bubble sort. Inserti... |
3,834,620 | 3,834,678 | How does MSVC optimize static variable usage? | I'm interested in how the Microsoft Visual C++ compiler treat/optimize static variables.
My code:
#include <cstdlib>
void no_static_initialization()
{
static int value = 3;
}
void static_initialization(int new_value)
{
static int value = new_value;
}
int main()
{
no_static_initialization();
static_in... | Yes, the compiler has to add a hidden flag to test whether it is the first call to the function and initialize or not depending on that. In both snippets it is testing the flag, if it is raised it will jump to the end of the function or else it will initialize the static variable. Note that since the compiler has inlin... |
3,834,665 | 3,834,763 | Performance of C++ applications in VS2010 and VS2008 | I'm working on a real-time application (lets call it App1) which is communicating with another application (App2). I used VS2008 and both applications are in C++. Recently I converted the App1 project to VS2010 and right after that it started crashing (I use VS2010 Premium Ver. 10.0.30319.1). Crash dump shows that righ... | Well of course it has "some" effect on the performance. The compiler is newer, and in many regard better.
The problem you are suffering is unlikely to be as a result of the compiler going wrong however. Its possible you have made an assumption that no longer holds true under the C++0x features introduced in 2010 bu... |
3,834,909 | 3,834,993 | operator[] overloading | There is a class like this:
class X {
public:
...
private:
int changeable[3];
int unchangeable[3];
};
And this is its desirable usage:
X x;
x[0] = 1; // here changeable[0] should be used
a = x[0]; // here unchangeable[0] should be used
Is there any way of defining operator[] in c... | I'd probably solve this with a proxy object:
class Xproxy
{
int& changeable;
int& unchangeable;
Xproxy(int& c, int& u) : changeable(c), unchangeable(u)
{}
Xproxy& operator=(int i)
{
changeable=i
return *this
}
operator int()
{
return unchangeable;
}
};
class X
{
int changeable[3];... |
3,834,974 | 3,835,036 | Languages and Frameworks for creating High Load Web Service? | Maybe, i'm duplicating some existing theme (close this one if it's true) but i'm planning to work with high load web services and curios about best practices.
I have projects on Java and Grails. I'm doubt if Grails is right solution for high load service but Java (without any Hibernate or similar tools) can be used ver... | Java can handle heavy loads. See http://www.jboss.org/netty/performance/20090607-asalihefendic.html which discuss how to have hundred thousand simultaneous comet connections open to a single server. Not bad.
Note, that this kind of scalability does not come out of nowhere. Your application must be well written in th... |
3,835,009 | 3,835,029 | boost::thread without all of boost? | is there a way to use boost's threading capabilities without the entire boost library? What are the bare minimum h and cpp files needed for this?
Thanks
| http://www.boost.org/doc/libs/1_43_0/doc/html/thread.html
According to the above you need at least
#include <boost/thread.hpp>
|
3,835,021 | 3,835,044 | Can I use sizeof() or a #define for precision in sprintf of a string? | Lookign at:
http://www.cplusplus.com/reference/clibrary/cstdio/sprintf/
for string (%.Ns) precision.
When I use sizeof or a #define length in the precsion it reads it as actual text.
Why is this? What are the rules of this? Does it have to be an integer value only?
i.e. -
buffer[50];
sprintf (buffer, "%.sizeof(bu... | Anything inside quotation marks is part of the string, and the compiler won't even think of touching it. Instead, you can use a '*' to let sprintf know your precision is an extra argument it can read. Also, you need the '.' before your precision, or otherwise it will be a pad-width instead.
sprintf(buffer, "%.*s", (i... |
3,835,043 | 3,837,786 | High-performance message passing from C to Erlang | I have a C server (a data feed handler) that has the potential to send millions of tiny messages per second across a few thousand long-lived Erlang processes. In a single day, some of these processes will receive a few thousand messages, while others will receive tens of millions. My interests are threefold:
to minim... | I would suggest you invert your system, embed your C code to Erlang VM as linked-in driver. IMHO it is way how you can achieve fastest solution in manageable way.
|
3,835,147 | 3,835,224 | Question regarding multithreading | I want to make a simple GUI API. Essentially the way it will work is the gui widget is basically a thread in an infinite loop. The thread has a pointer to the widget's class. The way I want it to work is basically similar to WinAPI. I would do something like this:
textbox->SendMessage("Click",args);
which is then add... | Is there a reason you're going down this path for GUI development?
There's a very good reason nearly all GUI libraries rely on a single thread for managing 'widgets'. Multithreading is hard; when writing controls with a large exposed interface you're going to need to be exceedingly careful in how you design it. As th... |
3,835,261 | 3,835,267 | How many bytes does a #define string (string literal) take? | #define STR "test1"
Why does this take 6 bytes?
sizeof(STR) = 6
| There is a trailing '\0' at the end.
|
3,835,289 | 3,835,327 | Automated inlining for VC++? | Is there a way to tell the compiler to inline wherever it sees it to be useful? I thought it did this by default, but adding a few inline to my game loop functions improved performance by a good 30%.
Thanks
| The /Ob option
Note that the compiler can't auto-inline functions across compilation units unless you use Whole Program Optimization (/GL).
|
3,835,422 | 3,835,634 | Delete the current object and create an array of new ones | There is a member function which I would like to delete the current object and create an array of new ones in its place. How is it possible? The following code is an attempt of mine which has a lot of mistakes.
void LernaeanHydra::split(int parts)
{
LernaeanHydra *new_heads = new LernaeanHydra[parts];
for (int ... | When you're splitting a node in a tree, you'd normally start with one node containing a vector of pointers to its child nodes. You'd then create one new node containing a vector of pointers to its child nodes that you'd initialized with half the child pointers from the current node. Afterwards, you erase those pointers... |
3,835,434 | 3,835,443 | Can I use two precision '*' in a string format of two strings? |
.* The precision is not specified in
the format string, but as an
additional integer value argument
preceding the argument that has to be
formatted.
#define SUFF ".txt"
#define MAX_STR 50
fileName[MAX_STR];
name ="myFile"
sprintf( fileName, "%s%s", name, SUFF ); //fileName = "myFile.txt"
Now I want t... | You have the order of the variable arguments wrong. The width argument goes with the object argument (it must immediately precede the object).
sprintf(fileName,
"%.*s%.*s",
MAX_STR - (int) sizeof(SUFF), // precision and...
name, // ...object
(int) sizeof(SUFF),... |
3,835,439 | 3,835,562 | Polymorphic STL compare function (class cmp class, class cmp int) for sorting | I'm implementing a game. I have a state tree and a set<> based priority queue that sorts the states on their costs. For this I have the < operator implemented as:
struct DereferenceCompareState :
public std::binary_function<State*, State*, bool>
{
bool operator()(const State* lhs, const State* rhs) const
{
ve... | You can easily add more flexible comparison ability to struct DereferenceCompareState by overloading operator() more, but it won't help with what you're trying. The real problem you've come across is that std::set<T,Cmp>::upper_bound() only takes a key/value type (T) as argument. So no matter what you do to your comp... |
3,835,460 | 3,835,945 | how do i solve a data conflict between string and inFile.open | #include<iostream>
#include<fstream>
#include<cstdlib>
#include<string>
using namespace std;
**int main()
{
double write();
double read();
string choice;
while(1)
{
cout<<"Enter read to read a file and write to write a file.\n";
cin>>choice;
if (choice == "read")
cout<< ... | You just have to reconcile your use of "cin>>" versus "getline" when you want to read in a string. Their behavior is slightly different.
Remember that when using cin to read from the console, every keystroke that the user touches goes into the cin buffer including the \n for the return key.
So when your user types in ... |
3,835,509 | 3,835,597 | Opening a cash drawer using C/C++ or Java | I need to open a cash drawer using C/C++ or Java. It is a POS-X cash box with a USB connection. I've never done anything like this before. I noticed the cash box was linked to the "COM3" port. I know Java does not have a USB API so I turned to C/C++.
| Forum post about it here.
In a nutshell, install the driver, change the COM3 baud rate to 9600, and send a "1" to the COM port.
Check out javax.comm for a method of communicating with a com port on java.
|
3,835,698 | 3,835,716 | Virtual method & this pointer | I'm just beginning to learn C++ and I'm trying to make Thread class that that has the basic functionality of the Java Thread class. What I'm trying to do is make a class which you subclass, write a Run method (which is pure virtual in the base class) create an object of the subclass call the start method on it and you ... | The problem is that your MyThread object in main is destroyed as soon as the main function returns, which likely happens before the new thread actually gets around to calling its Start method.
As part of the destruction process, the vtable will be reset to the vtable of the base class before calling the base class dest... |
3,835,712 | 3,835,751 | C++, how to load images and count pixels of certain colours | here's my problem:
I'm looking for a way to import an image into C++ then traverse its pixels, incrementing a counter every time a pixel of a certain colour is found.
I've done some research, but I haven't found anything particularly useful. DevIL looks like a good option, but I'm not sure where to start.
Here's a bit... | Definiately take a look at OpenCV because when you begin to need more room to move then OpenCV will let you do many more computer vision tasks. And use boost::filesystem to do the 'for each image in dir' code.
Note that the cv::compare function basically does half the work for you already...I'll let you read that and e... |
3,835,738 | 3,835,761 | Using function pointers? | I'm not yet very familiar with these but maybe someone can shine light on this example.
Imagine I have class CFoo and it will have a function to add a handler and a function which is a function pointer.
So something like this:
class CFoo {
int *pointedFunc(int a, int b) = 0;
void setFunc(int *func(int a, int b))
{
... | Right now you have a member function returning int *, not a pointer to a function returning int. A set of parenthesis would fix that.
int (*pointedFunc)(int a, int b);
void setFunc(int (*pfunc)(int a, int b))
{
pointedFunc = pfunc;
}
Also, member variables get initialized in the constructor ctor-initializer-list... |
3,835,741 | 3,835,757 | Are references and pointers equal with regards to polymorphism? | I always think of having to use pointers for polymorphism. Using the canonical example:
DrawEngine::render(Shape *shape)
{
shape->draw();
shape->visible(true);
}
And passing in pointer to various Shape derived classes. Does it work the same with references?
DrawEngine::render(Shape &shape)
{
shape.draw();... | With regard to polymorphism, references work just like pointers.
|
3,835,850 | 3,839,585 | RapidXML XML parse error | I'm parsing an XML file which is quite simple:
<?xml version="1.0" encoding="utf-8"?>
<catalog>
<book id="bk101">
<author>Gambardella, Matthew</author>
<title>XML Developer's Guide</title>
<genre>Computer</genre><price>44.95</price><publish_date>2000-10-01</publish_date>
<description>An in-de... | Looks like my problem was just changing the parse declaration to:
document.parse<parse_full>();
Thanks to Karl for pointing me to http://www.ffuts.org/blog/quick-notes-on-how-to-use-rapidxml/, that's an excellent resource.
|
3,836,109 | 3,837,263 | How do I programmatically (C++) check the code signing date of an EXE in Windows? | Is this possible? How do I go about doing it? Does it require admin rights? (I would not think so)
A pointer to a help page or link is fine - no need to provide code. Given my difficulty with he code signing cert and setting it up in our build environment I am not sure I am googling with the right terms.
EDIT
Aft... | Use either WinVerifyTrust or SetupScanFileQueue(SPQ_SCAN_USE_CALLBACK_SIGNERINFO)
|
3,836,181 | 3,836,221 | Pure virtual and inline definition | Consider:
struct device{
virtual void switchon() = 0 {}
};
int main()
{
}
I wrote code similar to following and it gave an error:
pure-specifier on function-definition
compilation terminated due to
-Wfatal-errors.
When I asked him, he showed me the following quote from the standard:
A virtual function dec... | A pure virtual function may have a definition (out of class definition). That is completely optional. But what you are trying to do is plain wrong because
C++03 [Section 10.4/2] says:
[Note: a function declaration cannot provide both a pure-specifier and a definition —end note] [Example:
struct C {
virt... |
3,836,260 | 3,836,267 | Why C++ delete operator doesn't set pointer to NULL? |
Possible Duplicate:
Why doesn't delete set the pointer to NULL?
Is there any purpose for a pointer to deallocated memory?
| No, there's no real use to leaving it set to the original value, other than showing how inept people are at writing code :-)
It follows the traditions of C in that you're expected to know what you're doing. The cost of having the compiler set freed pointers to NULL was deemed too high in the C days and this has carried... |
3,836,290 | 3,836,294 | Why is this comparison always true? | I have the following code in my file:
unsigned char * pData = new unsigned char...
...
if(pData[0] >= 160 && pData[0] <= 255)
When I compile it, I get a warning from the compiler (gcc):
Warning: comparison is always true due to limited range of data type
How can this be? Isn't the range of an unsigned char 0-255? ... | If the range of unsigned char is from 0 to 255 and pData[0] is a char then pData[0] <= 255 will always be true.
|
3,836,353 | 3,836,361 | Vector insert crashes program | Can anyone tell me
why this crashes my program? It's suppose to make it so order has all the elements in the t vector situated by (y + height).
Edit: crashes on the lines with "insert" in them.
void createDrawOrder(vector<Thing*> t, vector<int> *order) {
int min = t[0]->y + t[0]->height;
int max = t[0]-... | Your iterator it is not guaranteed to be valid after order->push_back(k); which can reallocate the elements in your vector. Since I don't see you actually incrementing it anywhere, I'd recommend the uglier solution of replacing it with order->begin() in this function.
|
3,836,536 | 3,836,572 | Reading/Writing from STL Map in multithreaded environment | Problem: I need to write a function which returns a value for a input key from a map. If function can't found the value in map it will fetch the value from database, write into map for future use and return the same. There can be multiple threads calling this function.
I am thinking on this line:
string GetData (const ... | This function is not thread-safe because it results in undefined behavior. When you attempt to obtain the write lock, you already hold a read lock. From the documentation for pthread_rwlock_wrlock:
Results are undefined if the calling thread holds the read-write lock (whether a read or write lock) at the time the ca... |
3,836,573 | 3,836,632 | Standard C functions: Check for -1 or 0? | Many standard C and POSIX functions return -1 for error, and 0 on success, for example truncate, fflush, msync, etc.
int ret = truncate("/some/file", 42);
Is it better practice to check for success with ret != -1 or ret == 0, and why?
My Thoughts
It's my experience most people check for the error case (ret != -1), as ... | In my opinion, it really depends on what you need to do and the range of return values.
Take a call with one success value and many failure values. It's generally easier to == or != against the successful return value than check against any failure values. In this case, you would test against != success if you need to,... |
3,836,723 | 3,836,834 | Skiplast random function need explained | I read about skipList implementation in C++ and I don't understand this random function :
float frand() {
return (float) rand() / RAND_MAX;
}
int random_level() {
static bool first = true;
if (first) {
srand( (unsigned)time(NULL) );
first = false;
}
int lvl = (int)(log(frand())/lo... | So, the way skiplists work is it makes the new node link to other nodes at levels, randomly choosing to add a level or not. Normally this means flipping a coin once for each level the new node is intended to link to. if it comes up heads, you go up a level and flip again, if tails, you're done.
What this does is it s... |
3,836,880 | 4,281,851 | Creating a wxActiveXContainer | My objective is to display an active x object in wxwidgets.
I have declared two member pointers:
TeeChart::ITChartPtr mpChart;
wxActiveXContainer* mpAx;
I then create an instance of the teechart control:
mpChart.CreateInstance("TeeChart.TChart");
I then wish to create an instance of the wxActiveXContainer defined as:... | mpAx = new wxActiveXContainer(this, __uuidof(ITChart), mpChart.GetInterfacePtr());
|
3,836,923 | 3,837,158 | C++ Uninitialized memory? | I am sometimes (randomly) getting incorrect initialization of values, which makes me think I'm using memory uninitialized somewhere. My main data structure is:
template <class state>
class learnedStateData {
public:
learnedStateData() :gCost(DBL_MAX), hCost(0), isDead(false) {}
state theState;
double gCost;... | The implementation is perfectly sound... your issue must be elsewhere. You could use a tool like valgrind to check for invalid memory accesses, uninitialised reads etc.. You could add some assertions to try to narrow down the point where the state is corrupted. If you provide a hash algorithm, make sure it returns t... |
3,836,998 | 3,837,090 | GNU tool to analyze and reduce compile time for my application |
I am using SUSE10 (64 bit)/AIX (5.1) and HP I64 (11.3) to compile my application. Just to give some background, my application has around 200KLOC (2Lacs) lines of code (without templates). It is purely C++ code. From measurements, I see that compile time ranges from 45 minutes(SUSE) to around 75 minutes(AIX).
Questi... | Excessive (or seemingly excessive) compilation times are often caused by an overly complicated include file hierarchy.
While not exactly a tool for this purpose, doxygen could be quite helpful: among other charts it can display the include file hierarchy for every source file in the project. I have found many interesti... |
3,837,266 | 3,838,294 | Finding the points of a triangle after rotation | I'm working on a (rather) simple 2D project in OpenGL. It's some sort of asteroids clone.
The ship is basically an isosceles triangle of height H, with the base have a length of H/2.
The way I've been doing it so far is simply storing the center point (CP) of the triangle and then calculating the final vertex positions... | Thanks for the help guys but I think those explanations were a bit too technical for me. Nonetheless you made it clear to me that there's no special case for a triangle (which, in hindsight, I should've known) so I tried my hand at searching and after trying a few methods, found one which worked for me.
The post from e... |
3,837,387 | 3,837,572 | Find function signature in Linux | Given a .so file and function name, is there any simple way to find the function's signature through bash?
Return example:
@_ZN9CCSPlayer10SwitchTeamEi
Thank you.
| My compiler mangles things a little different to yours (OSX g++) but changing your leading @ to an underscore and passing the result to c++filt gives me the result that I think you want:
bash> echo __ZN9CCSPlayer10SwitchTeamEi | c++filt
CCSPlayer::SwitchTeam(int)
doing the reverse is trickier as CCSPlayer could be a n... |
3,837,494 | 3,837,735 | Is there a way to find sum of digits of 100!? | I know there is a way of finding the sum of digits of 100!(or any other big number's factorial) using Python. But I find it really tough when it comes to C++ as the the size of even LONG LONG is not enough.
I just want to know if there is some other way.
I get it that it is not possible as our processor is generally 3... | long long is not a part of C++. g++ provides it as an extension.
Arbitrary Precision Arithmetic is something that you are looking for. Check out the pseudocode given in the wiki page.
Furthermore long long cannot store such large values. So you can either create your BigInteger Class or you can use some 3rd party libr... |
3,837,637 | 3,837,694 | Multiple definitions of my template class | In my library, I have several initialize() and cleanup() functions, for different modules it depends on.
To make this part more safe to use, I decided to follow the RAII rule and built up an Initializer template class, that takes two functions as parameters:
// initializer.hpp (include guards omitted)
template <void i... | namespace xml
{
void initialize();
void cleanup();
typename ::Initializer<&initialize, &cleanup> Initializer;
}
typename is illegal here, it is only allowed in template definitions. You meant typedef!
namespace xml
{
void initialize();
void cleanup();
typedef ::Initializer<&initialize, &cle... |
3,838,124 | 3,839,011 | Placing Tab Control at runtime issue in MFC | I am loading background image at runtime in my MFC Application.
Like this :
m_objMainScrnDC.CreateCompatibleDC(NULL);
m_objMainScrnBgBitmap.LoadBitmap(IDB_MAIN_SCRN_BG);
And i have tabcontrol on my page at design time , now i want to place a background image for tab control at runtime but i am not able to ge... | My MFC is pretty rusty, but I think I remember that it involved creating a brush with your image and having MFC use it when the window gets redrawn (was it OnPaint()? OnRedraw()?).
I googled a bit and found this: http://www.codeproject.com/KB/MFC/UltimateToolbox_Skins.aspx Not exactly what you want, but the source is ... |
3,838,226 | 3,838,582 | Private data types and member functions | What does it actually mean when you declare a variable or a member function as private in a C++ class? Besides the obvious fact that, these are accessible only by the member functions, How are they mapped differently on memory, than their public counterparts?
| Imagine that they were only acessible from member functions, then code like this would break:
class Foo {
int x; // this is private
public:
int& X() { return x; } // this is public, but returns a reference to a private variable
};
Foo foo;
foo.X() = 42; // look, I can set the value of a private member without bei... |
3,838,603 | 3,963,733 | High performance logging library for embedded applications | I am looking for a high performance logging library that I will use on an embedded device.
I also want to say that I previously used PaulBunyan logging library which provided an efficient method for transferring information.
[By efficient I meant it had a solution for transferring only the __LINE__ and __FILE__ when se... | The decision is to implement this since no open alternatives are available.
|
3,838,855 | 3,839,023 | Is storing an invalid pointer automatically undefined behavior? | Obviously, dereferencing an invalid pointer causes undefined behavior. But what about simply storing an invalid memory address in a pointer variable?
Consider the following code:
const char* str = "abcdef";
const char* begin = str;
if (begin - 1 < str) { /* ... do something ... */ }
The expression begin - 1 evaluates... | I have the C Draft Standard here, and it makes it undefined by omission. It defines the case of ptr + I at 6.5.6/8 for
If the pointer operand points to an element of an array object, and the array is large enough, the result points to an element offset from the original element such that the difference of the subscrip... |
3,838,937 | 5,131,293 | Best free Cross-Platform Library for higher level Matrix, Vector and esp. SparseMatrix operations? | Our Platforms:
Windows, Linux, Mac OSX.
Free:
LGPL compatible
Support high-level operations:
Eigensystems, SVD, QR, LU, inverse, pseudo inverse (aka Moore-Penrose inverse),...
Support many matrix types and also good performing small matrices e.g. 3x3:
Sparse, Symmetric,... (and also operations on them!, e.g. pse... | eigen is the best one! It's much better than boost::ublas, you can write C = A*B instead of C = prod(A,B) as in ublas and I have tested the speed it's much faster than ublas.
|
3,838,954 | 3,839,818 | IVideoWindow update problem | I want to render the video from my webcam into QWidget. I've set QWidget, as a parent to IVideoWindow. Here is the code:
m_iVideoWindow->put_Owner((OAHWND)widget_->winId());
m_iVideoWindow->put_WindowStyle(WS_CHILD | WS_CLIPCHILDREN);
m_iVideoWindow->put_Left(0);
m_iVideoWindow->put_Top(0);
widget_->setChild(m_iVideoWi... | I think when Qt draws its widgets, it doesn't redraw them unless it knows they need to be updated. I'm also unsure as to whether it passes on whatever redraw stuff windows requires, to the window you've assigned as a child of the widget.
When I embed my own windows in a Qt widget, I use http://qt.nokia.com/products/app... |
3,838,961 | 3,839,660 | NSInvocation not passing pointer to c++ array | I think I'm making just a fundamental mistake, but I cannot for the life of me see it.
I'm calling a method on an Objective-C object from within a C++ class (which is locked). I'm using NSInvocation to prevent me from having to write hundreds methods just to access the data in this other object.
These are the steps I'... | An array is not a pointer. Try adding the following line
NSLog(@"%p, %p", s2, &s2);
just above.
id args2s[] = {(id)&_start.x(),(id)&_start.y(),(id)&s2};
s2 and &s2 are both the address of the first float in your array, so when you do:
[invocation setArgument:args[n] atIndex:2+n];
for n = 2, you are not copying in ... |
3,839,177 | 3,840,115 | Sharing data array among threads-C++ | I know that there are similar questions which are already answered, but I am asking this question since they don’t exactly give what I would like to know.
This is about synchronization between threads. The idea of my project is that we obtain data from a data acquisition card and plot and analyze data during data acqu... | If both consumers need to see all data items, you are probably better off with a buffer per consumer. The producer can then post the same data into each buffer. If you are concerned about the memory requirements of doubling the data this way, and the data is not modified by the consumers, then you could use a reference... |
3,839,199 | 3,839,265 | The memory cound not be "read". - random crash | I have a problem with a random crash caused by CSceneNode* pRoot = nodes[0]; // The real problem is = nodes[0];
Crash message is: The instruction at "0x0059d383" referenced memory at "0x00000000". The memory cound not be "read".
I do not see the problem, could please help me out ?
In Save.cpp
void CNESave::SaveLocati... | If the result of node->GetName() does not contain the string _Ldynamic, this will crash.
Because in this case GetNodesByPartOfName(..) will return false and GetNodes(..) will not execute nodes.push_back(this) and you will be left with an empty vector and later will try to access the first element of this empty vector a... |
3,839,407 | 3,840,030 | What's the correct way to get a gradient in a toolbar in win32 API (no MFC)? | For example, Notepad++ has a toolbar that looks like this:
7-Zip has a toolbar that looks like this:
(stack overflow won't let me post more links because I'm new)
Whereas mine is boring and flat, like this:
(stack overflow won't let me post more links because I'm new)
How do I do make my toolbar 3d? Is there a setting... | Explorer, 7Zip and Notepad++ get that look by using a Rebar as the parent of a transparent style toolbar.
|
3,839,553 | 3,839,658 | Array as const pointer | Consider the following code:
void Increment(int *arr) {
arr++;
}
int main() {
int arr[] = {1,2,3,4,5};
// arr++ // illegal because its a const pointer
Increment(arr); // legal
}
My question is if arr is a const pointer, how come I can send it to a function that doesn't receive a const pointer?
The... | Don't get fooled by the pointer. The same holds for plain ints:
const int a = 42;
int b = a; // How can I assign a const int to a non-const int?
int c = 4; // Come to think of it, the literal 4 is a constant too
void foo (int x) { std::cout << x; }
foo(a); // How come I can call foo with a const int?
In summary, const... |
3,840,278 | 3,840,454 | Vector push_back Access Violation | This is probably a silly error, but it's driving me nuts trying to fix it.
I have a struct:
struct MarkerData
{
int pattId;
unsigned short boneId;
Ogre::Matrix4 transToBone;
Ogre::Vector3 translation;
Ogre::Quaternion orientation;
MarkerData(int p_id, unsigned short b_id, Ogre::Matrix4 trans)
{
pattId = p_i... | Chances are high that the TrackingSystem object on which you're calling addMarker is dead (and that the this pointer is invalid. Either it went out of scope, delete was prematurely called, or it was never properly created (the pointer is still null).
This is even more likely since the push_back to a local vector works ... |
3,840,374 | 3,840,540 | How to make a C++ EXE larger (artificially) | I want to make a dummy Win32 EXE file that is much larger than it should be. So by default a boiler plate Win32 EXE file is 80 KB. I want a 5 MB one for testing some other utilities.
The first idea is to add a resource, but as it turns out embedded resources are not the same as 5 MB of code when it comes to memory allo... | Use a big array of constant data, like explicit strings:
char *dummy_data[] = {
"blajkhsdlmf..(long script-generated random string)..",
"kjsdfgkhsdfgsdgklj..(etc...)...jldsjglkhsdghlsdhgjkh",
};
Unlike variable data, constant data often falls in the same memory section as the actual code, although this may be ... |
3,840,531 | 3,840,599 | What is the purpose of ostringstream's string constructor? | On MSVC 2005, I have the following code.
std::ostringstream stream("initial string ");
stream << 5;
std::cout << stream.str();
What I expect is:
initial string 5
What I get is:
5nitial string
Initializing the stream with a string, I would expect the stream to move its position to the end of the initial string. Obvio... | Using an ostringstream and providing an initial value is just like opening an existing file for writing. You have some data there, and unless you specify otherwise, your initial position will be at the beginning of the data. You can seek in the data, or you specify ios::ate to initially position the write pointer to th... |
3,840,568 | 3,840,630 | std::map::erase infinite loop | I have a map of a vector of char's and a vector of strings. Every so often, if I've seen the vector of characters before, I'd like to add a string to my vector of strings. Below is my code to do that.
map<vector<char>, vector<string>>::iterator myIter = mMyMap.find(vChars);
if(myIter != mMyMap.end()) {
vector<str... | I don't see an error in the posted code fragment (other than a missing )). But may I suggest simplifying lines 2-8 to:
if(myIter != mMyMap.end()) {
myIter->second.push_back(some_other_string);
}
|
3,841,238 | 3,841,277 | Condensing Declaration and Implementation into an HPP file | I've read a few of the articles about the need / applicability / practicality of keeping headers around in C++ but I can't seem to find anywhere a solid reason why / when the above should or should not be done. I'm aware that boost uses .hpp files to deliver template functions to end users without the need for an asso... |
'm aware that boost uses .hpp files to deliver template functions to end users without the need for an associated .cpp file
Wrong verb: it’s not “without the need”, it’s “without the ability”.
If Boost could, they would separate their libraries into headers and implementation files. In fact, they do so where ever pos... |
3,841,299 | 3,841,324 | Copying a C++ class with a member variable of reference type | I've a class which stores a reference to its parent, the reference is passed in the constructor. If I try to copy an instance I get an error "error C2582: 'operator =' function is unavailable" presumably down to the reference being non-assignable.
Is there a way around this, or do I just change the variable to pointer ... | Yes, if you need to support assignment, making it a pointer instead of a reference is nearly your only choice.
|
3,841,327 | 3,841,358 | Defining constructor for struct declared inside a class in C++ | How can I declare constructor for a struct? My struct is declared in the private part of a class and I want to declare my constructor for it.
Below is my code
class Datastructure {
private:
struct Ship
{
std::string s_class;
std::string name;
unsigned int length;
... | Constructor declared in header file
struct Ship
{
Ship();
std::string s_class;
std::string name;
unsigned int length;
} minShip, maxShip;
and implemented in code:
DataStructure::Ship::Ship()
{
// build the ship here
}
or more likely:
DataStructure::Ship::Ship(const string& shipClass, const str... |
3,841,416 | 3,842,864 | Getting the index of boost::fusion::vector from a boost::mpl::vector | I started to play around with the boost fusion and mpl library and got stuck with a quite simple problem.
I declared the following types:
typedef boost::mpl::vector<char, int, long> TypeVector;
typedef boost::fusion::vector<char, int, long> FusionVector_t;
Now I wanted to write a function that gets me the value from... | You can use the find algorithm to get an "iterator" pointing to the first occurence of a type in an MPL sequence. Something like:
typedef boost::mpl::find<TypeVector, T>::type MplIter;
and then query the fusion vector at that "iterator"'s position:
return boost::fusion::at_c<MplIter::pos::value>(fvec);
However, I don... |
3,841,552 | 3,841,585 | Why is the compiler not warning about definitions with no names? | The following C++ code does nothing (using GCC 4.4.3) - it does not print the text:
struct MyStruct { MyStruct() { cout << "Hello" << endl; } };
void foo() {
MyStruct ();
}
I think this is not so obvious... Let alone the danger of forgetting to give a variable name. Is there a compiler option/warning to forbid comp... | This is not a declaration, because in MyStruct ();, the MyStruct would be part of the decl-specifier-seq and forms a type-name therein. And then () can only be a function-declarator. This requires that there is a declarator-id specified, which in your case is not. A special syntactical form is needed to allow such a sy... |
3,841,669 | 3,841,683 | Tell me the detail of virtual table in C++ | Can anybody tell me about the virtual table concept?
| Wikipedia's article is pretty good:
http://en.wikipedia.org/wiki/VTBL
And if Wikipedia's wrong, then I don't want to be right.
|
3,841,839 | 3,841,902 | difference between widening and narrowing in c++? | What is the difference between widening and narrowing in c++ ?
What is meant by casting and what are the types of casting ?
| This is a general casting thing, not C++ specific.
A "widening" cast is a cast from one type to another, where the "destination" type has a larger range or precision than the "source" (e.g. int to long, float to double). A "narrowing" cast is the exact opposite (long to int). A narrowing cast introduces the possibility... |
3,842,030 | 3,842,048 | C++ eof() problem - never returns true? | So I'm trying to read this file. Everything looks like it should work, but during runtime the program times out and stops working, and I have to close it. What is going on? I suspect that the oef() test is never returning true and it keeps looking for more in the file. I have no dragging empty lines in the text file. I... | eof returns true after you tried to read something and the operation failed. So put it after getline.
EDIT: try this code:
vector<Pet*> petArray;
ifstream textFile2("pets.txt");
string temp;
int tmpNum = 0;
while (getline(textFile2, temp))
{
if (temp == "Dogs") tmpNum = 0;
else if (temp == "Cats") tmpNum = 1;... |
3,842,181 | 10,105,361 | How to determine elements count in boost.preprocessor tuple`s? | How to determine elements count in boost.preprocessor tuple`s ?
| Boost 1.49 already has BOOST_PP_TUPLE_SIZE macro
|
3,842,353 | 3,842,378 | more efficient sparse matrix element accessor | I wrote a small sparse matrix class with the member:
std::map<int,std::map<int,double> > sm;
The method below is the function i use to access the elements of a matrix, if not possible through an iterator:
double matrix::operator()(int r,int c) const
{
std::map<int,std::map<int,double> >::const_iterator i = sm.find... | If you are to write your own code rather than using a library, then this change may improve performance dramatically:
std::map<std::pair<int,int>, double> sm;
To increase farther you can go to hashed containers:
std::unordered_map<std::pair<int,int>, double> sm;
(use tr1, boost or C++0x)
EDIT: in the first case you c... |
3,842,486 | 3,842,587 | How does std::stringstream handle wchar_t* in operator<<? | Given that the following snippet doesn't compile:
std::stringstream ss;
ss << std::wstring(L"abc");
I didn't think this one would, either:
std::stringstream ss;
ss << L"abc";
But it does (on VC++ at least). I'm guessing this is due to the following ostream::operator<< overload:
ostream& operator<< (const void* val );... |
Does this have the potential to silently break my code, if I inadvertently mix character types?
In a word: yes, and there is no workaround that I know of. You'll just see a representation of a pointer value instead of a string of characters, so it's not a potential crash or undefined behaviour, just output that isn't... |
3,842,827 | 3,842,841 | What are methods that affect their explicit parameters called? | I'm documenting some code in C++ right now, and one of the methods I intend to write will sort an array. It won't create a new array, though, it will sort the elements of the given array in place. I want to include a remark along the lines of, "if the original ordering was important to you, then don't use this method!"... | Sorts the given array in-place.
You are aware of std::sort and std::stable_sort, right?
|
3,842,871 | 3,842,887 | Installing C++ Boost library on Windows without Visual Studio | I would like to install Boost library without the need of Visual Studio compiler, preferably by downloading the pre-compiled binaries. We are working on a cross-platform C++ project in Eclipse, so VS is out of option.
About a year ago, I found an installer, but it does not longer exists.
The best match I have found so ... | Whichever toolchain that you are going to use on Windows, you can use that toolchain to compile Boost easily.
For example, if you use Eclipse CDT for C++ on Windows, you can use either MinGW or Cygwin toolchain. Then simply start the command prompt that has those toolchains (make, gcc, ...) in your path. Go to the Boos... |
3,842,938 | 3,843,796 | What is the proper way of handling linked lists in wxWidgets? | I wrote an application using wxWidgets that uses wxList. I am having some random crahses (segfault) in the destructors that collect the list data. I could not find a definite way of removing items from the list (Erase() VS DeleteNode()). Even iterating over the items has two flavours (list->GetFirst() VS list->begin())... | On the difference between list->GetFirst() and list->begin() in wxList API, it seems to be that list->GetFirst() returns NULL if list is empty and list->begin() returns the value of iterator to end list->end() as usual for other iterators. list->GetFirst() is the old API, list->begin() is the new one. The main benefit ... |
3,842,979 | 3,843,086 | C++ fill array with objects derived from array type | In C++ I have an array of pointers to Player objects and want to fill it with Fickle objects where Fickle is a class that is derived from Player. This is because I want a general Player array that I can fill with different objects from different classes that all are derived from the Player class.
How can I do this?
I ... | While you probably should be using a vector instead, there's no real reason a dynamically allocated array can't work. Here's a bit of working demo code:
#include <iostream>
class Player {
public:
virtual void show() { std::cout << "Player\n"; }
};
class Fickle : public Player {
public:
virtual void show() { s... |
3,843,275 | 3,843,385 | Linking Lua with Visual Studio 2010 | We use Lua (www.lua.org) script to let users to customize our server software written in C++.
At the moment we are porting the 32 bits Windows version of our project to Visual Studio 2010.
Once everything works fine with VS 2008, we thought that we would have no problem on upgrade process.
Unfortunately whenever we tri... | The reported missing names are correct, this not a compile problem. You must be linking the wrong .lib. The name you use sounds wrong, it isn't "lualib", the current version of the import library is named lua5.1.lib (or lua51.lib, not sure what the difference is). Download it from here.
|
3,843,350 | 3,843,526 | How to call a C++ DLL from VB6 without going through COM? | OK, so I have a C++ project that compiles to a DLL file. I am able to reference this file in C# and see/use all of the objects and functions within the DLL file. What I need to do is to reference those objects and function through VB6.
The C++ code has nothing in it that looks like it's creating a DLL. There are no '__... | Use regasm to create a COM Type Library (.TLB) file from your C++/CLI assembly.
You should now be able to reference the C++/CLI code by referencing the TLB file in your VB6 code. From the example there:
In its simplest form, you can do:
REGASM MyAssembly.dll
Now, all of the
COM-compatible classes are registered
... |
3,843,367 | 3,843,407 | What am I doing wrong that I can't render an image/texture properly in OpenGL? | I'm trying to render an image to the window. Super simple (or so I thought). No matter what I do, I always get this purple square. Some tidbits of my code:
// load image from file, called one time on load:
glClearColor (0.0, 0.0, 0.0, 0.0);
glShadeModel(GL_FLAT);
glEnable(GL_DEPTH_TEST);
RgbImage theTexMap( filenam... | Rebind your texture object in your glutDisplayFunc() callback, Just In Case™.
Also, I'm slightly leery of the GL_RGBA8. Try GL_RGBA. Probably superstition on my part though.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.