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 |
|---|---|---|---|---|
4,908,132 | 4,908,177 | My compiler allows "T&...". Is this an extension? | I was surprised when the following worked
template<typename T>
void f(T &...);
I thought that I have to declare "T" as "typename ...T" then, and that it only works in C++0x. But the above compiled in strict C++03 mode. What's going on?
| It's just the bad old C varargs syntax; the grammar allows omitting the comma. The following are equivalent:
int printf(const char* fmt, ...);
int printf(const char* fmt...);
|
4,908,193 | 4,908,881 | Create a reverse LinkedList in C++ from a given LinkedList | I'm having some trouble create a linkedlist in reverse order from a given linkedlist.
I come from a java background, and just started doing some C++.
Can you check out my code and see what's wrong? I'm guessing I'm just manipulating pointer and not creating anything new.
//this is a method of linkedlist class, it creat... | Easier one: Go through your linked list, save the previous and the next node and just let the current node point at the previous one:
void LinkedList::reversedLinkedList()
{
if(head == NULL) return;
Node *prev = NULL, *current = NULL, *next = NULL;
current = head;
while(current != NULL){
next =... |
4,908,203 | 4,909,947 | Generic structure of Intel C++ Compiler itself | I want to learn, how Intel C++ Compiler works. I want to find a diagramm, which will show the internal structure of Intel compiler for X86 and X86_64 with major parts of it drawn. Parts I want are "Code generation", "Front-end", "Back-end", register allocation, analysises, etc.
I was able only to find a picture for Ita... | You could try hunting around intel's website using google with the following search criteria:
site:intel.com +compiler +design
site:intel.com filetype:pdf +compiler +design
I came across:
An Overview of the Intel® IA-64
Compiler
The Making of a Compiler for the
Intel® ItaniumTM Processor
Which I think might help...... |
4,908,317 | 4,908,411 | Iterate through STL sequence and associative containers using same code? | Let's say I'd like to write an algorithm that prints the value of each element in a container. The container could be a Sequence or Associative container (e.g. std::vector or std::map). In the case of a sequence, the algorithm would print the value_type. In the case of an associative type, the algorithm would print the... | The difference that you have between your two function templates is not a difference between associative containers and sequences but a difference in the part of the type that is stored.
To clarify, std::set is an associative container but would work with your printSequence function; the problem with map is not the fac... |
4,908,351 | 4,908,377 | Collection of good C++ Themes in Visual Studio 2010? | I have found the site: http://studiostyl.es/ which specializes in Visual Studio 2010 themes. However, it appears that all of these themes are built with C# and .NET development in mind.
I am currently trying to get into some C++ programming and couldn't find anything on the subject of special themes for C++. Right now,... | Get Visual Assist X and don't look back.
Edit: There is also Refactor! for C++. As you can guess from the name, it's oriented primarily toward refactoring code, but if memory serves can also do some colorizing and such. I haven't used it recently enough to say much more than that (I've used VA-X for years, and a couple... |
4,908,379 | 4,908,440 | What is the scope of global variables inside C++ DLLs | Let's say a 3rd-party DLL X has a global variable G
I write two separate DLLs (as plugins for an app) P1 & P2 which both dynamically load X.
The application's process loads my two plugins P1 & P2 so both are loaded at the same time.
Does this mean I have one instance of G or two?
edit:
The usage scenario is X is a 3D r... | The DLL loading routines exposed in the Win32 API make sure you only have one copy of a DLL loaded per process (see the "Remarks" section here, particular paragraph three and the last paragraph before the Security Remarks section, where per-process reference counts are discussed). I assume you're just calling LoadLibra... |
4,908,392 | 4,908,737 | How to implement template class covariance in C++? | Is it possible to implement a class template in such a way that one object could be casted to another if their template arguments are related? Here is an exaple to show the idea (of course it will not compile):
struct Base {};
struct Derived : Base {};
template <typename T> class Foo {
virtual ~Foo() {}
virtua... | The template argument has nothing to do with the content of the object you are pointing to. There is no reason this should work. To illustrate
struct Base { };
struct Derived : Base {};
template<typename T> struct A { int foo; };
template<> struct A<Base> { int foo; int bar; };
A<Derived> a;
A<Base> *b = &a; // assum... |
4,908,417 | 4,908,503 | List of IDispatch errors and/or message texts | I am calling methods on WMI/WBEM interfaces that return HRESULTS. I want to display meaningful error messages for these error codes to the user. However, when I look up the HRESULT's error message I only get strings like "IDispatch error #3598".
Were can I find a list of these IDispatch error codes that explains their ... | COM servers can generate their own HRESULT error codes. The IErrorInfo interface helps a client to get a description of the error. You are not giving the _com_error class a chance to do that job, you don't pass the IErrorInfo interface pointer to the constructor.
First QI the interface for ISupportErrorInfo and call ... |
4,908,539 | 4,908,662 | a way in c++ to hide a specific function | i have an inheritance struct A : public B, i want to hide individual functions from B, is this possible?
i know the opposite is possible using using BMethod in the A declaration.
cheers
| If you want to selectively hide functions from B it does not make much sense to use public inheritance in the first place.
Use private inheritance & selectively bring methods from B into the scope of A:
struct B{
void method1(){};
void method2(){};
};
struct A : private B{
using B::method1;
};
A a;
a.method1(... |
4,908,567 | 4,908,605 | Is there any C/C++ library similar to apache httpcomponents? | are there any library similar to apache httpcomponents for c/c++ language?
Thanks in advance,
Dario.
| I'm not sure how similar they are to those particular Apache components, but you might want to look at POCO and ACE. Both provide quite a bit in the way of networking in C++. ACE tends to be the more all-encompassing of the two (both in terms of supporting lots of protocols and such, and in terms of tending to control/... |
4,908,696 | 4,908,816 | Defining buffer size correct "Stack around the variable String was corrupted" | I have these two lines in my code:
TCHAR String[400] = {0};
SendMessageW(hwnd, WM_GETTEXT,sizeof(String), (LPARAM)String);
When I use it that way I sometimes get a runtime error: "Stack around the variable String was corrupted"
When I use
TCHAR String[400] = {0};
SendMessageW(hwnd, WM_GETTEXT,10, (LPARAM)String);
it... | You are using wchar_t, sizeof(String) will be 800, not 400. Fix:
wchar_t String[400] = 0;
SendMessageW(hwnd, WM_GETTEXT, sizeof(String) / sizeof(wchar_t), (LPARAM)String);
|
4,908,907 | 4,908,915 | Changing the main file in a C++ netbeans project | When I create a new C++ project in netbeans,it prompts me to choose a name for the main file of the project
this is the file that gets executed when I press "Run" in the IDE
does anybody know how to change this file to another one AFTER I've already created the project?
| You don't need to change the name or point to a different file.
In C++, on NetBeans or any other IDE, just place main function on a different file (the file you want to RUN when you press RUN on the IDE) and you should be done.
|
4,909,340 | 4,909,374 | Developing an ISAPI filter | I want to develop an ISAPI filter which shall read the headers of an URL, this shall talk to an ASP .NET application . Can this be achieved in C# , or do I need to develop this in C++ , and create a CLI/C++ DLL so that the ASP .NET application can communicate with the C++ dll .
| In .Net you use HTTPModule and HTTPHandlers to accomplish what ISAPI gave you before.
Here is a decent MSDN article: http://msdn.microsoft.com/en-us/library/bb398986.aspx
|
4,909,399 | 4,909,584 | Is it possible to to cascade overloaded extraction operator with overloaded arithmetic operators? | I am trying to implement a class COMPLEX in C++ and overload the arithmetic operators as well as the '<<' and '>>' operators for input/output. Individually and also when cascaded the arithmetic operators work as expected - but i am unable to obtain correct results when trying to execute statements such as:
cout << ... | The problem is that your stream insertion operator is defined as
friend ostream& operator << (ostream &, COMPLEX &);
This takes a non-const reference to a COMPLEX object as the second parameter. When you try writing
cout << a + b << endl;
The value of a + b is an rvalue, not an lvalue, because it's the value returne... |
4,909,403 | 4,909,457 | Simple C++ program help compiling | Guys I am a starting programmer and need help. I am working on PART A ONLY of an assignment located here: http://cs.binghamton.edu/~sgreene/cs240-2010f/labs/lab2.html
However I am having trouble compiling my programs. Please tell me what im doing wrong in my makefile and in the cpp files! Here are my files:
# CS240 La... | I think your makefile should look more like this:
all: lab2
lab2: main.o tenstrings.o
g++ main.o tenstrings.o -o lab2
main.o: main.cpp
g++ -Wall -c main.cpp -o main.o
tenstrings.o: tenstrings.cpp
g++ -Wall -c tenstrings.cpp -o tenstrings.o
that might sort out your first two errors.
|
4,909,420 | 4,912,727 | C++: How to force libc declarations into std::? | So, I find myself in the need of libc in my C++ program. However, I do not like the idea of sprinkling it all over the global namespace. Ideally, I'd like to force the entirety of libc into the std:: namespace so I'd have to do std::memcpy rather than memcpy.
Is this possible? And how? I'm willing to use compiler-speci... | You cannot do this, unless it's already done.
The namespace std is reserved to the Standard Library, it is forbidden to add new members to this namespace. Therefore, if the C-headers are not already embedded within std, then you have no choice but to accept it.
On the other hand, you can perfectly create a new namespac... |
4,909,598 | 4,909,622 | zlib compress2 returning Z_STREAM_ERROR | char buffer[12] = {"Testing! 12"};
unsigned long compressedSize;
char* compressed = compress(buffer, 12, &compressedSize);
...
char* compress(char* buffer, unsigned long size, unsigned long* compressedSize)
{
Bytef* inBuffer = reinterpret_cast<Bytef*>(buffer);
uLong inSize = static_cast<uLong>(size);
By... | Your outBuffer is a NULL pointer. You cannot pass a NULL pointer as the output buffer to compress2 , compress2 needs some space to store the compressed data, so allocate a buffer that's compressBound(inSize) big. It's evident from the prototype of compression2 that you can't have compres2 allocate and "return" such a b... |
4,909,716 | 4,909,783 | Time mask in TMaskEdit | Is it real to write mask for correct time input?
Max hours: 23
Max mins: 59
23:59
| @Funtime, why you are using a TMaskEdit componnet? instead try a using a a TDateTimePicker. You must set the format property to HH:mm and the DateMode property to dmUpDown and will look like this.
And now you can access the current time selected reading the Time property
|
4,909,766 | 4,909,801 | Is it unspecified behavior to compare pointers to different arrays for equality? | The equality operators have the semantic restrictions of relational operators on pointers:
The == (equal to) and the != (not equal to) operators have the same semantic restrictions, conversions, and result type as the relational operators except for their lower precedence and truth-value result. [C++03 §5.10p2]
And t... | The semantics for op== and op!= explicitly say that the mapping is except for their truth-value result. So you need to look what is defined for their truth value result. If they say that the result is unspecified, then it is unspecified. If they define specific rules, then it is not. It says in particular
Two pointers... |
4,910,106 | 4,910,229 | Compile C programs with Visual Studio 2005? | Can I use Visual Studio 2005 to compile simple C programs? There appears to be only options to create projects for VB, C# or C++. If this is possible, what do I need to do?
| To give you a more concrete answer, Visual Studio will definitely compile C code under a C++ project. It will even compile it as C code, not C++ - Visual Studio treats anything with a .c extension as C code and will compile as such by default. This is confirmed in the documentation on MSDN (albeit only specified for ... |
4,910,145 | 4,914,359 | Get time_t / timeval corresponding to ( local_timezone ) midnight on a given date | Given a time_t or struct timeval, how do I get the timeval or time_t of midnight EST/EDT ( local timezone ) on that day ?
As in assuming local timezone is EST/EDT, given a time_t corresponding to say 2010-11-30 08:00:00 EST/EDT, the expected answer is a time_t that corresponds to 2010-11-30 00:00:00 EST/EDT
Attempt 1 (... | Current solution :
time_t RewindToMidnight ( const time_t & temp_time_t_ )
{
int temp_yyyymmdd_ = iso_date_from_time_t ( temp_time_t_ );
return time_t_from_iso_date ( temp_yyyymmdd_ );
}
int iso_date_from_time_t ( const time_t & in_time_t_ )
{
tm temp_this_tm_;
{ // the following to set local dst ... |
4,910,313 | 4,910,332 | What is the purpose of a double negative in macro definition, like (!!(expr))? |
Possible Duplicate:
Double Negation in C++ code.
I'm reading a code base, and find something like this:
#define uassert(msgid, msg, expr) (void)((!!(expr))||(uasserted(msgid, msg), 0))
I cannot figure out why (!!(expr)) is used instead of a single (expr). Anyway, a double negative means positive, is not it? Am I m... | It is a way to cast an expression to bool. In C++ though, operator! can be overloaded. Another way for C/C++:
0 != (expr)
C++ only way:
static_cast<bool>(expr)
[Edit]
Thinking more about C++ operator overloading, it make sense to avoid using operators. Libraries like Boost.Spirit and Boost.Lambda use expression templ... |
4,910,316 | 4,910,340 | Enumeration trouble: redeclared as different kind of symbol | I am writing a program that is supposed to help me learn about enumeration data types in C++. The current trouble is that the compiler doesn't like my enum usage when trying to use the new data type as I would other data types. I am getting the error "redeclared as different kind of symbol" when compiling my trangleSha... | Your problem has nothing to do with enums. The problem line is this line in your triangleShape definition:
triangleType triangleShape(sideLenght1, sideLength2, sideLength3)
You're missing the types for your parameters and some compilers such as gcc default to int (although this isn't standard behaviour so you should n... |
4,910,324 | 4,912,280 | Can't get a reference to IPart | I'm trying to get a reference to the IPart interface to control Windows audio volume level, for example, and I'm using the IDeviceTopology::GetPartById function to get it.
This function takes a UINT. I tried 0 and got nothing, then gave in and just tried incrementing a UINT until I could get a reference. No luck that w... | The easiest way is to enumerate the host pins and call GetSignalPath from the desired input to the desired output, that will return you a collection of parts.
Alternatively, if you have a topology object, you can call GetSubunit or GetConnector to retrieve the subunits or connectors (which are also parts). From each c... |
4,910,345 | 4,910,384 | Storing pointers in multi-dimensional array | My intention is to create a dynamic 3D array in C++ using pointers.
MyType*** myArray;
myArray = new MyType**[GRID_SIZE];
for (int i = 0; i < GRID_SIZE; ++i) {
myArray[i] = new MyType*[GRID_SIZE];
for (int j = 0; j < GRID_SIZE; ++j) {
myArray[i][j] = new MyType[GRID_SIZE];
}
}
Now this 3D array is ready to s... | Simply add another * to your declaration, but don't call new on it.
|
4,910,373 | 4,918,873 | Interoperability between boost::date_time and std::chrono | How interoperable are boost::date_time and std::chrono?
For example, is there a way to convert between boost::posix_time::ptime and std::chrono::time_point?
I tried searching for documentation on such conversions but couldn't find any.
| I found this on the boost commits mailing list: http://lists.boost.org/boost-commit/2009/04/15209.php
Here are the relevant functions:
template < class Clock, class Duration>
struct convert_to<posix_time::ptime, chrono::time_point<Clock, Duration> > {
inline static posix_time::ptime apply(const chrono::time_point... |
4,910,426 | 4,910,443 | Find if a string contains a name like 'John' or a general word | I want to find all the person names like John etc. embedded in a piece of english text. What is the best way to do this in C++?
| You should use a toolkit - see http://en.wikipedia.org/wiki/Natural_language_processing_toolkits. There are several in C or C++ and these will have tools for Proper names. The names will be identified by lookup, by context and by other NLP heuristics. This may need to be combined with a lookup service if you have a spe... |
4,910,699 | 4,910,777 | Help With C++ CLASS Definition | I have this bit of code:
int main()
{
String s1; // s1 == ""
assert(s1.length() == 0);
String s2("hi"); // s2 == "hi"
assert(s2.length() == 2);
cout << "SUCCESS" << endl;
}
And I want to write a class that will go through it and get to the ending "cout" statement.
So far, all I have is this:
#include... | Do you know anything about pointers and arrays?
String is basically an array of characters. What you need to do is to always allocate the right amount of memory using the new[] operator, make sure it's cleaned up when it's supposed to be (you've got it right, the delete[] operator is the correct way) and put there the... |
4,910,815 | 4,910,824 | if statement problem? | My program is up and running but there is a problem with my if statements somewhere that is making "scalene" be the output in addition to the correct output (unless scalene is the correct output). take a look at the issue:
Can anyone spot the bug?
triangleShape function
# include "header.h"
triangleType triangleShape... | You have an extra semi-colon on this line:
else (triangleShape (sideLength1, sideLength2, sideLength3) == scalene);
Remove the semi-colon at the end, and add an if in the line (or remove the check completely). It's causing the print following the "else" to always occur, as it becomes a separate statement.
You can do... |
4,911,008 | 4,911,443 | Now I can't get the numerator to output any number. When I do this I get 0/whatever denominator. What am I missing? | //This program evaluates an expression of two fractions added or subtracted
#include <iostream>
#include <cmath>
using namespace std;
int CrossMultiplication(int, char, int);
int DenominatorConversion(int, int);
int main(){
int NumeratorA;
int NumeratorB;
int DenominatorA;
int DenominatorB;
char Ope... | in function Crossmultiplication, your values for DenominatorA and DenominatorB are not properly initialized. Try to change it into something like
int CrossMultiplication (int NumeratorA, int DenominatorA, char Operation, int NumeratorB, int Denominator B)
and change the function call accordingly.
Also, your return st... |
4,911,187 | 4,912,324 | vector::at reference | Given this definition:
vector<some_struct_t> lots_of_stuff;
And the fact that vector::at returns a reference, this code makes sense to me:
some_struct_t & ref_element = lots_of_stuff.at(0);
But, this code also compiles and seems to work:
some_struct_t val_element = lots_of_stuff.at(0);
How can a non-reference work h... | A reference of type T is simply an lvalue expression of type T just like a variable's name of type T is an lvalue expression of T. So, ...
vector<T> v = ...;
T a = ...;
T b = a;
T c = v.at(0);
there is little difference between how b and c are initialized because on the right hand side is simply an lvalue expression o... |
4,911,224 | 4,911,244 | Why does a forward declaration not fix the circular dependency? | I have three classes: a TopClass which contains an instance of a BottomClass pointer. The BottomClass contains a pointer to a HelperClass. The HelperClass keeps a pointer to the TopClass. Circular dependency pops up and a forward declaration is needed in the HelperClass.
All of this is illustrated with the following co... | The problem is that you're forward declaring TopLevel outside the foo namespace so the compiler is never finding the class foo::TopLevel.
Try moving the forward declaration of TopLevel inside the foo namespace.
|
4,911,270 | 4,911,428 | C++ simple program help String Data | Thanks for helping me in advance! I am used to Java and C# but C++ is completely different. I am trying to do part B of this lab: http://cs.binghamton.edu/~sgreene/cs240-2010f/labs/lab2.html
Is this the idea that is assigned in Part B? Also I dont know what exactly is missing in the header file that deals with indef en... | I notice that the assignment carries this warning:
This is an individual assignment - you may NOT work in groups. Do not write or dictate code for anyone else, and do not use code from anyone else. If you break this rule, you may fail the entire class.
Hence I will provide only some guidance, not code.
First I dont kn... |
4,911,284 | 4,911,431 | Typecasting an array of structs (of pointers?) to be sent through winsock | I'm still getting my head around pointers and the like, so here goes...
Each client sends the position of the player correctly to the server.
On the server the data is then put into an array of structs (or points to structs?). The data of that array has also been verified to be correct.
The server then is meant to se... | PlayerShip *playerArray[serverMaxClients];
declares an array of serverMaxClients pointers, each of which points to a PlayerShip structure.
Here
char* outgoing = (char*)playerArray;
you're referring to the address of this array of pointers, so your call to send will send a bunch of pointers, which is almost certainly... |
4,911,313 | 4,911,434 | Passing struct from array of structs to pthread_create | I have created an array of structs. I am attempting to pass one element in this array to a thread through pthread_create. I am getting the following errors (they are for the 2 pthread_create calls I have in for loops):
/../a2/main.cpp|117|error: invalid conversion from ‘void (*)(serverDataStruct*)’ to ‘void* (*)(void... | Your functions are defined correctly, but your forward declarations are incorrect.
Change these two lines:
void serverFunc(serverDataStruct *serverData);
void clientFunc(int *ticketNum);
to match the function definitions:
void *serverFunc(void *serverData);
void *clientFunc(void *ticketNum);
Btw, please edit your que... |
4,911,407 | 4,911,471 | Constant reference to void* pointer | I want to alias a void* variable so I can use it with another name. This would mean I could set pointer (p) to something, and the aliased variable (pp) would also be set to same adress.
For instance:
class foo {
private:
static void* p; //I just happen to need this for static variable
static const void*& pp;
... | What you are trying to do, i.e. set a const void* & to point to void* seems like it should be legal and harmless enough, but it isn't, and it is illegal for a good reason. Remember that a reference is just an alias to what it is referencing.
Say we could do this:
const void* & foo::pp = foo::p; // illegal as we will se... |
4,911,470 | 4,911,493 | converting strings to dates c++ | I'm using < time.h > to convert between strings and dates in c++.
int main() {
string dateFormat = "%m-%d-%Y %H:%M:%S";
tm startDate, endDate;
if (strptime("1-1-2004 01:01:01", &dateFormat[0], &startDate) == NULL) { exit(1); }
if (strptime("1-1-2010 00:00:00", &dateFormat[0], &endDate) == NULL) { exit(... | I figured it out. asctime uses a shared piece of memory to write the strings to. I have to copy that to another string so that it does not get overwritten.
int main() {
string dateFormat = "%m-%d-%Y %H:%M:%S";
tm startDate, endDate;
if (strptime("1-1-2004 01:01:01", &dateFormat[0], &startDate) == NULL) { ex... |
4,911,548 | 4,911,652 | Following use of getline, cannot write to file | I'm building a large file I/O library and am currently struggling with the interoperability of getline() and writing to a file. My question below is alot like this one, which unfortunately remains unanswered: C++ After I use getline to read from a file I can no longer write to the txt file
Once I've used getline(), I'm... | Based on some experimentation, it looks like the << operator expects the offset to be at the end of the file. I can't explain it exactly, but it seems that the offset isn't where it expects it to be after you call getline(). I was able to get writing to the file to work by adding the line:
workFile.seekg(ios_base::en... |
4,911,993 | 4,912,662 | How to generate and run native code dynamically? | I'd like to write a very small proof-of-concept JIT compiler for a toy language processor I've written (purely academic), but I'm having some trouble in the middle-altitudes of design. Conceptually, I'm familiar with how JIT works - you compile bytecode into (machine or assembly?) code to run. At the nuts-and-bolts l... | Not sure about linux, but this works on x86/windows.
Update: http://codepad.org/sQoF6kR8
#include <stdio.h>
#include <windows.h>
typedef unsigned char byte;
int arg1;
int arg2;
int res1;
typedef void (*pfunc)(void);
union funcptr {
pfunc x;
byte* y;
};
int main( void ) {
byte* buf = (byte*)VirtualAllocEx( G... |
4,911,994 | 4,912,131 | Sharing a global/static variable between a process and DLL | I'd like to share a static/global variable only between a process and a dll that is invoked by the process. The exe and dll are in the same memory address space. I don't want the variable to be shared among other processes.
Elaboration of the problem:
Say that there is a static/global variable x in a.cpp. Both the exe... | First, I found that this article was a very interesting and a concise read on dynamic link libraries (the article is only specific to Linux, but the concepts surely apply to windows as well and you might get some insight as to the different behaviour you are seeing). Especially the fundamental difference between static... |
4,912,264 | 4,912,286 | Problem In Separating The Interface And The Implementation | Its the first time I am trying to separate the class in a separate header file but I am getting an error.Please help me out.Thanks
CODE:
My main function:
#include <iostream>
#include <MyClass>
int MyClass::data;
int main()
{
cout<<"data="<<MyClass::data;
system("pause");
return 0;
}
MyClass.h
#ifndef MyCl... | You should use
#include "MyClass.h"
angle brackets are for system headers.
Also it's data or data_?
Also it would be better something like
#if !defined(MYCLASS_H_INCLUDED)
#define MYCLASS_H_INCLUDED
...
#endif
#define-ing a name identical to the class name is going to be a source of problems
|
4,912,313 | 4,912,322 | What is the syntax for initializing a struct in C++? | Can I build a constructor to initialize a struct this way:
mystruct struct1(a,b);
the same way I initialize a class?
Or do I have to use this way:
mystruct struct1=mystruct(a,b);
?
| You can use the same syntax as you use for class. In C++, there is no difference between them except for the default access specifiers which is public for struct and private for class. See here for detailed explaination: Difference between struct and class
|
4,912,380 | 4,912,492 | Move list element to the end in STL | I have already the list pointer of CDrawObject*
std::list<CDrawObject*> elements;
How I can move some element to the end of list.
I see STL Algorithms Reference but i don't find this operations. How i can do it?
| Use the list method splice()
void list::splice ( iterator position, list<T,Allocator>& x, iterator i );
Move iterator i from list x into current list at position "position"
Thus to move it to the end put
x.splice( x.end(), x, iter );
(they can both be the same list or different lists as long as the list from which the... |
4,912,467 | 4,912,493 | C , C++ unsynchronized threads returning a strange result | Okay, i have this question in one regarding threads.
there are two unsynchronized threads running simultaneously and using a global resource "int num"
1st:
void Thread()
{
int i;
for ( i=0 ; i < 100000000; i++ )
{
num++;
num--;
}
}
2nd:
void Thread2()
{
int j;
for ( j=... | num++ and num-- don't have to be atomic operations. To take num++ as an example, this is probably implemented like:
int tmp = num;
tmp = tmp + 1;
num = tmp;
where tmp is held in a CPU register.
Now let's say that num == 0, both threads try to execute num++, and the operations are interleaved as follows:
Thread A ... |
4,912,846 | 4,912,982 | Unable to iterate std::map of Poco::Any | I have a std::map of Poco::Any which I'm trying to iterate and output to a stream but i'm getting a compiler error. My code is below:
map<string, Poco::Any>::const_iterator it;
map<string, Poco::Any>::const_iterator end = _map.end();
map<string, Poco::Any>::const_iterator begin = _map.begin();
for(it = begin; it != end... | Runtime type information cannot be used to instantiate templates. An instance of type_info whose value will only be known when you run the program, doesn't magically turn into a type like int, std::string or struct FooBar when the compiler is compiling this code.
I don't know Poco library, but perhaps you could use the... |
4,913,138 | 4,913,278 | /usr/bin/ld: warning: abc.so, needed by xyz.so not found (try using -rpath or -rpath-link)" | I am building a C++ application, using Netbeans 6.9 as my IDE. I have a C++ library which is a wrapper around a pure C library.
I have correctly added the file to the project (using the Add Library File option). Here is the output produced by g++ and the linker:
g++ -o dist/Debug/GNU-Linux-x86/testluaembed build/Debug... | Make sure the directory where libtanlib_core.so is placed is configured in /etc/ld.so.conf (or /etc/ld.so.conf.d/) - otherwise ldconfig will not find it.
|
4,913,161 | 4,913,192 | Are pointers allowed as keys in ordered STL containers? | There's this other question asking about how comparing pointers is supposed to be interpreted wrt the C++ Std.
So I was wondering what the C++ Std has to say about using pointers as keys in ordered standard library (STL) containers -- i.e. is one allowed to have
std::map<T1*, T2>
and is this due to the specification of... | Yes, because it uses std::less, which is required to result in a total order even if < doesn't. (< would be allowed to treat different pointers from distinct sequences as equal, which would result in an odd behaviour of map etc if you insert pointers from different sequences).
|
4,913,254 | 4,914,943 | “Uninitialized use” warning in the g++ compiler | I’m using g++ with warning level -Wall -Wextra and treating warnings as errors (-Werror).
Now I’m sometimes getting an error “variable may be used uninitialized in this function”.
By “sometimes” I mean that I have two independent compilation units that both include the same header file. One compilation unit compiles wi... | An algorithm that diagnoses uninitialized variables with no false negatives or positives must (as a subroutine) include an algorithm that solves the Halting Problem. Which means there is no such algorithm. It is impossible for a computer to get this right 100% of the time.
I don't know how GCC's uninitialized variabl... |
4,913,258 | 4,913,554 | How to create a undeletable registry key (or file) in C++ | I would like to create time limited version of a game I am developping in C++.
I already meet some program that create files I am still not able to delete, and other that created registry key very hard to delete (because there were several sub key and needed to change owner to the deeper first, delete it go up, change ... | The standard Windows API is unable to deal with null characters in key/value names, whereas the native API can. As such, you can create a key containing one or more NULL characters in the name to store your licensing data, which would not be deletable using standard tools like regedit.
See: http://technet.microsoft.com... |
4,913,265 | 4,913,293 | assign to std:vector from a structure containing an array | I am trying to assign data from a struct to a std::vector
Here is the code
struct myArray
{
double * data;
size_t len;
};
typedef std::vector<double> DoubleVect;
DoubleVect myvect;
MyArray myarr;
// code to initialize alloc and populate the MyArray variable
// ....
myvect.assign(&myarr.data, &myarr.data... | Yes. Get rid of the address operator and it will be fine. Taking the address of the data member data gives you an expression of type double**. This is certainly not what you want.
|
4,913,272 | 4,913,287 | iterate std::vector<std::vector<char> >? | I have a vector like this:
std::vector<std::vector<char> > _lines;
I would like to iterate these vector and the vector contained within, however I'm not sure how I'd access the inside vector using the iterator of the first one?
I have the following already:
std::vector<std::vector<char> >::iterator first_iter = _lines... | for (std::vector<std::vector<char> >::iterator i = _lines.begin();
i != _lines.end(); ++i)
{
for (std::vector<char>::iterator j = i->begin(); j != i->end(); ++j)
{
// ... use *j
}
}
If you use a modern compiler, you can use the C++0x feature auto to de... |
4,913,350 | 4,913,454 | Boost installation and library paths | I have been using Boost (the header only library part) for sometime now. I recently started on a project that required the compiled libraries (filesystem etc).
I followed the instructions given in the documentation, and was under the impression that the libraries to installed (directly) in the usr/local folder. After ... | An example for linking regex static(*.a) lib:
g++ -I /usr/local/boost_1_45_0 -c your_regex_prog
g++ -static -o static_regex your_regex_prog.o -lboost_regex
|
4,913,611 | 4,913,737 | Opencv and Visual Studio 2010 | I am trying to use Opencv in the environment of Visual Studio 2010. My computer is 64 bit and I use vs 2010 64 bit too. I searched many tutorials on how to configure opencv in vs 2010. However, I could not succeed.
There is a video about compile and configure the vs 2010 and opencv
http://www.youtube.com/watch?v=XeBhw... | In Visual C++ you need to tell the compiler where to look for the OpenCV LIBRARIES and headers.
Looks like the compiler cannot find the libraries.
OR
According to:
http://opencv.willowgarage.com/wiki/VisualC%2B%2B
a) OpenCV 2.1 has problems in 64 bit configuration, upgrade.
b) As the above link suggests, build the Libr... |
4,913,630 | 4,913,665 | LNK2019 error while creating an object in another solution c++ | I'm trying to create objects by using another c++ solution's files.
When I create a MyClass1 object program gives error of:
1>main.obj : error LNK2019: unresolved external symbol "public: virtual __thiscall MyClass1::~MyClass1(void)" (??1MyClass1@@UAE@XZ) referenced in function _main
1>main.obj : error LNK2019: unreso... | It seems like the myclasses.o file is missing. Are you sure you're compiling and linking myclasses.o?
Since this is Qt, have you run "qmake -project" after you added this source file to your project?
|
4,913,631 | 5,041,116 | Layered COLLADA Loader for OpenGL3.1+ Context | What layers would aid in implementing this efficiently? Preferably such that I am able to get these three components listed below up with the early layers and code the rest as I go.
I am writing a COLLADA loading library to use with my graphics engine. So of course as soon as I began I notice this seems to be a rather ... | Are you aware of Open Asset Import Library (http://assimp.sourceforge.net/)? It has quite decent support for Collada loading and targets use in graphics engines. Writing a collada loader on your own is not only hard, it also takes ages to get it stable enough for productive use, mostly because the format is terribly co... |
4,913,683 | 4,913,716 | storage allocation at opening brace of scope in c++? | while reading from BRUCE ECKEL'S THINKING IN C++..i came across the following text
In c++,a variable can be define at any point in a scope,so it might be seem that storage for variable may not be define until its point of definition .It's actually more likely that the compiler will follow in c of allocating all the s... | The compiler can analyze the entire function before actually emitting any code. Typically, the compiler will work out, for each braced segment, how much storage is required, and add a single assembly instruction in the function prologue to adjust the stack pointer by that many bytes.
Actually initializing the variables... |
4,913,702 | 4,962,206 | C++ inheritance: virtual member needs redeclaring? | I'm sure this question has already been asked in one form or another, but I couldn't find the clue. Please consider the following C++-code:
// A.h
class A
{
public:
A();
virtual ~A();
virtual void setVisibility(bool v);
virtual bool setVisibility();
protected:
bool visib... | The other answers are all correct before the correction. But it's not the solution to the problem. There actually isn't any problem at all. The problem lies in my implementation of the setVisibility-method, that's where the segfault occurs. Therefore the solution can't be found here.
Thanks to all who tried to help!
re... |
4,913,894 | 4,913,933 | replacing double space to single space | How can I replace the double space into single space using C++
ex:
"1 2 3 4 5" => "1 2 3 4 5"
this is what I`ve done till now:
int _tmain(int argc, _TCHAR* argv[])
{
string line;
ifstream myfile(myFile);
if(myfile.is_open())
{
cout<<"File Opened ...\n";
while(myfile.good())
... | In while loop of splitLines code, use this code.
while((loc = line.find(" ")) != std::string::npos) //Two spaces here
{
line.replace(loc,2," "); //Single space in quotes
}
cout << line << endl;
Thats it. I haven't tried it out, let me know if it works.
And as fred pointed out, use pass by reference in... |
4,913,919 | 4,914,233 | C++: Check istream has non-space, non-tab, non-newline characters left without extracting chars | I am reading a std::istream and I need to verify without extracting characters that:
The stream is not "empty", i.e. that trying to read a char will not result in an fail state (solved by using peek() member function and checking fail state, then setting back to original state)
That among the characters left there is... | this is what I did to skip whitespace/detect EOF before the actual input:
char c;
if (!(cin >> c)) //skip whitespace
return false; // EOF or other error
cin.unget();
This is independent of what data you are going to read.
This code relies on the skipws manipulator being set by default for standard streams, but it... |
4,913,922 | 4,914,108 | Possible problems with NOMINMAX on Visual C++ | What problems could I get when defining NOMINMAX before anything else in my program?
As far as I know, this will make <Windows.h> not define the min and max macros such that many conflicts with the STL, e.g. std::min(), std::max(), or std::numeric_limits<T>::min() are resolved.
Am I right in the assumption that only Wi... | Using NOMINMAX is the only not-completely-evil way to include <windows.h>. You should also define UNICODE and STRICT. Although the latter is defined by default by modern implementations.
You can however run into problems with Microsoft’s headers, e.g. for GdiPlus. I’m not aware of problems with headers from any other c... |
4,914,118 | 16,353,259 | How to doxygen comment Qt properties? | I would like to attach Doxygen comments to my Q_PROPERTYs.
For example:
song.h
class Song : public QObject
{
Q_OBJECT
private:
Q_PROPERTY(QString title READ title WRITE setTitle);
QString _title;
public:
QString title() const;
void setTitle(const QString& value);
};
song.cpp
#include "song.h"
S... | I have finally found a way to do this.
In the source files:
/**
* @brief The name of the user.
* @accessors name(), setName()
*/
Q_PROPERTY(QString name READ name WRITE setName)
In the Doxyfile:
ALIASES = "accessors=\par Accessors:\n"
What I've done is define an alias named "accessors" that will generate a parag... |
4,914,183 | 4,914,877 | What's the correct way to add 1 byte to a pointer in C/C++? | I'm using this code to move pointer by 1 byte now, but I'm feeling something unclear..
int* a = (int*)malloc(sizeof(int));
void* b = ((char*)a)+1;
char is 1 byte, but not defined for byte operation purpose. I believe there's another way to do this byte operation. What's the correct way to byte operation?
PS. I modi... | I think you are confused:
char is 1 byte, but not defined for byte operation purpose. I believe there's another way to do this byte operation. What's the correct way to byte operation?
What exactly are you expecting byte to mean, if not the exact same thing that char means?
In C and in C++, chars are bytes. By defini... |
4,914,365 | 4,914,456 | Computing Rotation Speed In C++ | Basically, In C++, how do I compute how long will it take for a car wheel to rotate 360 degrees while moving at a speed of 10 MPH? I've tried googling but nothing showed up. Any ideas?
As usual, I've searched this site for an answer but nothing showed up - unless I missed one.
Thanks.
| If you know the speed of your object and the radius of the circle it moves on, then the time needed for one rotation is
rotation_time = 2*pi*radius/speed
The number of rotations per time unit is
rotation_speed = 1/rotation_time
The angular speed is
angular_speed = full_circle/rotation_time,
with the value of full_ci... |
4,914,488 | 4,914,496 | How to manage passing a pointer to an array to a function | I have a buffer of points that I want to send off to be processed by a function. It is an array of unsigned shorts. Currently I'm trying the following:
void ftn(unsigned short **buffer, int size)
{
for (int i = 0; i < size; i++)
{
*(buffer[i]) = 0; //test
}
}
Outside of the function, it's defined... | When you pass an array to a function, you don't actually pass the array by value. Rather, you actually pass a reference to the original array.
Therefore, you simply need to do:
void ftn(unsigned short buffer[], int size)
{
for (int i = 0; i < size; i++)
{
buffer[i] = 0; //test
}
}
Note that if you ... |
4,914,987 | 4,916,132 | When is precomputing a value using TMP ever actually useful? | Scott Meyers in "Effective C++" points at the ability to do e.g. matrix operations in the compiler as a reason for implementing some of your algorithms in template classes/functions. But these functions can't operate on arguments that are determined at run-time, obviously--they only work for numbers that are written i... | The main advantage of TMP when it comes to matrix operations is not the ability to precompute the result of a matrix operation, but rather the ability to optimize the generated code for doing the actual matrix computation at runtime. You are correct - it would be pretty unlikely that you'd ever want to precompute a ma... |
4,914,999 | 4,915,437 | Marshaling unmanaged char** to managed string[] | I have a C++ function in a DLL file (it is compiled with the Multi-Byte Character Set option):
_declspec(dllexport) void TestArray(char** OutBuff,int Count,int MaxLength)
{
for(int i=0;i<Count;i++)
{
char buff[25];
_itoa(i,buff,10);
strncpy(OutBuff[i],buff,MaxLength);
}
}
I suppose... | So OutBuff is basically an array of pointers - so you need to create an IntPtr array whose elements are valid pointers - that is IntPtr values that point to valid memory. Like below:
int count = 10;
int maxLen = 25;
IntPtr[] buffer = new IntPtr[count];
for (int i = 0; i < count; i++)
buffer[i] = Marshal.AllocHGlo... |
4,915,032 | 4,915,060 | Problems hiding scrollbars in QWebView | I am trying to hide the scrollbars on a QWebView have tried this:
webView.page()->mainFrame()->setScrollBarPolicy( Qt::Vertical, Qt::ScrollBarAlwaysOff );
webView.page()->mainFrame()->setScrollBarPolicy( Qt::Horizontal, Qt::ScrollBarAlwaysOff );
but Qt is giving me this error:
"invalid use of incomplete type 'struct QW... | Such an error message in Qt usually means that you have to #include <QWebFrame>.
|
4,915,188 | 4,915,265 | Advice on postfix-to-infix parsers | I've come across a proprietary stack-based scripting language that looks like a somewhat simplified version of x86 ASM.
I built a stack-based linear parser for this language in C++ that I hope will produce pseudo-C code to make the language a lot easier to read.
I've encountered at least one serious issue that I feel h... | What you want is symbolic execution. Arrange to have a C++ representation of expressions, such as
class Expression{...};
class StringConstant:public Expression{...};
class FunctionCall:public Expression{...};
Then, make your symbolic stack contain Expression*. When you then arrive at
return foo
compile this to
cout<<... |
4,915,223 | 4,915,476 | OpenGL: can I mix glBindBuffer with glBindBufferARB? | Is glBindBuffer equivelent to glBindBufferARB ?
Are the enums (like GL_ARRAY_BUFFER and GL_ARRAY_BUFFER_ARB) equivilent? Can I use non-_ARB enum in glBindBufferARB?
Can I mix + match glBindBuffer() calls with glBindBufferARB()?
ALSO: if a card supports the _ARB extension, does it always support the core GL function - e... | In general, it is not legal to do that kind of thing, because core functionality and extensions are not exchangeable, even if they have the same name (one notable example is primitive restart).
However, in this particular case, they happen to be exactly the same with the exact same constants, so... although it's not le... |
4,915,666 | 4,918,167 | Dijkstra's algorithm question | In the code below:
#define MAX_VERTICES 260000
#include <fstream>
#include <vector>
#include <queue>
#define endl '\n'
using namespace std;
struct edge {
int dest;
int length;
};
bool operator< (edge e1, edge e2) {
return e1.length > e2.length;
}
int C, P, P0, P1, P2;
vector<edge> edges[MAX_VERTICES];
i... | That line is a way to handle the fact that c++'s priority_queue does not have a decrease_key function.
That is, when you do pq.push(e) and there is already an edge with the same destination in the heap you would prefer to decrease the key of the edge already in the heap. This is not easily done with c++'s priority_que... |
4,915,970 | 4,916,029 | C++ casting to derived and parent structs | I was wondering how to do something in C++. I want to be able to create an instance of this struct
struct ComplexInstruction : simple_instr
{
bool isHead;
bool isTail;
};
that copies all the data from the simple_instr instance. So essentially, I want to do something like this
ComplexInstruction cInstr = instr;... | Create a consctructor in the derived class to initialize from a base class.
class Base
{
int x;
public:
Base(int a) : x(a){}
};
class Derived : public Base
{
public:
Derived(const Base & B) : Base(B){}
};
Note that if you have a derived object of Base, you actually have a base object and you can safely use the... |
4,916,090 | 4,916,116 | How to move files in Qt? | Is there a cross-platform function in Qt that is equivalent to the MoveFile function in Windows and the mv command in Linux?
| Sure, QDir::rename() following the old Unix / POSIX tradition of calling this rename.
Which makes sense if you think of a file with its complete path: the underlying inodes just get assigned a different path/file label.
|
4,916,175 | 6,836,460 | next_permutation problem c++ | While using this code:
for(int i=0; i<line; i++) {
next_permutation(nums, nums+N);
if(DEBUG) {
for(int j=0; j<N; j++) {
cout << nums[j] << " ";
}
}
}
I am getting this output: -1076591092_1_2_4_3_-1076591092_1_3_2_4_
Int his case, line would be 3, and N is 5;
Thanks!
| The problem is related to poor memory management.
|
4,916,193 | 4,916,274 | Creating/writing into a new file in Qt | I am trying to write into a file and if the file doesn't exist create it. I have searched on the internet and nothing worked for me.
My code looks currently like this:
QString filename="Data.txt";
QFile file( filename );
if ( file.open(QIODevice::ReadWrite) )
{
QTextStream stream( &file );
stream << "something"... | Are you sure you're in the right directory?
Opening a file without a full path will open it in the current working directory. In most cases this is not what you want. Try changing the first line to
QString filename="c:\\Data.txt" or
QString filename="c:/Data.txt"
and see if the file is created in c:\
|
4,916,287 | 4,916,400 | How to use union-find, minheap, Kruskal's, and a sort algorithm to create a minimum cost spanning tree? (C++) | I apologize if this question is a bit broad, but I'm having a difficult time trying to understand how I would create a minimum cost spanning tree. This is in C++ if it matters at all.
From what I understand, you would use Kruskal's to select the minimum cost edges for building the spanning tree. My thinking is to read ... | These two structures serve different purposes in the algorithm. Kruskal's algorithm works by adding the cheapest possible edge at each point that doesn't form a cycle. It can be shown using some not particularly complex math that this guarantees that the resulting spanning tree is minimal. The intuition behind why ... |
4,916,485 | 4,916,524 | Determining if std::sort(begin, end) modified the range | What is the most elegant way to determine if a call to std::sort(begin, end) actually modified the range?
Here are my two ideas:
(a) check if already sorted O(n):
if (already_sorted(begin, end)) { return false; }
std::sort(begin, end);
return true;
(b) track changes in comparator (is this safe?):
bool modified = false... | Unless you iterate through the structure from "begin" to "end", you can't know if it is already sorted, so the best you can do it is in O(n).
I would go for the first choice, the already_sorted one.
|
4,916,548 | 4,916,566 | C++: continue after __debugbreak(), or better alternative | I am developing a C++ library with Visual Studio, and there are points in my code where some conditions are checked. If such conditions fails, an exception is thrown. In order to aid my debugging, I have put a
__debugbreak();
statement (like asm int 3;) before the point at which the exception is thrown, which effectiv... | It seems like a much better option than using this particular library function would be to just run the program in a debugger and put breakpoints at the spots in which you want to pause execution for testing. Hardcoding in interrupts to trap into the debugger means that you might accidentally release code to clients t... |
4,916,659 | 4,916,706 | Custom strict weak ordering | Background: I am writing an algorithm that stores a map of objects to an associated attribute that I would like to accumulate. This is a cascading assignment procedure which loads this attribute onto a network using a predefined path through the network. The path is defined as a build-forward path from an origin in the... | You can use the value of the pointers (it appears your map type is map<PathLink const*,double>, right?) to differentiate items with equal costs:
bool pathLinkComp(const PathLink* lhs, const PathLink* rhs) {
return (lhs->cost < rhs->cost)
or (lhs->cost == rhs->cost and std::less<PathLink const*>()(lhs, rhs));
}
|
4,916,738 | 4,916,840 | __fastcall convention within c# | Considering that:
Microsoft Specific
The __fastcall calling convention
specifies that arguments to functions
are to be passed in registers, when
possible. The following list shows the
implementation of this calling
convention.
And that the read/write time in a register is way faster than in a stack, do we h... | Not directly, C# mostly uses what would be equivalent to MSVC++'s __stdcall convention. It can however be "fixed", though in a relatively dirty way (note that example is for __cdecl).
It's probably best this way, though. In a high-level language like C# (heck, even in most C++ programs) this is an optimization best lef... |
4,916,751 | 4,916,824 | How to switch between 2 function sets in C++? | Is there a way, I can switch between 2 similar function sets (C/C++) in an effective way?
To explain better what I mean, lets say I have 2 sets of global functions like:
void a_someCoolFunction();
void a_anotherCoolFunction(int withParameters);
…
void b_someCoolFunction();
void b_anotherCoolFunction(int withParameters... | In C (since it seems you want both C and C++) this is done with pointer to functions.
// Globals. Default to the a_ functions
void(*theCoolFunction)() = a_someCoolFunction;
void(*theOtherCoolFunction)(int) = a_anotherCoolFunction;
// In the code ...
{
...
// use the other functions
theCoolFunction =... |
4,916,859 | 4,916,945 | Faster version of double_price to int_price given the input sequence | In a given trading system, the input prices are of type double. The minimum_price_increment min_price_increment_ is known, and equality is defined as :
inline bool DblPxCompare ( const double & price1, const double & price2 ) const
{
register double tdiff = ( price1 - price2 );
return ( ( tdiff > -half_min_... | I'd be inclined to say no, caching is not going to work better. The reason is that each time you'll need to check that the entries in the cache are appropriate for the conversion at hand, and I think that check is going to negate any performance advantage from saving having to do the conversion in the first place. What... |
4,916,881 | 4,916,902 | sem_open() error: "undefined reference to sem_open()" on linux (Ubuntu 10.10) | So I am getting the error: "undefined reference to sem_open()" even though I have included the <semaphore.h> header. The same thing is happening for all my pthread function calls (mutex, pthread_create, etc). Any thoughts? I am using the following command to compile:
g++ '/home/robin/Desktop/main.cpp' -o '/home/robi... | You need link with pthread lib, using -lpthread option.
|
4,917,060 | 4,918,568 | edit frames from a video source before render c++ | I need you to recommend me a library for c++ to use with visual c++ 2008 to perform an edition ef the frames from a video source before been rendered on the screen. I dont want to perform effects like blur or things like that, I want to change the size en some cases and other stuff.
I have tried with phonon (where I ca... | Try ffmpeg. It's what OpenCV uses to read frames.
FFMPEG includes a simple player -- ffplay. Have a look at its source for an idea of how to use the library.
|
4,917,086 | 4,917,133 | Binary Tree insertion (in order sorted) | I've scoured the internet for help on this problem but I need help. This isn't exactly an ordinary insertion problem for a binary tree, since we don't get to work directly with the tree structure itself. My prof wrote that himself and has given us functions we can use to write functions pertaining to binary trees. A... | Inserting into a zero-element tree is easy:
return tree_make(elt, tree_make(), tree_make());
Inserting into a one-element tree is also easy:
tree_t new_node = tree_make(elt, tree_make(), tree_make());
if(elt < tree_elt(tree))
return tree_make(tree_elt(tree), new_node, tree_right(tree));
else
return tree_make(t... |
4,917,090 | 4,917,103 | c++ forward declaration | #include <iostream>
#include <cstring>
using namespace std;
class Obj;
class Test {
friend class Obj;
public:
Test()
{
}
~Test()
{
}
void foo()
{
//print();
//Obj::print();
//Obj x;
//x.print();
}
};
class Obj {
public:
void p... | You need to define the member function after the definition of Obj:
class Test {
public:
void foo();
};
class Obj {
public:
void print() { }
};
void Test::foo() {
Obj o;
o.print();
}
|
4,917,265 | 4,917,309 | Can I tell if a std::string represents a number using stringstream? | Apparently this is suposed to work in showing if a string is numerical, for example "12.5" == yes, "abc" == no. However I get a no reguardless of the input.
std::stringstream ss("2");
double d; ss >> d;
if(ss.good()) {std::cout<<"number"<<std::endl;}
else {std::cout<<"other"<<std::endl;}
| You should use an istringstream so that it knows it's trying to parse input. Also, just check the result of the extraction directly rather than using good later.
#include <sstream>
#include <iostream>
int main()
{
std::istringstream ss("2");
double d = 0.0;
if(ss >> d) {std::cout<<"number"<<std::endl;}
... |
4,917,440 | 4,917,651 | C++ STL container for template base class | I am attempting to store objects derived from a templated base class in an STL map. However, attempting to insert derived (or indeed base) objects returns:
C2440 'initializing' : cannot convert from 'CBase<T> ' to 'CBase<T>'
I understand using derived classes is one accepted way of making an STL container heterogenou... | The following line:
map<string, CBase<class T>* > m_myMap;
almost certainly does not mean what you think it does. This is equivalent to:
map<string, CBase<T>* > m_myMap;
That is: 'T' is a concrete class, not a template parameter. There is of course no relationship between the classes:
CBase<int>
and
CBase<T>
Henc... |
4,917,488 | 4,917,527 | C++ include header problem | I am new to c/c++, I am confused about followings:
Whether I should put class declarations in its own header file, and actual implementation in another file?
Whether I should put headers like <iostream> in the example.h file or in example.cpp file?
If all the classes need to use <iostream>, and I include a class's hea... |
1.Whether I should put class declarations in its own header file,
and actual implementation in another
file?
You can write the definition of a class, and the definition of the members of the class separately in the same header file if you are manipulating templates. Also, if you want to make your members function... |
4,917,498 | 4,917,508 | Undefined reference to class? | NetBeans interpret weird my code. In main function I have code:
SequenceAlignment align;
align.Alignment( local, seqs, argv[4], matrix)
But NetBeans show:
cpp:91: undefined reference to `SequenceAlignment::Alignment(std::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::vector<std::basic_string<c... | This is a linker error indicating that the linker can't find an implementation for SequenceAlignment::Alignment. Check to see that you indeed have an implementation of this function and that the code containing that implementation is indeed being compiled and linked.
|
4,917,506 | 4,917,526 | Will there be a class redefinition if a class is included via two include files indirectly? | if I include class definition file classA.h in classB.h and classC.h, then if classD.h includes both classB.h and classC.h, will there be a class redefinition?
| Provided that you correctly use include guards, this shouldn't be a problem. In particular, if you ensure that #include-ing the same file twice is idempotent (#include-ing the same header twice is the same as #include-ing it once), then this won't cause a problem. When classD.h includes classB.h, it will include clas... |
4,917,521 | 4,917,550 | How to connect Database in C++? What database to use? | What are the suitable database for Visual Studio C++?
How could I connect a database to C++?
| Your choice of a database is fully dependent on your requirements. SQLite offers a nice and simple interface.
|
4,917,560 | 4,917,565 | Using struct as SSE vector type in gcc? | Is it possible in GCC to use a struct or class as a vector type for SSE instructions?
something like:
typedef struct vfloat __attribute__((vector_size(16))) {
float x,y,z,w;
} vfloat;
Rather than the canonical:
typedef float v4sf __attribute__ ((vector_size(16)));
union vfloat {
v4sf v;
float f[4];
};
Wo... | Could you make a union like the one you posted but with your struct instead of float f[4]; as the second member? That would give you the behavior you want.
|
4,917,584 | 4,917,598 | Checking the size of a tr1 array at compile time | I just found out that boost::array::static_size isn't part of tr1::array, or at least it's not in my implementation (GCC 4.2.1) and I can't find it in any tr1 documentation.
Is there another way to perform a compile-time assertion on the number of elements in a tr1 array?
e.g. The following works with a boost array bu... | TR1 itself says that std::tuple_size<array<T, N> >::value returns N, the size of the array.
|
4,917,743 | 4,918,120 | How do library dependancies work when linking? | I have a library libmya.so and a library libmyb.so. The functions in libmyb.so depend on functions in libmya.so. Also I have an executable myexe which depends on libmyb.so. When I make these libraries, in which rules should I put the -l options?
Should it be 1):
libmya.so: $(OBJ_FILES)
$(CPP) $(LDFLAGS) -o $@ $^
l... | I would go with option 1 (though option 2 works, I wouldn't recommend it since then anybody who links the exe needs to remember all the transitive libraries required).
However, this advice is only for making an so file, as you do above. so files (shared objects) are "intelligent" libraries, much like executables, excep... |
4,917,907 | 4,918,081 | expected primary-expression before 'else' | I have an emergency here. This homework is due tomorrow for my CP 1 class. We have to make a simple dice game. If you get doubles of the same number, then good things happen. Here is the function:
void Doubles(); //prototype for the function Doubles()
//pre: n/a
//post: Plays a simple dice game with the user
voi... | You are missing the brace, as has been pointed out, but the flaw comes from not being able to look at the code indentation correctly and not being able to clearly see the error. The indentation on the else if's is indented one more than the if, and if this were not the case, you would quickly see the missing brace, bu... |
4,918,144 | 4,918,236 | How can I tell whether a pointer points to an instance of a derived type? | I have a struct simple_instr that I can't modify. I create a derived type from it as so:
struct ComplexInstruction : simple_instr
{
ComplexInstruction(const simple_instr& simple) : simple_instr(simple)
{
}
bool isHead;
bool isTail;
bool isPreHeader;
};
I want to be able to tell whether an ... | I can think of two approaches. Firstly, have each constructor for a complex instruction store its address in a set, and check this before casting. Secondly, if you can define youir own allocator for all the objects, and store the necessary tag field before the object. I've seen both approaches used very sucessfully in ... |
4,918,186 | 4,918,405 | Changing the Label images in Qt | How to change the label image in Qt when the application is running. I am able to change the image of label by adding an icon resource file to that in the code it self. But I want that user can browse the image & can set it in the label. It can be changed by user. So which class I have to use to make it work?
Thanks.
| Try setPixmap
You can create a pixmap from a file.
|
4,918,329 | 4,918,357 | how to create a process which is not visible in task manager or services list |
Possible Duplicate:
Hide a C# program from the task manager?
I need to create an enterprise level activity monitor process in which the user should not be able to kill using the Task Manager or some other method. Perhaps it should be a hidden process. Is this possible? Are there any workarounds? I prefer to use C# t... | Related:
Hide a C# program from the task manager?
https://stackoverflow.com/questions/759466/is-it-possible-to-hide-console-c-application-from-task-manager
Short answer is: no, you can't (legally) hide it from Task manager, unless you wrap it with a Windows service. There are various ways of preventing your application... |
4,918,338 | 4,986,927 | Linking to framework with cmake on Mac OS X | I'm attempting to link a program against ogre and a few other libraries on OS X using cmake, but I keep getting this error:
ld: warning: directory '/Library/Frameworks/SDL.framework/Debug' following -L not found
ld: warning: directory '-framework Cocoa/Debug' following -L not found
ld: warning: directory '-framework C... | First, you should note that ${APPLE} "does not imply that the system is Mac OS X, only that APPLE is #defined in C/C++ header files." Use IF(${CMAKE_SYSTEM_NAME} MATCHES "Darwin") to check for OS X.
I don't have your build environment to test the following suggestions, but give them a try:
Line 309 and 321 have a typo.... |
4,918,386 | 4,918,410 | convert uint64 to uint32 | I have a uint64 variable ...but the function in which I want to pass it only accepts uint32.
I tried using static unsigned int ToUInt32(uint64 variable); reference MSDN, but it gives an error that precision lost.
Is there any way to convert uint64 to uint32 without losing any data?
| Well think about what you are trying to do. You are taking a number which will potentially take up to 64bits and then cutting in half.
Of course you are going to lose data in this instance.
If you are sure that the number being given is not going to be larger than uint32 then you can try this
uint64 largeNumber = 98765... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.