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 |
|---|---|---|---|---|
2,189,245 | 2,189,263 | How can I get the username of the person executing my program? | How can I get the username of the process owner (the user who is executing my program) in C++?
| Windows
GetUserName()
Example:
char user_name[UNLEN+1];
DWORD user_name_size = sizeof(user_name);
if (GetUserName(user_name, &user_name_size))
cout << "Your user name is: " << user_name << endl;
else
/* Handle error */
Linux
Look at getpwuid:
The getpwuid() function shall search
the user database for an entry with a
matching uid.
The getpwuid() function shall return a
pointer to a struct passwd
The struct passwd will contain char *pw_name.
Use getuid to get the user id.
|
2,189,279 | 2,189,632 | implicit promotion to avoid overflow in std::partial_sum | This code suffers from overflow because the type of intermediate results does not depend on the destination type:
vector< uint8_t > increments;
…
vector< uint32_t > increasing( increments.size() );
partial_sum( increments.begin(), increments.end(), increasing.begin() );
However, so does this (GCC 4.2):
partial_sum( increments.begin(), increments.end(), increasing.begin(),
plus< uint32_t >() );
Shouldn't plus< uint32_t > promote its operands and avoid the overflow?
Edit: I'm too SO-addicted. After a short break, I sat back down and checked the implementation. It does this:
/* input_iterator::value_type */ __value = __binary_op(__value, *__first);
*++__result = __value;
I don't think that's compliant, so I'll check the latest version and maybe file a bug… and here we go: http://gcc.gnu.org/bugzilla/show_bug.cgi?id=42943
| According to http://www.open-std.org/jtc1/sc22/wg21/docs/lwg-active.html#539, partial_sum has been completely redefined since n3000 (the latest release):
Effects: Let VT be InputIterator's
value type. For a nonempty range,
initializes an accumulator acc of type
VT with *first and performs *result =
acc. For every iterator i in [first +
1, last) in order, acc is then
modified by acc = acc + *i or acc =
binary_op(acc, *i) and is assigned to
*(result + (i - first)).
and
The 'widening' behaviour can then be
obtained by writing a custom proxy
iterator, which is somewhat involved.
I really can't see the advantage of doing things this way. Reading the defect report, I don't see any justification besides
The intent of the algorithms is to perform their calculations using the
type of the input iterator.
Arrrgh.
Edit: I went ahead and implemented a widening input iterator. Works as advertised.
template< class Base, class Wider >
struct widen_iter : iterator< input_iterator_tag, Wider > {
Base b;
widen_iter( Base const &inb = Base() ) : b( inb ) {}
Wider operator*() const { return Wider( *b ); }
Wider const *operator->() const { Wider t( *b ), *ta = &t; return ta; }
widen_iter &operator++() { ++ b; return *this; }
widen_iter operator++(int) { widen_iter t = *this; ++ b; return t; }
bool operator==( widen_iter const &r ) const { return b == r.b; }
bool operator!=( widen_iter const &r ) const { return b != r.b; }
};
template< class Wider, class Base >
widen_iter< Base, Wider >
widener( Base b ) { return widen_iter< Base, Wider >( b ); }
Would be a lot shorter if there were a generic filter-by-functor input iterator.
|
2,189,304 | 2,189,375 | How to check open processes in C++? | In Windows I would like the C++ command or reference that would get the "tasklist" in C++ and output it to a buffer?
| Use EnumProcesses() to get the process identifiers, use OpenProcess() to get their handles and get the information you need via the usual process functions.
|
2,189,430 | 2,189,444 | How to port forward in C++? | I have a sockets program that requires port 1002 to be open and I wanna know how to port forward in C++ on windows so i may use this port freely?
| Port forwarding is done upstream of the client system, typically on the router.
I believe some applications use Universal Plug and Play to communicate with the upstream router to open a port publicly but you'll have to do a lot of research to see how it's done: I haven't the slightest.
|
2,189,577 | 2,189,680 | Simple File I/O in C++ - Never Exits This Loop? | I'm a programming student in my second OOP class, my first class was taught in C# and this class is taught in C++. To get our feet wet in C++, our professor has asked us to write a rather large program with File I/O. The problem is, I have a small part of my program that is not working, at least, not for me. The project requires that we code a loop to test if the file could be opened successfully, and the loop I have written doesn't seem to be working.
I don't get any compiler errors, but when I enter in the path to the file, either relative or absolute, it says it's invalid. I have a feeling it has something to do with my conditions in my do-while loop, but I can't pinpoint it.
I don't mean to bring my homework to SO, but I've been scratching my head for two+ hours, and I can't seem to figure this out.
Would you mind helping me fix my loop? And maybe explain what it is that I'm doing wrong? I want to learn.
Thanks!
Code:
Rainfall rData;
ifstream actualReader;
ifstream averageReader;
string aRDataLoc;
char response = 'a';
const int KILL_VALUE = 1;
double actualRainfallD;
double actualRainfallPassedArray[ARRAY_CAPACITY];
double averageRainfallPassedArray[ARRAY_CAPACITY];
int i = 0;
do
{
actualReader.clear();
cout << "\nPlease enter in the path to the file containing the actual rainfall data." << endl;
cout << "Path to file: ";
cin >> aRDataLoc;
actualReader.open(aRDataLoc.c_str());
if (!actualReader.is_open())
{
cout << "Invalid file path! Would you like to enter in a new file path?(y/n): ";
cin >> response;
if (response == 'n') { exit(KILL_VALUE); }
}
}while (!actualReader.is_open() && response == 'y');
| I don't know what input you are giving to cin, but be aware that cin will stop at the first whitespace character it encounters. For example, if you give as input the following:
C:\Program Files\directory
then aRDataLog would have the value C:\Program .
In order to read the whole line, you could use getline.
Check also this post.
|
2,189,616 | 2,189,620 | Should I use a function in a situation where it would be called an extreme number of times? | I have a section of my program that contains a large amount of math with some rather long equations. Its long and unsightly and I wish to replace it with a function. However, chunk of code is used an extreme number of times in my code and also requires a lot of variables to be initialized.
If I'm worried about speed, is the cost of calling the function and initializing the variables negligible here or should i stick to directly coding it in each time?
Thanks,
-Faken
| Most compilers are smart about inlining reasonably small functions to avoid the overhead of a function call. For functions big enough that the compiler won't inline them, the overhead for the call is probably a very small fraction of the total execution time.
Check your compiler documentation to understand it's specific approach. Some older compilers required or could benefit from hints that a function is a candidate for inlining.
Either way, stick with functions and keep your code clean.
|
2,189,723 | 2,189,763 | Double to int conversion behind the scene? | I am just curious to know what happens behind the scene to convert a double to int, say int(5666.1) ? Is that going to be more expensive than a static_cast of a child class to parent? Since the representation of the int and double are fundamentally different is there going to be temporaries created during the process and expensive too.
| Any CPU with native floating point will have an instruction to convert floating-point to integer data. That operation can take from a few cycles to many. Usually there are separate CPU registers for FP and integers, so you also have to subsequently move the integer to an integer register before you can use it. That may be another operation, possibly expensive. See your processor manual.
PowerPC notably does not include an instruction to move an integer in an FP register to an integer register. There has to be a store from FP to memory and load to integer. You could therefore say that a temporary variable is created.
In the case of no hardware FP support, the number has to be decoded. IEEE FP format is:
sign | exponent + bias | mantissa
To convert, you have to do something like
// Single-precision format values:
int const mantissa_bits = 23; // 52 for double.
int const exponent_bits = 8; // 11 for double.
int const exponent_bias = 127; // 1023 for double.
std::int32_t ieee;
std::memcpy( & ieee, & float_value, sizeof (std::int32_t) );
std::int32_t mantissa = ieee & (1 << mantissa_bits)-1 | 1 << mantissa_bits;
int exponent = ( ieee >> mantissa_bits & (1 << exponent_bits)-1 )
- ( exponent_bias + mantissa_bits );
if ( exponent <= -32 ) {
mantissa = 0;
} else if ( exponent < 0 ) {
mantissa >>= - exponent;
} else if ( exponent + mantissa_bits + 1 >= 32 ) {
overflow();
} else {
mantissa <<= exponent;
}
if ( ieee < 0 ) mantissa = - mantissa;
return mantissa;
I.e., a few bit unpacking instructions and a shift.
|
2,189,780 | 2,189,807 | Can all keys be represented as a single char in c++? | I've searched around and I can't seem to find a way to represent arrow keys or the escape key as single char in c++. Is this even possible? I would expect that it would be similar to \t or \n for tab and new line respectively. Whenever I search for escaped characters, there's only ever a list of five or six well known characters.
| The short answer is no.
The long answer is that there are a number of control characters in the standard ANSI character set (from decimal 1 to decimal 31, inclusive), among which are the control codes for linefeed, carriage return, end-of-file, and so on. A few are commonly interpreted as arrows and the escape key, but only for compatibility with terminals.
Standard PC keyboards send a 2- or 3-byte control code that represents the key that was pressed, what state it's in, which control/alt/shift key is pressed, and a few other things. You'll want to look up "key codes" to see how to handle them. Handling them differs between operating systems and the base libraries you use, and their meaning differs based on the operating system's configured keyboard layout (which may include characters not found in the ANSI character set).
|
2,189,883 | 2,189,895 | C++ STL Memory Allocator Compile Error | I'm writing a C++ custom allocator for use with STL. When I put the following code in the class definition, it compiles:
#include "MyAlloc.hpp"
#if 1
template <typename T>
typename MyAlloc<T>::pointer
MyAlloc<T>::allocate(size_type n, MyAlloc<void>::const_pointer p) {
void *ptr = getMemory(n*sizeof(T));
typename MyAlloc<T>::pointer tptr = static_cast<MyAlloc<T>::pointer>(ptr);
return tptr;
}
#endif
But when I put it in a separate .cpp file, I get the following error. What am I doing wrong? The error is on the static_cast line.
g++ -c MyAlloc.cpp
MyAlloc.cpp: In member function ‘typename MyAlloc<T>::pointer MyAlloc<T>::allocate(size_t, const void*)’:
MyAlloc.cpp:9: error: expected type-specifier
MyAlloc.cpp:9: error: expected `>'
MyAlloc.cpp:9: error: expected `('
MyAlloc.cpp:9: error: expected `)' before ‘;’ token
make: *** [MyAlloc.o] Error 1
PT
| Templates must always be defined within a translation unit. In order to use the template function, the definition of the template needs to go in the header file, not a separate .cpp file.
|
2,190,026 | 2,190,047 | Where is pointer metadata stored? | Could be that I am overlooking something obvious, but where is pointer metadata stored? For instance if I have a 32-bit int pointer ptr and I execute ptr++ it knows to advance 4 bytes in memory. However, if I have a 64-bit int pointer it knows to advance 8 bytes. So who keeps track of what type of pointer ptr is and where is it stored? For simplicity you can limit this to C++.
| It isn't stored anywhere, per-se. The compiler looks at the type of the ptr and turns the ++ operation into an increment of the correct number of bytes.
|
2,190,080 | 2,190,145 | Using boost::random and getting same sequence of numbers | I have the following code:
Class B {
void generator()
{
// creating random number generator
boost::mt19937 randgen(static_cast<unsigned int>(std::time(0)));
boost::normal_distribution<float> noise(0,1);
boost::variate_generator<boost::mt19937,
boost::normal_distribution<float> > nD(randgen, noise);
for (int i = 0; i < 100; i++)
{
value = nD();
// graph each value
}
}
};
Class A {
void someFunction()
{
for(int i = 1; i <=3; i++)
{
std::shared_ptr<B> b;
b.reset(new B());
b->generator();
}
}
};
I wish to execute the above code multiple times in rapid succession to produce multiple graphs. I have also reviewed this stackoverflow question which is similar but the caveat states that when time(0) is used and the member function is called in rapid succession then you will still likely get the same sequence of numbers.
How might I overcome this problem?
EDIT: I've tried making randgen static in Class B, also tried making it a global variable in Class A, but each time the 3 graphs are still the same. I've also tried seeding from the GetSystemTime milliseconds. I must be missing something.
| One way would be to not reseed the random number generator every time you execute your code.
Create the generator and seed it once, then just continue to use it.
That's assuming you're calling that code multiple times within the same run. If you're doing multiple runs (but still within the same second), you can use another differing property such as the process ID to change the seed.
Alternatively, you can go platform-dependent, using either the Windows GetSystemTime() returning a SYSTEMTIME structure with one of its elements being milliseconds, or the Linux getTimeOfDay returning number of microseconds since the epoch.
Windows:
#include <windows.h>
SYSTEMTIME st;
GetSystemTime (&st);
// Use st.wSecond * 100 + st.wMillisecs to seed (0 thru 59999).
Linux:
#include <sys/time.h>
struct timeval tv;
gettimeofday (&tv, NULL);
// Use tv.tv_sec * 100 + (tv.tv_usec / 1000) to seed (0 thru 59999).
|
2,190,231 | 2,190,552 | Looking for a C or C++ library providing a functionality similar to Google Go's channels | ...for use in a multithreaded network server.
I want to pass data around between multiple threads. Currently I'm using sockets, with the master thread blocking on select() and workers blocking on recv(), though I feel there probably are more advanced or prepackaged ways of handling this task in C++.
| I would have worker threads waiting in a thread pool.
Then the master waiting on select (for both reads and writes).
As data comes the master adds jobs to the thread pool. As each job is added a thread wakes up executes the job and returns to the pool. This way you are not blocking threads waiting on specific ports with recv() and a fixed set of child threads can handle all incoming traffic.
Currentl libs that support this functionality in ready made objects:
ACE: http://www.cs.wustl.edu/~schmidt/ACE.html
Poco: http://pocoproject.org/
|
2,190,349 | 2,191,360 | None in boost.python | I am trying to translate the following code
d = {}
d[0] = None
into C++ with boost.python
boost::python::dict d;
d[0] = ?None
How can I get a None object in boost.python?
| There is no constructor of boost::python::object that takes a PyObject* (from my understanding, a ctor like that would invalidate the whole idea if mapping Python types to C++ types anyway, because the PyObject* could be anything). According to the documentation:
object();
Effects: Constructs an object managing a reference to the Python None object.
|
2,190,416 | 2,190,971 | What does C4250 VC++ warning mean? | What does C4250 Visual C+ warning mean in practical terms? I've read the linked MSDN page, but I still don't get what the problem is.
What does the compiler warn me about and what problems could arise if I ignore the warning?
| The warning is pointing out that if any weak class operations depend on vbc virtual operations that are implemented in dominant, then those operations might change behavior due to the fact that they are bundled in a diamond inheritance hierarchy.
struct base {
virtual int number() { return 0; }
};
struct weak : public virtual base {
void print() { // seems to only depend on base, but depends on dominant
std::cout << number() << std::endl;
}
};
struct dominant : public virtual base {
int number() { return 5; }
};
struct derived : public weak, public dominant {}
int main() {
weak w; w.print(); // 0
derived d; d.print(); // 5
}
That is the behavior that the standard specifies, but it might be surprising for the programmer at times, the weak::print operation behavior has changed not because of an overridden method above or below in the hierarchy, but by a sibling class in the inheritance hierarchy, when called from derived. Note that it makes perfect sense from the derived point of view, it is calling an operation that depends on a virtual method implemented in dominant.
|
2,190,444 | 2,190,454 | Operators in C/C++/Java | Consider the following fragment:
int a,b;
a = 1;
b = 2;
c = a++++b; // does not work!! Compilation error.
c = a++*+b; // works !!
Help me understand this behaviour.
| c = a++++b;
is treated as:
c = ((a++)++)b;
which is incorrect as you are trying to increment non-lvalue.
and
c = a++*+b;
is treated as:
c = (a++)*(+b);
The cause for this behaviour is: The C language lexical analyzer is greedy.
In case 1: After the token 'a' (identifier) the lexer sees +, followed by another +, so it consumes both (as the increment operator) as part of same token. It does not make the 3rd + part of the same token as +++ is not a valid token. Similarly it groups the next two + into ++ token making it effectively same as:
c = ((a++)++)b;
which is not correct as a++ will not return a lvalue, hence you can't apply a ++ on it. Something similar to saying 5++;
But in case2: the first pair of ++ will be grouped together (as increment operator). Next the * alone will be a token as you cannot combine it with a + as *+ is not a valid token. Finally the + will a token (as unary +) effectively making your statement as:
c = (a++)*(+b);
You can override this greedy behaviour of the lexer by making use of parenthesis or whitespaces as follows:
c = a++ + +b;
c = a++ * +b;
|
2,190,455 | 2,190,629 | Why we can't implement polymorphism in C++ without base class pointer or reference? |
First of all have a look at the following code (in this code shape is the base class and line is the derived class)
void drawshapes(shape sarray[],int size)
{
for(int i=0;i< size; i++)
sarray[i].draw();
}
main()
{
line larray[10];
larray[0]=line(p1,p2);//assuming that we have a point class
larray[1]=line(p2,p3);
..........
drawshapes(larray,10);
}
when we compile this program the draw method of shape would be called at first then program terminates. why it terminates ? why we can not implement polymorphism without base class pointer or reference what is the technical reason for this? what compiler will do if we are trying to implement polymorphism with the array of objects ? please explain in much understandable manner with examples. I will be very thankful.
| You are asking a question and providing a code example that fails but for a different reason. From the wording of your question:
Why are references/pointers required for polymorphism?
struct base {
virtual void f();
};
struct derived : public base {
virtual void f();
};
void call1( base b ) {
b.f(); // base::f
}
void call2( base &b ) {
b.f(); // derived::f
}
int main() {
derived d;
call1(d);
call2(d);
}
When you use pass-by-value semantics (or store derived elements in a base container) you are creating copies of type base of the elements of type derived. That is called slicing, as it resembles the fact that you have a derived object and you slice/cut only the base subobject from it. In the example, call1 does not work from the object d in main, but rather with a temporary of type base, and base::f is called.
In the call2 method you are passing a reference to a base object. When the compiler sees call2(d) in main it will create a reference to the base subobject in d and pass it to the function. The function performs the operation on a reference of type base that points to an object of type derived, and will call derived::f. The same happens with pointers, when you get a base * into a derived object, the object is still derived.
Why can I not pass a container of derived pointers to a function taking a container of base pointers?
_Clearly if derived are base, a container of derived is a container of base.
No. Containers of derived are not containers of base. That would break the type system. The simplest example of using a container of derived as container of base objects breaking the type system is below.
void f( std::vector<base*> & v )
{
v.push_back( new base );
v.push_back( new another_derived );
}
int main() {
std::vector<derived*> v;
f( v ); // error!!!
}
If the line marked with error was allowed by the language, then it would allow the application to insert elements that are not of type derived* into the container, and that would mean lots of trouble...
But the question was about containers of value types...
When you have containers of value types, the elements get copied into the container. Inserting an element of type derived into a container of type base will make a copy of the subobject of type base within the derived object. That is the same slicing than above. Besides that being a language restriction, it is there for a good reason, when you have a container of base objects, you have space to hold just base elements. You cannot store bigger objects into the same container. Else the compiler would not even know how much space to reserve for each element (what if we later extend with an even-bigger type?).
In other languages it may seem as this is actually allowed (Java), but it is not. The only change is in the syntax. When you have String array[] in Java you are actually writting the equivalent of string *array[] in C++. All non-primitive types are references in the language, and the fact that you do not add the * in the syntax does not mean that the container holds instances of String, containers hold references into Strings, that are more related to c++ pointers than c++ references.
|
2,190,463 | 2,190,489 | An interview question | Given a linked list of T size , select first 2n nodes and delete first n nodes from them; Then do it for the next 2n nodes and so on...
For example-
Let's consider a linked list of size 7:
`1->2->3->4->5->6->7`
If n = 2, the desired output is :
`1->2->5->6->7`
I didn't understand what this problem is actually indicating.Could somebody help me to understand the problem ?
EDIT : Adding C and C++ tags so that this may reach to more eye balls, and of-course those are only two languages allowed in the interview itself.
| That actually looks like it should say:
Given a linked list of T size , select first 2n nodes and delete last n nodes from them; Then do it for the next 2n nodes and so on...
or:
Given a linked list of T size , select first 2n nodes and keep first n nodes from them; Then do it for the next 2n nodes and so on...
That would mean select 1,2,3,4 then delete 3,4 (or keep 1,2 which is the same thing). Then select 5,6,7,8, not possible so stop.
|
2,190,504 | 2,190,512 | Difference between intellisense and compiler in VS.NET C++ 2010 | Is the following legal C++ code:
class C
{
static public int x;
};
It compiles OK in Visual Studio 2008 C++ and Visual Studio 2010 C++ (beta 2). But the static member x does not end up being public.
In Visual Studio 2010 beta 2 the experience is even stranger. Intellisense reports an error "expected an identifier", but the compiler does not. Visual Studio 2008 does not give any error.
So the questions are:
Is this legal C++ code?
What does it mean?
| This is not legal C++. It is a legal C#, so that's why MS IDE bugged out.
Correct:
public: static int x;
|
2,190,695 | 2,190,726 | Problem passing vector of templated states to constructor | For those who are following the saga, I am still trying to define Finite State Machine, states & events in the "proper" C++ way, with templates.
What's wrong with this code?
template <typename StateTypeEnum, typename EventTypeEnum>
class Fsm
{
public:
Fsm(E_subSystems subSystem,
uint8_t instance,
const char * const fsmName,
const std::vector<State<StateTypeEnum, EventTypeEnum> >& states)
{}
where
template <typename StateTypeEnum, typename EventTypeEnum>
class State
{
public:
State(INPUT E_subSystems subSystem,
StateTypeEnum stateId,
const char * const stateName,
const std::map<Event<EventTypeEnum>, EventHandlerFunction>& events)
{}
The only error message is
no matching function for call to "State<E_callControlStates, E_callControEvents>::State()" fsm.h line 98 C/C++ Problem
It looks like the error message refers to a non-existent default constructor for state, but why?
E_callControlStates, E_callControEvents were the template parameters for declaring an object of Fsm (with no errors).
Obviously, I am overlooking something & making a st00pid n00b mistake, but what? Thanks in advance
My bad. Of course it had nothing to do with the code that I was looking at - but then it rarely does, does it?
The class Fsm declared
private: State<StateTypeEnum, EventTypeEnum> _currentState;
when it should have been
private: State<StateTypeEnum, EventTypeEnum> *_currentState;
Sorry for misleading you, folks, and thanks for deducing the problem, despite that.
| The problem is not in the code you present, but most probably a member of type State that is not being initialized in the initialization list of some constructor, forcing the compiler to default initialize it, and the compiler is not finding the appropriate constructor.
I can only assume that line 98 is in the Fsm constructor and that Fsm has a member of type State<...>.
|
2,190,919 | 2,190,981 | Mixing extern and const | Can I mix extern and const, as extern const? If yes, does the const qualifier impose it's reign only within the scope it's declared in or should it exactly match the declaration of the translational unit it's declared in? I.e. can I declare say extern const int i; even when the actual i is not a const and vice versa?
|
Yes, you can use them together.
And yes, it should exactly match the declaration in the translation unit it's actually declared in. Unless of course you are participating in the Underhanded C Programming Contest :-)
The usual pattern is:
file.h: extern const int a_global_var;
file.c: #include "file.h" const int a_global_var = /* some const expression */;
Edit: Incorporated legends2k's comment. Thanks.
|
2,190,993 | 2,191,072 | Creating an ATL COM object that implements a specific interface | I need to implement a simple ATL COM object that implements a specific interface for which I have been given both a .tlb file and a .idl file. The interface is very simple and only consists of a single method. I have created many ATL objects in the past but never one that has to implement a specific interface. What do I need to achieve this? I'm assuming that I somehow need to reference the interface's IDL or TLB in my new objects IDL somewhere?
Any pointers are welcome.
| It's much more automatic than the other answers here are suggesting. All the boilerplate code is written for you by Visual Studio.
You're lucky you have the .idl, it's by far the most conveninent, I think.
You could paste the contents of the .idl file into your ATL COM project's existing .idl file, which would give you access to the declarations in it. For example, something like this could be pasted into an IDL file:
[
object,
uuid(ecaac0b8-08e6-45e8-a075-c6349bc2d0ac),
dual,
nonextensible,
helpstring("IJim Interface"),
pointer_default(unique)
]
interface IJim : IDispatch
{
[id(1), helpstring("method SpliceMainbrace")] HRESULT SpliceMainbrace(BSTR* avast);
};
Then in Class View, right click your class and choose Add | Implement Interface.
Notice that in this dialog, you can actually browse for a .tlb file, but I think it's better to have plain-text source for these things, for version control and the like.
Pick IJim from the list, press the > button to add it to the list to be implemented. Press Finish.
Visual Studio will add this to your class (along with a bunch of other crap to make it work):
// IJim Methods
public:
STDMETHOD(SpliceMainbrace)(BSTR * avast)
{
// Add your function implementation here.
return E_NOTIMPL;
}
|
2,191,076 | 2,191,125 | Explicitly passing a const object to an constructor which takes const reference to a polymorphic class | I got into a problem with my classes, passing a const object (polymorphic structure) to an explicit constructor which takes a const reference to the base class of that polymorphic structure.
Here is the sample (this is not from my code, it is for explanation here)
class Base
{
...
}
class Derived:public Base
{
...
}
class Problem
{
Problem(const Base&);
...
}
void myFunction(const Problem& problem)
{
...
}
int main()
{
//explicit constructor with non const object
Derived d;
Problem no1(d); //this is working fine
myFunction(no1);
//implicit constructor with const object
Problem no2=Derived(); //this is working fine, debugged and everything called fine
myFunction(no2); //is working fine
//explicit constructor with const object NOT WORKING
Problem no3(Derived()); //debugger jumps over this line (no compiler error here)
myFunction(no3); //this line is NOT COMPILING at all it says that:
//no matching function for call to myFunction(Problem (&)(Derived))
//note: candidates are: void MyFunction(const Problem&)
}
It seems that it is working fine with the second version (explicit constructor call for Problem) only if i explicitly cast the Derived object to its base class Base it like:
Problem(*(Base*)&Derived);
I do not realize the difference between calling impicitly and explicitly the constructor of the Problem class.
Thank you!
| The problem is you aren't declaring an object, but a function:
Problem no3(Derived());
// equivalent to:
Problem no3(Derived); // with parameter name omitted
Use:
Problem no3((Derived()));
// extra parens prevent function-declaration interpretation
// which is otherwise required by the standard (so that the code isn't ambiguous)
This is a quirk of C's declaration syntax inherited by C++.
More examples:
void f(int(a)); /* same as: */ void f(int a);
void g() {
void function(int); // declare function
void function(int()); // we can declare it again
void function(int=42); // add default value
function(); // calls ::function(42) ('function' in the global scope)
}
// 'function' not available here (not declared)
void function(int) {} // definition for declarations inside g above
|
2,191,146 | 2,191,170 | XML usage for c++ application | I have a couple of questions about XML.
Can XML be used for normal c++ application instead of using a text file ?
If so, does this method have advantages?
and finally, how can I use XML to store data? what tools are needed?
Regards.
| You can use XML for storing information - it's less Human readable than a text file, but can be more easily communicated with other systems and coding languages.
If all you need is a few text/numeric properties, stick to a property file.
If you need a mix of configuration options, and you want to use validation (can be accomplished using XML schema), automatic modification (e.g. XSL transformations) or communicate it easily with Web Services, than XML is useful.
If you want to store binary data, XML is probably not that answer. Though you can store it in a filesystem and use the XML for the metadata (i.e. where each file is located).
Take a look at Apache Xerces-C for C++ XML code - http://xerces.apache.org/xerces-c/
|
2,191,168 | 2,193,571 | Mac OS. How to create image from PNG data? | I have an array of data that represents PNG:
unsigned short systemFontTexture[] = {
...
0x5089,0x474E,0x0A0D,0x5089,0x474E,0x0A0D,0x5089,
0x474E,0x0A0D,0x5089,0x474E,0x474E,0x0A0D,0x5089,
0x474E,0x0A0D,0x5089,0x474E,0x474E,0x0A0D,0x5089,
...
}
Can I create PNG file using this data?
If yes, then HOW?
| Create a data provider to serve up the data, and then create an image with the data provider.
|
2,191,238 | 2,191,267 | How to allow your data structure to take in objects of any class - C++ | How do I do that? Like you know in Java, you can use an ArrayList and it will take any object as long as you cast it down to whatever it is when you're retrieving the object.
Even better, you can specify what class of objects that ArrayList would store by doing...
new ArrayList()< whateverObject >
I've implemented a linked list data structure in C++ and I'd like to know how I can allow it to do this...
At the moment, I'm just using...
typedef whateverObject ItemType
at the start of my header file for my linked list and then manipulating "ItemType" throughout the implementation of the linked list. So every time I want to change the type, e.g. instead of using the list for storing strings, I want to store an int, I'll have to change the typedef in my linked list's header but I want to be able to simply use it for any object so...
How?!
Thanks.
| Templates are the answer to your question.
Define your linked list as follows :
template<typename ItemType>
class ArrayList
{
// What's inside your class definition does not need to be changed
// Include your method definitions here and you'll be fine
};
The type to use is then ArrayList<WhateverObject>.
|
2,191,572 | 2,192,290 | Iterator for custom container with derived classes | I've a custom container which is implemented in two different ways, but with a single interface. some thing like this.
class Vector
{
virtual Iterator begin() = 0;
virtual Iterator end () = 0 ;
... // some more functions.
} ;
class VectorImplA : public Vector
{
Iterator begin() { return m_data.begin() ; }
Iterator end () { return m_data.end() ; }
private:
SomeFloatContainer m_data ;
} ;
class VectorImplB : public Vector
{
Iterator begin() { return m_data.end() ; }
Iterator end() ; { return m_data.end() ; }
private:
std::vector <float> m_data ;
} ;
What I need is a unified interface to Iterator, so that I'can use it in base class. Any Ideas ?
| I've run into exactly this problem myself before. While there are ways to solve your problem, you most likely should let go of the idea of a vector base class. What you probably should do instead, is mimic the way the c++ STL container are designed.
The STL consists of concepts rather than base classes. An std::vector is a model of the Container concept, but does not inherit from a Container base class. A concept is a set of requirements that any model of the concept should adhere to. See this page for the requirements for Container for example.
The requirements for Container state for example that you should typedef the type of the contents of the container as value_type, and typedef iterators as iterator and const_iterator. Furthermore, you should define begin() and end() functions returning iterators, and so on.
You'll then need to change functions that operate on your Vector base class to instead operate on any class that adheres to the requirements imposed by the concept. This can be done by making the functions templated. You don't necessarily have to stick to the concepts used by the STL, you might as well cook up your own. Sticking to the concepts as they are defined in the STL has the additional benefit that the STL algorithms (std::sort for example) can operate on your containers.
Quick example:
class VectorImplA
{
public:
typedef VectorImplAIterator iterator;
iterator begin();
iterator end();
};
class VectorImplB
{
public:
typedef VectorImplBIterator iterator;
iterator begin();
iterator end();
};
template <typename VectorConcept>
void doSomeOperations(VectorConcept &container)
{
VectorConcept::iterator it;
it = container.begin();
}
int main()
{
VectorImplA vecA;
VectorImplB vecB;
doSomeOperations(vecA); // Compiles!
doSomeOperations(vecB); // Compiles as well!
}
As a bonus, to answer the original question, consider the following design (I wouldn't go this way though!):
struct IteratorBase
{
virtual void next() = 0;
};
struct IteratorA : IteratorBase
{
void next() {};
};
struct IteratorB : IteratorBase
{
void next() {};
};
class Iterator
{
IteratorBase *d_base;
public:
void next() { d_base->next(); }
};
|
2,191,684 | 2,191,928 | How to write a GUI for a large cross-platform C++ project? | I have a large cross-platform (Linux and Windows) C++ project, for which I want to create a GUI.
I have few very general questions about the basic principles of GUI for such project:
Should the GUI be separated from the application's logic?
If it is separated, how should the logic and the GUI communicate? Are TCP/IP sockets a good option? What are other possibilities?
Is it a good idea to have the GUI in a language different than a C++? If yes - which language?
Is it a good idea to have a browser-based GUI?
Even though the project's core logic is cross-platform, I can decide that the GUI will be only Windows-based (.NET?) and it will communicate with the logic on the relevant Win/Linux machine through Socket or similar method. Is it a good idea to do so?
|
Should the GUI be separated from the application's logic?
Yes, definitely....
If it is separated, how should the logic and the GUI communicate? Are TCP/IP sockets a good option? What are other possibilities?
...but not that much. Sockets would be overkill (exception: see question 5). Usually you split up the classes in GUI and backend parts. The GUI classes then call methods of the backend.
Is it a good idea to have the GUI in a language different than a C++? If yes - which language?
If so, you would have to integrate the two languages, so I would recommend writing everything in the same language. But to answer your question, you could for example create Python bindings for your backend and write the GUI in Python (with PyGTK, PyQT or wxWidgets).
Is it a good idea to have a browser-based GUI?
That depends on how you want to deploy your application. If it should be installed on each client computer, a web interface doesn't make sense. If you want to host it centrally, then you might opt for a web interface.
Even though the project's core logic is cross-platform, I can decide that the GUI will be only Windows-based (.NET?) and it will communicate with the logic on the relevant Win/Linux machine through Socket or similar method. Is it a good idea to do so?
I think this makes sense only if the backend must be some kind of secure (i.e. must not be installed on users' computers) or if you have a thin client-like approach as in question 4. Writing cross-platform GUIs is much easier than writing cross-platform backends (in my opinion), so you should rather do both parts cross-platform. By the way, .NET-based GUIs are not Windows-only - Mono already supports a great subset of Windows Forms, for example (but not WPF, sadly).
EDIT:
Concerning your Mono question: Mono is mostly stable, but not everything is yet implemented. To be sure, you can run The Mono Migration Analyzer (MoMA) to find out if something will not work in Mono. But I think the fact that so many companies are successfully using Mono in production environments means that you should at least consider Mono as an option!
|
2,191,724 | 2,192,608 | Using Iterators to hide internal container and achieve generic operation over a base container | I basically want to have a base container class which can return a generic iterator that can be used to traverse an instance of the container class, without needing to specify iterator templates. I think I cannot implement the base container over a class template, which would then require a traversal algorithm based on template classes which are not known in advance. The base container can be inherited and implemented using any (custom or standard) container type/implementation within. Here are some code samples to make it clear:
struct MyObject {
int myInt;
}
// an abstract container
class BaseContainer {
public:
virtual void insertMyObject(MyObject& obj) = 0;
virtual iterator getFirst(); // the iterator type is for demonstration purposes only
virtual iterator getLast(); // the iterator type is for demonstration purposes only
}
// Sample container class that uses a std::vector instance to manage objects
class BaseContainer_Vector : public BaseContainer {
public:
void insertMyObject(MyObject& obj); // e.g. just pushes back to the vector
iterator getFirst(); // needs to override the iterator?
iterator getLast(); // needs to override the iterator?
private:
std::vector<MyObject> objectContainer;
}
I will then have a list of container objects, and I want to iterate over both these containers and the objects stored.
std::vector<MyContainer*> containers;
for(int i=0 ; i<containers.size() ; i++){
iterator i = containers[i]->getFirst();
iterator iend = containers[i]->getLast();
for(; i != iend ; i++) {
std::cout << (*i).myInt << std::endl;
}
}
I further would like to have support for boost foreach macro statement. It supports extensions as long as range_begin and range_end functions are properly. But, the example in boost doc uses std::string::iterator as return type, while what I need is a generic iterator class and I could not yet figure out how to do that as well.
std::vector<MyContainer*> containers;
for(int i=0 ; i<containers.size() ; i++){
BOOST_FOREACH(MyObject obj, *(containers[i])) {
std::cout << obj.myInt << std::endl;
}
}
I think I can define my own iterator class, then each class that extends BaseContainer should define their own iterator extending that basic iterator. Yet, I would prefer to use standard iterators (stl or boost) to support this structure, rather that writing my own iterators. I guess this approach will work, but I am open to comments regarding its efficiency.
Is there a feasible approach that can solve this problem elegantly? Or am I missing a simple point which can solve this problem without any pain?
A similar question can be found here, but the proposed solutions seem a bit complex for my needs, and the requirements differ as far as I can understand.
| It's gonna be complicated.
As already stated, first you need your iterators to have value semantic because since they are usually copied around otherwise it would result in object slicing.
class BaseContainer
{
protected:
class BaseIteratorImpl; // Abstract class, for the interface
public:
class iterator
{
public:
iterator(const BaseIteratorImpl& impl);
private:
BaseIteratorImpl* m_impl;
};
iterator begin();
iterator end();
}; // BaseContainer
Then, BaseIterator forwards all methods to m_impl.
This way you achieve value semantic syntax with a polymorphic core.
Obviously, you'll have to handle deep-copy semantics and proper destruction.
Some notes:
publish both an iterator and a const_iterator class
name your methods empty, size, begin, end etc... for compatibility with STL algorithms
You can check SGI Iterators for help about the Concepts and operations your operators should support for maximum compatibility.
|
2,191,782 | 2,191,797 | Differences between structs and classes? | Do structures support inheritance? I think it's stupid question, but I have not much idea about it.
What is the meaning of writing code like this:
struct A {
void f() { cout << "Class A" << endl; }
};
struct B: A {
void f() { cout << "Class B" << endl; }
};
In structures also private section will come, don't they give encapsulation? What is the major difference between structures and classes?
| Yes structures support all features that classes do. The differences are:
structure inheritance is public by default
structure members are public by default
|
2,191,831 | 2,191,846 | Real time plotting/data logging | I'm going to write a program that plots data from a sensor connected to the computer. The sensor value is going to be plotted as a function of the time (sensor value on the y-axis, time on the x-axis). I want to be able to add new values to the plot in real time. What would be best to do this with in C++?
Edit: And by the way, the program will be running on a Linux machine
| Write a function that can plot a std::deque in a way you like, then .push_back() values from the sensor onto the queue as they come available, and .pop_front() values from the queue if it becomes too long for nice plotting.
The exact nature of your plotting function depends on your platform, needs, sense of esthetics, etc.
|
2,192,086 | 2,192,151 | Which one is faster, reading from disk or allocate system memory | My environment is XP 32-bit. I find when allocated memory is nearly the maximum size, 2GB, that means a little virtual space is available, allocationnew memory is very slow.
So if I have a page file, my app need to analyze them.
I have two ways. One is to read them all into system memory, then do the analysis.
The other is to reserv a memory buffer first as a cache, and read part of page file into that buffer, analyze and then discard it, then read second part of page file, and override the cache, do the analysis again.
From the profiling, it looks the second one is faster, since it avoid the allocation time cost.
What do you think? Thanks in adavance.
| (1) I'm not sure the question matches the title. If you're allocating close to 2GB of RAM on 32 bit Windows, the system is probably paging a lot of memory to disk, and that's where I'd look first for the slow down. When you're using a lot of memory, you should think of it as being stored on disk (in pagefile.sys) but cached in physical RAM. The second one might be faster not because of the cost of doing allocation, but because of the cost of using a lot of memory at once. In effect when you copy the file into one big allocation you're copying much of it disk->disk via RAM, then when you run over it again to analyse, you're loading the copy back to RAM again. If your analysis is a single-pass algorithm that's a lot of redundant work.
(2) What I think is, mmap the file (MapViewOfFile and friends on Windows).
Edit: (3) a caution. If the file is currently 1.8GB, there might be a chance that next year it might be 4GB. If so, I'd plan now for it to have a size greater than 2^32 on a 32bit machine, which means either taking your second option, or else still using MapViewOfFile but doing it one sensible-sized chunk of the file at a time, rather than all at once. Otherwise you'll be revisiting this code the first time someone tries it on a big file and reports the bug.
|
2,192,238 | 2,192,255 | What are the differences in string initialization in C++? | Is there any difference between
std::string s1("foo");
and
std::string s2 = "foo";
?
| Yes and No.
The first is initialized explicitly, and the second is copy initialized. The standards permits to replace the second with the first. In practice, the produced code is the same.
Here is what happens in a nutshell:
std::string s1("foo");
The string constructor of the form:
string ( const char * s );
is called for s1.
In the second case. A temporary is created, and the mentioned earler constructor is called for that temporary. Then, the copy constructor is invoked. e.g:
string s1 = string("foo");
In practice, the second form is optimized, to be of the form of the first. I haven't seen a compiler that doesn't optimize the second case.
|
2,192,253 | 2,192,261 | Can two booleans be compared in C++? | Is the following piece of code supposed to work?
bool b1 = true;
bool b2 = 1 < 2;
if (b1 == b2)
{
// do something
}
I suspect that not all 'trues' are equal.
| Yes. All trues are equal.
|
2,192,326 | 2,192,383 | To get reference counting, do I have to clutter my APIs with shared_ptr? | I recently had the following memory bug, which is easy to spot here, but can be harder to detect in more complex code:
class Foo : public IFoo {
const Bar& bar_;
public:
Foo(const Bar& bar) : bar_(bar) {
}
void test() {
// access bar_ here
}
};
int baz() {
IFoo* foo = NULL;
if(whatever) {
Bar bar;
foo = new Foo(bar);
}
else {
// create other foo's
}
foo->test(); // segmentation fault
}
The bug is that Bar immediately goes out of scope, is destroyed and then used in foo->test(). One solution is to create Bar on the heap, using Bar* bar = new Bar(). However, I don't like to do this because I'd have to keep the Bar* bar pointer at top-level so I can access and delete it at the end, even though Bar is something that is specific to that particular code block if(whatever){}.
Another solution is boost::shared_ptr<Bar>, but I cannot just write this:
if(whatever) {
boost::shared_ptr<Bar> bar(new Bar());
foo = new Foo(*bar);
}
since the shared_ptr goes out of scope immediately, too, destroying the contained object.
So in short, to get rid of this problem, I'd have to use shared_ptr everywhere, in Foo as member variable, in Foo's constructor, etc. To eliminate these problems in general, all my APIs etc. have to use shared_ptr, which is kind of ugly. But, is it the right thing to do? So far, I have used it sometimes to create reference-counted objects, but I have kept my APIs clean of shared_ptr. How do you deal with this problem that, once you use shared_ptr you have to use it everywhere?
(Also, if you use these reference-counted pointers, you have to start worrying about if you really want shared_ptr or rather weak_ptr etc.)
And, what would I use as an equivalent to Foo(const Bar& bar)? Foo(const shared_ptr<const Bar> bar)?
Another option, of course, is to add reference counting inside the Bar and other objects yourself, using pimpl and your own counters, but that gets too tedious as a general rule.
| Actually I do use shared_ptr everywhere... There are several ways to make it look less cluttered. One convention I use is typedefs for each defined class:
class AClass {
public:
typedef boost::shared_ptr<AClass> Ptr;
typedef boost::weak_ptr<AClass> Ref;
//...
};
Makes the code much more readable :)
As for your specific problem, remember that you can pass bar by pointer -- you'd have to remember to allocate it on the heap though.
|
2,192,415 | 2,192,460 | unlink vs remove in c++ | What is the difference between remove and unlink functions in C++?
| Apart from the fact that unlink is unix-specific (as pointed out by Chris), we read in the POSIX manual:
If path does not name a directory, remove(path) is equivalent to unlink(path).
If path names a directory, remove(path) is equivalent to rmdir(path).
As for the directory-passed unlink, we read:
The path argument must not name a directory unless the process has appropriate privileges and the implementation supports using unlink() on directories. (...) Applications should use rmdir() to remove a directory.
|
2,192,416 | 2,192,903 | How to convert concatenated strings to wide-char with the C preprocessor? | I am working on a project where I have many constant strings formed by concatenation (numbers, etc.).
For example, I have a LOCATION macro that formats __FILE__ and __LINE__ into a string that I can use to know where I am in the code, when printing messages or errors:
#define _STR(x) # x
#define STR(x) _STR(x)
#define LOCATION __FILE__ "(" STR(__LINE__) ")"
So, this would format a location like "file.cpp(42)". The problem is when I try to convert the result to a wide-string:
#define _WIDEN(x) L ## x
#define WIDEN(x) _WIDEN(x)
#define WLOCATION WIDEN(LOCATION)
This works just fine with GCC, and results in L"file.cpp(42)" being inserted in my code. However, when trying this with MSVC++ (using Visual C++ 2008 Express), I get an error:
error: Concatenating wide "file.cpp" with narrow "("
I understand that the L prefix gets added only to the first term in my expression. I've also tried this:
#define _WIDEN(x) L ## #x
Which "works", but gives the string L"\"file.cpp\" \"(\" \"42\" \")\"" which is obviously not very convenient (and not what I am looking for), especially considering that this macro is simple compared to other macros.
So, my question is: how can I get it to apply to the entire expression in MSVC++, so I can get the same result I am getting with GCC? I would rather not create a second string with all-wide tokens, because I would then have to maintain two macros for each one, which is not very convenient and can lead to bugs. Plus, I need the narrow version of each string as well, so using all-wide strings is not an option either, unfortunately.
| According to the C standard (aka "ISO-9899:1999" aka "C99"), Visual C is wrong and gcc is correct. That standard states, section 6.4.5/4:
In translation phase 6, the multibyte character sequences specified by any sequence of adjacent character and wide string literal tokens are concatenated into a single multibyte character sequence. If any of the tokens are wide string literal tokens, the resulting multibyte character sequence is treated as a wide string literal; otherwise, it is treated as a character string literal.
So you could file a complaint. Arguably, the previous version of the C standard (aka "C89" aka "C90" aka "ANSI C") did not mandate merging of wide strings with non-wide strings. Although C99 is now more than ten years old, it seems that Microsoft has no interest in making its C compiler conforming. Some users have reported being able to access some "C99" features by compiling C code as if it was C++ code, because C++ includes these features -- and for C++, Microsoft made an effort. But this does not seem to extend to the preprocessor.
In the C89 dialect, I think that what you are looking for is not possible (actually I am pretty sure of it, and since I have written my own preprocessor I think I know what I am talking about). But you could add an extra parameter and propagate it:
#define W(x) W_(x)
#define W_(x) L ## x
#define N(x) x
#define STR(x, t) STR_(x, t)
#define STR_(x, t) t(#x)
#define LOCATION_(t) t(__FILE__) t("(") STR(__LINE__, t) t(")")
#define LOCATION LOCATION_(N)
#define WLOCATION LOCATION_(W)
which should work on both gcc and Visual C (at least, it works for me, using Visual C 2005).
Side note: you should not define macros with a name beginning with an underscore. These names are reserved, so by using them you could clash with some names used in system headers or in future versions of the compiler. Instead of _WIDEN, use WIDEN_.
|
2,192,476 | 2,287,878 | Thread Building Block versus MPI, which one fits mt need better? | Now I have a serial solver in C++ for solving optimization problems and I am supposed to parallelize my solver with different parameters to see whether it can help improve the performance of the solver. Now I am not sure whther I should use TBB or MPI. From a TBB book I read, I feel TBB is more suitable for looping or fine-grained code. Since I do not have much experience with TBB, I feel it is difficult to divide my code to small parts in order to realize the parallelization. In addition, from the literature, I find many authors used MPI to parallel several solvers and make it cooperate. I guess maybe MPI fits my need more. Since I do not have much knowledge on either TBB or MPI. Anyone can tell me whether my feeling is right? Will MPI fit me better? If so, what material is good for start learning MPI. I have no experience with MPI and I use Windows system and c++. Thanks a lot.
| The basic thing you need to have in mind is to choose between shared-memory and distributed-memory.
Shared-memory is when you have more than one process (normally more than one thread within a process) that can access a common memory. This can be quite fine-grained and it is normally simpler to adapt a single-threaded program to have several threads. You will need to design the program in a way that the threads work most of the time in separate parts of the memory (exploit data parallelism) and that the shared part is protected against concurrent accesses using locks.
Distributed-memory means that you have different processes that might be executed in one or several distributed computers but these process have together a common goal and share data through message-passing (data communication). There is no common memory space and all the data one process need from another process will require communication.
It is a more general approach but, because of communication requirements, it requires coarse grains.
TBB is a library support for thread-based shared-memory parallelism while MPI is a library for distributed-memory parallelism (it has simple primitives for communication and also scripts for several processes in different nodes execution).
The most important thing is for you to identify the parallelisms within your solver and then choose the best solution. Do you have data parallelism (different thread/processes could be working in parallel in different chunks of data without the need of communication or sharing parts of this data)? Task parallelism (different threads/processes could be performing a different transformation to your data or a different step in the data processing in a pipeline or graph fashion)?
|
2,192,584 | 2,424,273 | How do I decrypt a file with Crypto++ that was encrypted with C# | I would like to decrypt a file that I previously encrypted with C# using the TripleDESCryptoServiceProvider.
Here's my code for encrypting:
private static void EncryptData(MemoryStream streamToEncrypt)
{
// initialize the encryption algorithm
TripleDES algorithm = new TripleDESCryptoServiceProvider();
byte[] desIV = new byte[8];
byte[] desKey = new byte[16];
for (int i = 0; i < 8; ++i)
{
desIV[i] = (byte)i;
}
for (int j = 0; j < 16; ++j)
{
desKey[j] = (byte)j;
}
FileStream outputStream = new FileStream(TheCryptedSettingsFilePath, FileMode.OpenOrCreate, FileAccess.Write);
outputStream.SetLength(0);
CryptoStream encStream = new CryptoStream(outputStream, algorithm.CreateEncryptor(desKey, desIV),
CryptoStreamMode.Write);
// write the encrypted data to the file
encStream.Write(streamToEncrypt.ToArray(), 0, (int)streamToEncrypt.Length);
encStream.Close();
outputStream.Close();
}
I already found the Crypto++ library and managed to build and link it. So I tried to decrypt the file that was stored with C# after the encryption with the following (native) C++ code:
FILE *fp;
long len;
char *buf;
if (_wfopen_s(&fp, _T("MyTest.bin"), _T("rb")) != 0)
{
return false;
}
fseek(fp ,0 ,SEEK_END); //go to end
len = ftell(fp); //get position at end (length)
fseek(fp, 0, SEEK_SET); //go to beg.
buf = (char *)malloc(len); //malloc buffer
fread(buf, len, 1, fp); //read into buffer
fclose(fp);
BYTE pIV[] = {0, 1, 2, 3, 4, 5, 6, 7};
BYTE pKey[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};
const BYTE* lpData = (const BYTE*)(LPCTSTR)buf;
size_t bufferSize = strlen(buf);
BYTE* result = (BYTE *)malloc(bufferSize);
CFB_FIPS_Mode<DES_EDE2>::Decryption decryption_DES_EDE2_CFB;
decryption_DES_EDE2_CFB.SetKeyWithIV(pKey, sizeof(pKey), pIV, sizeof(pIV));
decryption_DES_EDE2_CFB.ProcessString(result, lpData, bufferSize);
That code won't decrypt properly. The result after the decryption doesn't match the plain text that was encrypted previously. Any idea about my code?
| I managed to do that task with Windows Crypto API as stated in my other post.
|
2,192,680 | 2,192,771 | Macro / keyword which can be used to print out method name? | __FILE__ and __LINE__ are well known. There is a __func__ since C99.
#include <iostream>
struct Foo {
void Do(){ std::cout << __func__ << std::endl; }
};
int main()
{
std::cout << __func__ << std::endl;
Foo foo; foo.Do();
return 0;
}
will output
main
Do
Is there any macro / keyword that would output method name like Foo::Do?
| Boost has a special utility macro called BOOST_CURRENT_FUNCTION that hides the differences between the compiler implementations.
Following it's implementation we see that there are several macros depending on compiler:
__PRETTY_FUNCTION__ -- GCC, MetroWerks, Digital Mars, ICC, MinGW
__FUNCSIG__ -- MSVC
__FUNCTION__ -- Intel and IBM
__FUNC__ -- Borland
__func__ -- ANSI C99
|
2,192,880 | 2,192,994 | Worst side effects from chars signedness. (Explanation of signedness effects on chars and casts) | I frequently work with libraries that use char when working with bytes in C++. The alternative is to define a "Byte" as unsigned char but that not the standard they decided to use. I frequently pass bytes from C# into the C++ dlls and cast them to char to work with the library.
When casting ints to chars or chars to other simple types what are some of the side effects that can occur. Specifically, when has this broken code that you have worked on and how did you find out it was because of the char signedness?
Lucky i haven't run into this in my code, used a char signed casting trick back in an embedded systems class in school. I'm looking to better understand the issue since I feel it is relevant to the work I am doing.
| One major risk is if you need to shift the bytes. A signed char keeps the sign-bit when right-shifted, whereas an unsigned char doesn't.
Here's a small test program:
#include <stdio.h>
int main (void)
{
signed char a = -1;
unsigned char b = 255;
printf("%d\n%d\n", a >> 1, b >> 1);
return 0;
}
It should print -1 and 127, even though a and b start out with the same bit pattern (given 8-bit chars, two's-complement and signed values using arithmetic shift).
In short, you can't rely on shift working identically for signed and unsigned chars, so if you need portability, use unsigned char rather than char or signed char.
|
2,192,902 | 2,195,659 | Why this Dijkstra (graph) implementation isn't working? | I made this implementation for this problem :
http://www.spoj.pl/problems/SHOP/
#include<iostream>
#include<stdio.h>
#include<queue>
#include<conio.h>
#include<string.h>
using namespace std;
struct node
{
int x;
int y;
int time;
};
bool operator <(const node &s,const node &r)
{
if(s.time>r.time)
return true;
else return false;
}
node beg,src,dest,tempa;
int b,a,temp;
int map[25][25];
bool vis[25][25];
int X[]={1,0,-1,0};
int Y[]={0,1,0,-1};
int djs_bfs(node src,node dest)
{
int result=0;
priority_queue<node>pq;
pq.push(src);
while(!pq.empty())
{
node top = pq.top();
pq.pop();
if(top.x==dest.x && top.y==dest.y) return result;
if(top.x<0 || top.x>=a) continue;
if(top.y<0 || top.y>=b) continue;
if(vis[top.x][top.y]) continue;
vis[top.x][top.y]=true;
result+=map[top.x][top.y];
for(int i=0;i<4;i++)
{
tempa.x=top.x+X[0];
tempa.y=top.y+Y[0];
tempa.time=map[top.x+X[0]][top.y+Y[0]];
pq.push(tempa);
}
}
return -1;
}
int main()
{
memset(vis,false,sizeof(vis));
scanf("%d %d",&a,&b);
while(a != 0)
{
for(int i=0;i<a;i++)
for(int j=0;j<b;j++)
{
scanf("%c",&temp);
if(temp=='X') {map[i][j]=0;vis[i][j]=true;}
if(temp=='S') {src.x=i;src.y=j;src.time=0;}
if(temp=='D') {dest.x=i;dest.y=j;dest.time=0;}
else map[i][j]=temp-'0';
}
cout<<djs_bfs(src,dest)<<endl;
scanf("%d %d",&a,&b);
}
return 0;
getch();
}
I don't know why my code doesn't generate the right answer for the testcases.
If someone can help me improve the code, please do so :D
| First of all, the graph parsing code is incorrect. The first line specifies width and height, where the width is the number of characters per line the height is the number of lines. Therefore, swap &a and &b in the first scanf, or swap the order of the nested for loops (but not both). Also, I had to add dummy scanf("%c", &dummy); calls at various places to filter out newlines. A simple dump, such as this, will help determine if your map was parsed correctly:
cout << "a=" << a << endl;
cout << "b=" << b << endl;
for (int i=0; i<a; i++) {
for(int j=0; j<b; j++) {
cout << (char)('0' + map[i][j]) << ",";
}
cout << endl;
}
Note: I also set map[i][j] to 0 for 'S' and 'D', also changing the repeated if statements into an if; else if; else chain. This makes the algorithm more robust, since you can generically add time from the source or destination.
Now, on to the algorithm itself....
Each loop of the algorithm increments result by the current map location weight. However, the algorithm is searching multiple paths simultaneously (i.e., the number of entries in the priority queue), and therefore result ends up being the sum of all processed node weights, not the current path weight. The current path weight is top.temp, and therefore you can eliminate the result variable and simply return top.temp when you reach the destination.
Also, as other answers noted, you need to use X[i] and Y[i] in your inner loop, otherwise you are only searching in one direction.
Now, because of the addition/subtraction from X[i] and Y[i], you will likely access map[][] out of range (-1 or 25). Therefore, I recommend moving the if guards to the inner for loop to guard against the out-of-range access. This also avoids filling the priority queue with illegal possibilities.
Here is my version of the algorithm, with minimal corrections, for reference:
priority_queue<node>pq;
pq.push(src);
while(!pq.empty())
{
node top = pq.top();
pq.pop();
if(top.x==dest.x && top.y==dest.y) return top.time;
if(vis[top.x][top.y]) continue;
vis[top.x][top.y]=true;
for(int i=0;i<4;i++)
{
tempa.x=top.x+X[i];
tempa.y=top.y+Y[i];
if(tempa.x<0 || tempa.x>=a) continue;
if(tempa.y<0 || tempa.y>=b) continue;
tempa.time=top.time + map[tempa.x][tempa.y];
pq.push(tempa);
}
}
return -1;
I hope this helps.
|
2,193,399 | 2,197,145 | How do I require const_iterator semantics in a template function signature? | I am creating a constructor that will take a pair of input iterators. I want the method signature to have compile-time const semantics similar to:
DataObject::DataObject(const char *begin, const char *end)
However, I can't find any examples of this.
For example, my STL implementation's range constructor for vector is defined as:
template<class InputIterator>
vector::vector(InputIterator first, InputIterator last)
{
construct(first, last, iterator_category(first));
}
which has no compile-time const guarantees. iterator_category / iterator_traits<> contain nothing relating to const, either.
Is there any way to indicate to guarantee the caller that I can't modify the input data?
edit, 2010-02-03 16:35 UTC
As an example of how I would like to use the function, I would like to be able to pass a pair of char* pointers and know, based on the function signature, that the data they point at will not be modified.
I was hoping I could avoid creating a pair of const char* pointers to guarantee const_iterator semantics. I may be forced to pay the template tax in this case.
| You could simply create a dummy function which calls your template with char * const pointers. If your template attempts to modify their targets, then your dummy function will not compile. You can then put said dummy inside #ifndef NDEBUG guards to exclude it from release builds.
|
2,193,605 | 2,196,852 | Which boost libraries are heading for TR2? | If found this quote at boost.org:
More Boost libraries are in the pipeline for TR2
It links to the TR2 call from proposals. But I can't seem to find any other information on which boost libraries are headed for TR2.
I've seen a draft proposal for Boost.Asio, and I vaguely remember seeing something about Boost.System and Boost.Filesystem being proposed as well.
Which boost libraries are headed for TR2?
What else has been proposed for the TR2?
Are there any good sources of information for this?
I know everyone's really focused on C++0x right now, and don't expect to find a lot of official information. But surely someone's documented something about the TR2.
| Sorry to answer my own question but after Neil's slap-in-the-face comment I had to find out for myself and none of the other comments were at all helpful.
Wikipedia doesn't have a C++ Technical Report 2 page but it does have a tr2 section in the C++ Technical Report 1 page.
Here is a quick list from Wikipedia.
Boost.Asio
Signals/Slots, a combination of Boost.Signals and libsigc++
Boost.Filesystem
Boost.Any
boost::lexcal_cast<>
Boost.String Algo
Boost.System
There are a couple more as well. Wikipedia has the links for to the actual proposals. The latest proposal (something about heterogenious containers) as sent in May 2009, less than a year ago.
|
2,193,944 | 2,194,114 | Convert a Static Library to a Shared Library (create libsome.so from libsome.a): where's my symbols? | the title of this question is an exact dupe, but the answers in that question don't help me.
I have a bunch of object files packed in a static library:
% g++ -std=c++98 -fpic -g -O1 -c -o foo.o foo.cpp
% g++ -std=c++98 -fpic -g -O1 -c -o bar.o bar.cpp
% ar -rc libsome.a foo.o bar.o
I'd like to generate libsome.so from libsome.a instead of the object files, but the library is really barebones:
% g++ -std=c++98 -fpic -g -O1 -shared -o libsome.so libsome.a
% nm -DC libsome.so
0000xxxx A _DYNAMIC
0000xxxx A _GLOBAL_OFFSET_TABLE_
w _Jv_RegisterClasses
0000xxxx A __bss_start
w __cxa_finalize
0000xxxx A _edata
0000xxxx A _end
0000xxxx T _fini
0000xxxx T _init
the static library is ok, or at least I'm perfectly able to link it to an executable and have it run the contained functionality. also, everything is fine if I create libsome.so from foo.o and bar.o.
| Assuming you're using the GNU linker, you need to specify the --whole-archive option so that you'll get all the contents of the static archive. Since that's an linker option, you'll need -Wl to tell gcc to pass it through to the linker:
g++ -std=c++98 -fpic -g -O1 -shared -o libsome.so -Wl,--whole-archive libsome.a
If you were doing something more complicated where you want all of library some but only the part of library support needed by libsome, you would want to turn off whole archive after you've used it on libsome:
... -Wl,--whole-archive libsome.a -Wl,--no-whole-archive libsupport.a
If you're not using the GNU linker, you'll need to see if your linker supports it and what it's called. On the Sun linker, it's called -z allextract and -z defaultextract.
|
2,193,977 | 2,194,025 | Why does GetLastError() return different codes during debug vs "normal" execution? | try
{
pConnect = sess->GetFtpConnection(ftpArgs.host, ftpArgs.userName, ftpArgs.password, port, FALSE );
}
catch (CInternetException* pEx)
{
loginErrCode = GetLastError();
printf("loginErrCode: %d\n", loginErrCode);
if(loginErrCode == 12013)
{
printf("Incorrect user name!\n");
exit(0);
}
else if(loginErrCode == 12014)
{
printf("Incorrect password!\n");
exit(0);
}
else if(loginErrCode == 12007)
{
printf("Incorrect server name!\n");
exit(0);
}
else //display all other errors
{
TCHAR sz[1024];
pEx->GetErrorMessage(sz, 1024);
printf("ERROR! %s\n, sz);
pEx->Delete();
exit(0);
}
When this code runs from visual studio with an intentional incorrect user name, GetLastError() returns 12014 (expected).
However, when running the same code from the command line (with the same exact incorrect username) GetLastError() returns 2? (the GetErrorMessage() does return incorrect password)
I do not understand what the difference is.
In addition, I ran the program from the command line while attaching the process to it in visual studio, to debug. I received 12014.
Whenever the debugger is involved, I get 12014. When I run the executable "normally" with the same parameters, I get 2.
Are the WinInet error codes not being found when I run the program outside of the debugger? Do I need to compile the program differently?
Any help is appreciated. Thank You.
| My memory is a little hazy in this regard, but what happens if you use the m_dwError field of the CInternetException object instead of calling GetLastError()?
My guess is that something is causing the error code to be reset between when the actual error and your call to GetLastError(). I don't know why this happens when running outside the debugger but not inside the debugger. However, MFC caches the error code that caused the exception in the thrown object, so you should be able to use the cached value regardless of what API calls have happened since the exception was thrown.
GetErrorMessage() returns the correct error string because it uses this m_dwError field, rather than calling GetLastError().
|
2,194,050 | 2,195,250 | Simple proxy program with BOOST | I'm trying to do a very simple program. It's actually a proxy, that I need to connect to it and that proxy fowards the packets to the outter world.
I think of making a list of incomming packets, change the incomming port to a new port, forward the packet and wait for a response, and get the port number for the packet from my list and send it back to my app...
How can I do that with boost??? I don't need the complete source code, just some code and the directions to start...(althought the full code will be usefull hehehe)...
Thx.
| You're in over your head, have you considered not coding it? Use socat:
socat TCP-LISTEN:7656,bind=internal-ip,fork TCP:external-host:7656
|
2,194,100 | 2,194,328 | FIFO list (moving elements) [C++] | Good evening, people!
I'm trying to solve a rather simple problem, but.. well, it seems that I can't. :)
The idea is that I have a FIFO list (FIFO queue) with n elements and it's given a value, k (k < n). My little program has to move the elements to the left with k elements. (e.g. for n=4, k=3, a[]=(1, 2, 3, 4), the result is 4 1 2 3).
But well, I get nowhere near that.
This is what I've written so far:
#include <iostream>
using namespace std;
void move (int a[100], unsigned n, unsigned k) {
int t[100];
unsigned i;
for (i=0; i<=n-1; i++) t[i]=a[i];
for (i=0; i<=k-1; i++) a[i]=a[i+k-1];
for (i=k; i<=n-1; i++) a[i]=t[i+1];
}
int main () {
int a[100];
unsigned k, n, i;
cout<<"n; k= "; cin>>n>>k;
for (i=0; i<=n-1; i++) cin>>a[i];
move (a, n, k);
for (i=0; i<=n-1; i++) cout<<a[i]<<" ";
}
Any help would be greatly appreciated. Thank you in advance.
| I'm not sure if I've understood your question completely. But looks like you effectively want to rotate the contents of the array.
To rotate the array contents to the left k times. You can do the following:
Reverse the first K elements.
Reverse the remaining N-K elements.
Reverse the entire array.
Example:
N = 5, K = 3, and array = [1 2 3 4 5]
step 1: reverse the first 3 elements:
[3 2 1 4 5]
step 2: reverse the remaining 2
elements: [3 2 1 5 4]
step 3: reverse the entire array: [4
5 1 2 3]
C++ function to do the same:
void move (int a[100], int n, int k) {
int t[100];
int i,j;
for (i=k-1,j=0; i>=0; i--,j++) t[j]=a[i];
for (i=n-1; i>=k; i--,j++) t[j]=a[i];
for (i=n-1,j=0; i>=0; i--,j++) a[j]=t[i];
}
A better way to do it in constant space is to do the reversal in-place:
void arr_rev(int a[100], int start, int end) {
int temp;
for(;start<end;start++,end--) {
temp = a[start];
a[start] = a[end];
a[end] = temp;
}
}
void move2 (int a[100], int n, int k) {
arr_rev(a,0,k-1);
arr_rev(a,k,n-1);
arr_rev(a,0,n-1);
}
|
2,194,310 | 2,194,359 | Getting 32 bit words out of 64-bit values in C/C++ and not worrying about endianness | It's my understanding that in C/C++ bitwise operators are supposed to be endian independent and behave the way you expect. I want to make sure that I'm truly getting the most significant and least significant words out of a 64-bit value and not worry about endianness of the machine. Here's an example:
uint64_t temp;
uint32_t msw, lsw;
msw = (temp & 0xFFFFFFFF00000000) >> 32;
lsw = temp & 0x00000000FFFFFFFF;
Will this work?
|
6.5.7 Bitwise shift operators
4 The result of E1 << E2 is E1
left-shifted E2 bit positions; vacated
bits are filled with zeros. If E1 has
an unsigned type, the value of the
result is E1 × 2E2, reduced modulo one
more than the maximum value
representable in the result type. If
E1 has a signed type and nonnegative
value, and E1 × 2E2 is representable
in the result type, then that is the
resulting value; otherwise, the
behavior is undefined.
So, yes -- guranteed by the standard.
|
2,194,762 | 2,194,803 | How to compare two objects (the calling object and the parameter) in a class? | I am writing a "Date" class for an assignment and I am having trouble doing one the of the functions.
This is the header file for the class.
class Date
{
public:
Date(); // Constructor without parameters
Date(int m, int d, int y); // Constructor with parameters.
// accessors
int GetMonth(); // returns the size of the diamond
int GetDay();
int GetYear();
// mutators
bool Set(int m, int d, int y);
bool SetFormat(char f);
// standard input and output routines
void Input();
void Show();
void Increment(int numDays = 1);
int Compare(const Date& d);
private:
int month, // month variables
day, // day variable
year; // year variable
char format;
};
The member function I am trying to make is the int Compare(const Date& d) function. I need this function to compare two Date objects (the calling object and the
parameter), and should return: -1 if the calling object comes first
chronologically, 0 if the objects are the same date, and 1 if the parameter object
comes first chronologically.
I have tried doing a simple if statement with the == operator but I get errors.
if (d1 == d2)
cout << "The dates are the same";
return (0);
After the objects are created, the function should be called like this d1.Compare(d2)
Thank you in advance!
| int Date :: Compare (const Date& d) {
if (year<d.year) {
return -1;
}
else if (year>d.year) {
return 1;
}
else if (month<d.month) {
return -1;
}
else if (month>d.month) {
return 1;
}
// same for day
return 0;
}
Usually, you'lll also want to provide overloaded comparison operators, for example (also within the class definition):
bool operator == (const Date& d) const {
return !Compare(d);
}
bool operator < (const Date& d) const {
return Compare(d)<0;
}
... // consider using boost::operators
PS: There are smarter implementations of Compare() - just check the other answers. This one is pretty straightforward and readable, but conforms exactly to your specification.
|
2,194,827 | 2,195,044 | How to modify the keyboard input in QT? | The following feature needs to be implemented to our existing QT & C++ application.
We have to expand the user typed abbreviations into pre-defined words(s). The functionality we need to implement is something similar to text expander. Say if a user typed "FL", this needs to be replaced to "Florida" after immediately.
I was able to find out the QT documentation for capturing the key events, but I'm not sure how to modify the keyboard input with pre-defined characters set.
It would be great if you guys provide me some sample code and directions on this.
Thanks in advance!
| Could this example be useful to you ?
They use a mecanism called completer, that provides different words for a given entry... It's quite like a dictionnary on a cell phone...
Custom Completer Example :
http://qt.nokia.com/doc/4.6/tools-customcompleter.html
Hope it helps a bit !
|
2,194,904 | 2,195,006 | What good are thread affinity mask changes for the current thread? | I'm writing a game engine and I need a way to get a precise and accurate "deltatime" value from which to derive the current FPS for debug and also to limit the framerate (this is important for our project).
Doing a bit of research, I found out one of the best ways to do this is to use WinAPI's QueryPerformanceCounter function. GetTicksCount has to be used to prevent forward counter leaps, but it in itself is not very accurate.
Now, the problem with QueryPerformanceCounter is that it apparently may return values that would look like if time warped back (i.e. a call may return a value prior in time relative to another call in the past). This happens only when a value obtained with a given processor core is compared against a value obtained with another processor core, which leads me to the ultimate questions that motivated me to make this post:
May the OS "reallocate" a thread to another core while the thread is already running, or is a thread is allocated to a given core and that's that until the thread dies?
If a thread can't be reallocated (and that makes a lot of sense for me, at least), then why is it possible for me to do something like SetThreadAffinityMask(GetCurrentThread(),mask)? Ogre3D does that in its Ogre::Timer class (Windows implementation), and I'm assuming that's to avoid time going back. But for that to be true, then I would have to consider the possibility of threads being moved from one core to another arbitrarily by the OS, which seems rather odd to me (not sure why).
I think that was all I wanted to know for now. Thanks.
| Unless a thread has a processor affinity mask, the scheduler will move it from processor to processor in order to give it execution time. Since moving a thread between processors costs performance, it will try not to move it, but giving it a processor to execute on has priority over not moving it. So, usually threads move.
As for timer apis. timeGetTime is designed for multimedia timing, so it's a bit more accurate than GetTickCount.
QueryPerformanceCounter(). is still your most precise measurement though. Microsoft has this to say about it.
On a multiprocessor computer, it should not matter which processor is called. However, you can get different results on different processors due to bugs in the basic input/output system (BIOS) or the hardware abstraction layer (HAL). To specify processor affinity for a thread, use the SetThreadAffinityMask function.
So if you are doing the timing tests on a specific computer, you may not have to worry about QPC going backwards, you should do some testing and see if it matters on your machine.
|
2,194,958 | 2,195,057 | Should I cache the hash code of an STL string used as a hash key? | I've doing some performance analysis on the software I develop, and I've found that lookups on a global dictionary of URL's takes about 10% of the application's "load" phase time. The dictionary is implemented as a C++ STL std::map, which has O(lg n) lookups. I'm going to move it to a hash_map, which has roughly fixed time lookups. The stl string class doesn't have a hash code property, and it certainly doesn't cache a hash code. That means that each lookup requires re-generating the hash code.
I'm skeptical that caching the hash code is worth the effort. It would mean changing many lines of code to use a new string class with a cached hash code property. Given that the current implementation does log(n) full string comparisons on every lookup, I think reducing it to basically one string traversal (by the hash function) per lookup is a big win.
Does anyone have experience with caching string hash codes? Has it ever proven worth the effort?
| I don't have experience with caching hash codes, but I've done some work recently converting std::map to std::tr1::unordered_map. Two thoughts come to mind. First, try profiling that relatively simple change first, because it sometimes makes things worse, depending on what your code is doing. It might give you enough speedup on its own before you try optimizing further. Secondly, what does your profiler say about the other 90% of your initialization time? Even if you optimized the global dictionary stuff down to 0 time, you will at most improve performance by 10%.
|
2,195,056 | 2,195,220 | Error with using a function as a non-type template parameter | I have this template :
template <class SourceFormat, class DestFormat, void (*convert)(DestFormat, SourceFormat)>
static void _draw(...);
And these functions :
template <class Class1, class Class2>
inline static void convertNone(Class1& dest, Class2& source) {
dest = source;
};
inline static void convertARGB_GREY(unsigned __int32& dest, unsigned __int8& source) {
dest = source + (source << 8);
dest += (dest << 16);
};
I use the template in another function :
void Blitter::draw(...) {
if (...) {
_draw<unsigned __int32, unsigned __int32, &convertNone>(...);
} else {
_draw<unsigned __int32, unsigned __int8, &convertARGB_GREY>(...); // ERRORS go here!
}
}
I get these errors :
Error 1 error C2440: 'specialization' : cannot convert from 'void (__cdecl *)(unsigned int &,unsigned char &)' to 'void (__cdecl *const )(unsigned char,unsigned int)' d:\projects\fanlib\source\blitter.cpp 102
Error 2 error C2973: 'FANLib::Blitter::_draw' : invalid template argument 'void (__cdecl *)(unsigned int &,unsigned char &)' d:\projects\fanlib\source\blitter.cpp 102
I suppose it's rather obvious that I don't fully comprehend functions-as-parameters... :-(
Many thanks in advance
| I don't know if you've done it intentionally, but your template parameters go Source/Destintaion and then Destination/Source.
Notice that when you do _draw<unsigned __int32, unsigned __int8, &convertARGB_GREY>(...); your template definition fills them in as:
SourceFormat = unsigned __int32
DestFormat = unsigned __int8
void (*convert)(unsigned __int8, unsigned __int32)
You don't have a function of that definition though.
You do have one that matches
void (*convert)(unsigned __int32&, unsigned __int8&)
Do you see how the parameters don't match?
Declare your template like this:
template <
class SourceFormat,
class DestFormat,
void (*convert)(SourceFormat, DestFormat)>
static void _draw(...);
and your function declaration like this:
void convertARGB_GREY(
unsigned __int32 source, // notice how I removed the '&'
unsigned __int8 destination) // character on these two lines
and it will compile. (Since you lose the references, I'd recommend returning the result in this case: unsigned __int8 destination convertARGB_GREY(...) though.)
|
2,195,276 | 2,195,305 | A destructor - should I use delete or delete[]? | I am writing a template class that takes as an input a pointer and stores it. The pointer is meant to point to an object allocated by another class, and handed to the this containing class.
Now I want to create a destructor for this container. How should I free the memory pointed to by this pointer? I have no way of knowing a priori whether it is an array or a single element.
I'm sort of new to C++, so bear with me. I've always used C, and Java is my OO language of choice, but between wanting to learn C++ and the speed requirements of my project, I've gone with C++.
Would it be a better idea to change the container from a template to a container for an abstract class that can implement its own destructor?
| If you don't know whether it was allocated with new or new[], then it is not safe to delete it.
Your code may appear to work. For example, on one platform I work on, the difference only matters when you have an array of objects that have destructors. So, you do this:
// by luck, this works on my preferred platform
// don't do this - just an example of why your code seems to work
int *ints = new int[20];
delete ints;
but then you do this:
// crashes on my platform
std::string *strings = new std::string[10];
delete strings;
|
2,195,391 | 2,195,429 | Linked List explanation required | I need to understand how a linked list works in this C++ code. I got it from my textbook. Could someone explain in detail what exactly is going on here?
/*The Node Class*/
class Node{
private:
int object;
Node *nextNode;
public:
int get()
{
return object;
}
void set(int object)
{
this-> object=object;
}
Node *getNext()
{
return nextNode;
};
void setNext(Node *nextNode)
{
this->nextNode = nextNode;
};
};
/* The List class */
class List
{
public:
List();
void add (int addObject);
int get();
bool next();
friend void traverse(List list);
friend List addNodes();
private:
int size;
Node * headNode;
Node * currentNode;
Node * lastCurrentNode;
};
/* Constructor */
List::List()
{
headNode = new Node();
headNode->setNext(NULL);
currentNode = NULL;
lastCurrentNode = NULL;
size = 0;
}
/* add() class method */
void List::add (int addObject)
{
Node * newNode = new Node();
newNode->set(addObject);
if( currentNode != NULL )
{
newNode->setNext(currentNode->getNext());
currentNode->setNext( newNode );
lastCurrentNode = currentNode;
currentNode = newNode;
}
else
{
newNode->setNext(NULL);
headNode->setNext(newNode);
lastCurrentNode = headNode;
currentNode = newNode;
}
size ++;
}
/* get() class method */
int List::get()
{
if (currentNode != NULL)
return currentNode->get();
}
/* next() class method */
bool List::next()
{
if (currentNode == NULL) return false;
lastCurrentNode = currentNode;
currentNode = currentNode->getNext();
if (currentNode == NULL || size == 0)
return false;
else
return true;
}
/* Friend function to traverse linked list */
void traverse(List list)
{
Node* savedCurrentNode = list.currentNode;
list.currentNode = list.headNode;
for(int i = 1; list.next(); i++)
{
cout<<"\n Element "<<i<<" "<<list.get();
}
list.currentNode = savedCurrentNode;
}
/* Friend function to add Nodes into the list */
List addNodes()
{
List list;
list.add(2);
list.add(8);
list.add(7);
list.add(1);
cout<<"\n List size = "<<list.size<<"\n";
return list;
}
main()
{
List list = addNodes();
traverse(list);
system("pause");
}
| what you've posted is a very basic implementation of a linked list. The objects that you're linking is "node".
GetNext function gets the next node in the list
and the setNex function gets the next node in the list.
i'm sure the chapter should have an explanation for the code, at the very least the explanation for the concept of linked list.
hope this helps.
|
2,195,414 | 2,195,479 | How to copy by value into a container class? | I am writing a sparse matrix class. I need to have a node class, which will be a template for its contents. My issue in writing this class is:
How do I store the contents?
I want to store the contents by value. If I stored it by pointer and it should be destroyed, then I'd have trouble. How can I safely perform a copy in the setContents method? Does C++ offer any guarantees that a class that should be placed into my node container has the capability to clone itself?
I've looked into the copy constructor, but I have some qualms. What if the contained class does not implement a copy constructor? Then passing it to the node by reference would not be wise, since that could lead to a dangling reference if the original object should be deleted or go out of scope.
What is the sort of "standard C++" way of doing this?
| The standard C++ approach is to mandate that the type(s) used by your container class must be copyable (and perhaps assignable). It is a very reasonable requirement and is used by all of the container class templates in the standard library.
For built-in types and simple POD-types, a user-declared copy constructor typically isn't needed. A writer of a class that isn't as simple but needs to have value sematics will typically have had to provide a suitable copy constructor in any case.
|
2,195,454 | 2,195,583 | Visual Build professional compile errors? | I am using visual build professional and one of the steps is a 'Make VS 2003' (c++ project). However, every time I get the following error:
fatal error C1033: cannot open program database ''
If I compile the project myself in visual studios it works fine.
Anyone know why this would be, or how I can fix it?
| I think I have gotten that error in the past when I have an old .pdb file (or one that was somehow corrupted). If so, the error message should indicate which file it is. You should be able to manually delete that file. I think it has often been vc60.pdb.
There is also some information about this error on msdn.
|
2,195,556 | 2,195,682 | Detect Window Move in Property Page (win32) | I implemented a wizard using property sheet. One one page I display tooltip if user enters something invalid. It is a tracking tooltip so I have to manually turn it on and off. Now I want to move the tooltip when the wizard page moves.
It seems that only the property sheet window receives WM_MOVE event from Windows. The page does not. Is there a way to get notified in the page window when the wizard moved?
| The property page isn't moving in relation to its parent window, the property sheet - that's why it's not getting WM_MOVE messages. You can set up a WM_MOVE handler in the property sheet and have it forward another message to the property page with PostMessage or SendMessage. I'd suggest a message in the WM_APP range.
|
2,195,760 | 2,195,779 | Using pThreads, is it possible to write a function that can detect what thread it's being called from? | This is the usage case:
Log(char* s); // prints out a log message
Now:
Log("hello world\n"); // called from Thread1
Desired output:
Thread1: hello world
Now:
Log("hello world\n"); // called from Thread2
Desired output:
Thread2: hello world
I can have a map that maps thread pids to strings. What I need however, is a function that when called form different threads gives me unique identification tags. Is this possible?
Thanks!
(Langauge: C/C++)
| You'll need to pass pthread_self() into your Log() function (or write a macro).
|
2,195,815 | 2,196,516 | How can I extend std::basic_streambuf to treat any iterable sequence as a stream? | Note: Edited based on responses to receive more appropriate answers.
I have a collection of C++ templates that I've made over the years, which I call Joop. It comprises mainly libraries that don't quite fall into the "general-purpose" category but are just useful enough that I keep slapping them into different projects, so most of them don't have equivalents in other libraries such as Boost.
One of these classes is seqstream. The idea is that it allows you to treat any iterable sequence as an ordinary STL-like stream, whose "character type" is the value type of the sequence.
The rationale for this class is twofold. First, it should present an interface that makes any potentially nonlinear, noncontiguous sequence look linear and contiguous; and second, it should treat any object in the stream as though it were a single, complex, large character. There is a standard means of treating a stream as a sequence, so why not the other way around?
At present, seqstream wraps three iterators for the first, last, and current element. I want to replace seqstream with a basic_seqbuf that can be plugged into a standard stream. Can anyone provide resources to get me started on extending std::basic_streambuf to provide this kind of behaviour?
Additionally, if a writable seqbuf is allowed, it is very that writing an object to the seqbuf does not serialise the object, but makes the appropriate call to an insert() method or uses a user-specified insert iterator, such as a std::back_insert_iterator.
Edit:
Here is an example of how seqstream is currently used:
// Create a sequence of objects.
std::vector<std::string> sequence;
for (int i = 0; i < 10; ++i) {
std::ostringstream stream;
stream << "Element " << i << ".";
sequence.push_back(stream.str());
}
// Create a seqstream wrapping that sequence.
joop::seqstream< std::vector<std::string> > seqstream(sequence.begin(), sequence.end());
// Read the sequence like a stream.
std::string element;
while (seqstream >> element) // OR seqstream.get(element)
std::cout << element << '\n';
| It can be confusing to look at the examples in sstream, but you probably don't want a new stream class at all. Looking now for an example at the basic_stringstream source, the only purpose of that class is to
provide str function (it just calls the underlying buffer's str)
avoid the underlying buffer's vtable when calling its methods
change rdbuf's return value to basic_stringbuf* (but that's unnecessary because an accessor for str was provided)
The stream classes do very little, and really aren't supposed to have any functionality besides calling an underlying buffer of type basic_streambuf. For example, I can do this:
string str( "Hello, world!" );
stringbuf buf( str ); // subclass of basic_streambuf
iostream pseudo_stringstream( &buf );
// pseudo_stringstream can do anything a stringstream can do.
// (not necessarily with the same syntax)
Moreover, all streams are supposed to inherit from either basic_istream, basic_ostream, or both. Inserter/extractor functions may not work if your stream doesn't inherit correctly. These inserter declarations are perfectly fine:
operator<<( ostream os, MyData d ); // not a template at all
// templated, but requires correct inheritance:
template< class C > operator<<( basic_ostream<C> os, MyData d );
Therefore, if you want iostream behavior, you need to implement a subclass of basic_streambuf and attach it to a basic_iostream.
But, what is your actual goal? What is the advantage of a memory-backed stream over the usual iterators and maybe some back_insert_iterators? Do you want to use the same code for serialization as for iteration? You probably want to make the stream look like a sequence using stream_iterator, not to make the sequence look like a stream.
|
2,196,052 | 2,196,100 | What is api interception? when is it used? how to implement it in C++ | What is API interception
When is it used
How to implement it in C++
| API interception is intercepting calls to a given DLL and re-directing them through your code.
It is generally used to override some functionality provided by a DLL. An example is for adding a logo to a DirectX based game.
How to implement it? Thats a complicated one and it depends on what sort of DLL you are trying to intercept. You may want do look around here and the net about "DLL Injection" or "API hooking".
e.g 'Safe' DLL Injection
or http://www.codeproject.com/KB/system/hooksys.aspx
|
2,196,121 | 2,196,164 | std::ostringstream woes | I can do
std::ostringstream oss;
oss << 1;
oss.str();
so why can't I do:
((std::ostringstream()) << 1).str() ?
Thanks!
| The << operator returns the base type ostream, while the str member function exists only on the derived type ostringstream.
|
2,196,155 | 2,196,183 | Is there anyway to write the following as a C++ macro? | my_macro << 1 << "hello world" << blah->getValue() << std::endl;
should expand into:
std::ostringstream oss;
oss << 1 << "hello world" << blah->getValue() << std::endl;
ThreadSafeLogging(oss.str());
| #define my_macro my_stream()
class my_stream: public std::ostringstream {
public:
my_stream() {}
~my_stream() {
ThreadSafeLogging(this->str());
}
};
int main() {
my_macro << 1 << "hello world" << std::endl;
}
A temporary of type my_stream is created, which is a subclass of ostringstream. All operations to that temporary work as they would on an ostringstream.
When the statement ends (ie. right after the semicolon on the whole printing operation in main()), the temporary object goes out of scope and is destroyed. The my_stream destructor calls ThreadSafeLogging with the data "collected" previously.
Tested (g++).
Thanks/credits to dingo for pointing out how to simplify the whole thing, so I don't need the overloaded operator<<. Too bad upvotes can't be shared.
|
2,196,205 | 2,196,389 | Composing objects of a class you inherit from? | I have a class Parameter, the purpose of which is to represent the possible values a certain parameter could hold (implements two key methods, GetNumValues() and GetValue(int index)).
Often one logical parameter (parameter values are bit flags) is best represented by 2 or more instances of the Parameter class (i.e. a Parameter that can be 1 or 2, and a Parameter than can be 4 or 8, rather than one Parameter than can be 5, 6, 9, or 10). To handle that, I would like to create a CompositeParameter class which contains Parameters, and will implement the GetNumValues() and GetValue() functions based on the combinations of the Parameters it holds.
And since CompositeParameter is combining Parameters to have them act as one single Parameter, the "CompositeParameter is a Parameter" relationship makes sense. So I find myself in the situation where I have a class which composes objects of a class it inherits from, which just doesn't seem right. But at the same time, I don't see why the higher level code shouldn't be able to treat CompositeParameters and Parameters exactly the same.
The only option I can think of is to have CompositeParameter simply compose Parameters, and the higher level code would only deal with CompositeParameters. However, that is somewhat wasteful b/c the general case would be CompositeParameters which contained just one Parameter.
Thoughts?
class Parameter
{
public:
virtual unsigned int GetNumValues() const {...}
virtual unsigned int GetValue(unsigned int index) const {...}
}
class CompositeParameter : public Parameter
{
public:
// product of GetNumValues() of each item in mParamList
virtual unsigned int GetNumValues() const {...}
// allow all the possible combinations of the items in mParamList to be
// treated as one parameter. i.e. if mNumParams = 2, this would be analogous
// to getting the row and col index of a matrix from index, and combining
// the mParamList[0]->GetValue(row) and mParamList[1]->GetValue(col)
virtual unsigned int GetValue(unsigned int index) const {...}
private:
static const unsigned int MAX_PARAMS = 10;
unsigned int mNumParams;
const Parameter* mParamList[MAX_PARAMS];
}
| I have a class which composes objects of a class it inherits from,
which just doesn't seem right.
Isn't that the definition of a composite?
(parameter values are bit flags)
This is the part of the design that I would question. Perhaps a better name for Parameter would be FlagSet?
It's fine to hide the bitwise tests behind an interface, but it seems like inheritence might be overkill to solve a problem with well known solutions in basic computer science.
However, that is somewhat wasteful b/c the general case would be
CompositeParameters which contained just one Parameter.
The point of the composite pattern is that a Leaf object represents the simple case, a Composite object represents the complex case, and client code can treat both cases the same. If your interface requires the client code to distinguish between the two, or iterate through the base class components, then you're not really getting any value out of using the pattern.
For example, if your main concern is testing, then the base class could have a method:
bool Test() const;
The leaf class implementation would look like:
bool LeafTester::Test() { return _DoTest(); }
The composite class implementation would look like:
bool CompositeTester::Test() {
bool success = true;
for (int i = 0; i < m_count; i++)
success &= m_components[i].Test();
return success;
}
And clients would always use the code like this:
// tester could be a Composite or a leaf, but we don't care:
bool testResult = tester.Test();
I've used a for loop to keep the example simple. In practice I would use STL instead.
|
2,196,300 | 2,196,359 | Installing PySide - OSX | Anyone had success installing and using PySide on OSX? I am following the install instructions on the PySide site, though I'm running into issues building the API Extractor. I run cmake on the CMakeLists.txt file inside the api extractor dir and:
This error is thrown-
CMake Error at /Applications/CMake 2.8-0.app/Contents/share/cmake-2.8/Modules/FindBoost.cmake:894 (message):
Unable to find the requested Boost libraries.
Unable to find the Boost header files. Please set BOOST_ROOT to the root
directory containing Boost or BOOST_INCLUDEDIR to the directory containing
Boost's headers.
Call Stack (most recent call first):
CMakeLists.txt:5 (find_package)
I am new to building source w/ cmake and I'm not event really sure what Boost is. Any light you might shed on the set up process would be great.
Thanks
| It's a set of quite widespread C++ libraries, they're probably needed by PySide, even though I've never tried it.
Download them from there:
http://sourceforge.net/projects/boost/files/boost/1.42.0/
Otherwise, you can install them from macports: http://www.macports.org once you've installed macports, just run "sudo port install boost". Unluckily, pyside itself doesn't seem to be in macports yet.
|
2,196,327 | 2,196,495 | C++ destructor & function call order | Suppose I have the following snipplet:
Foo foo;
....
return bar();
Now, does the C++ standard guarantees me that bar() will be called before foo::~Foo() ? Or is this the compiler/implementation's choice?
Thanks!
| It is guaranteed behaviour. The actual execution is unrolled as follows:
0: enter block (scope)
1: Foo::Foo()
2. evaluation of bar(); as expression in return statement
3. save result of the expression as value returned from function
4. finalize return statement to leave function to its caller (request exit from current scope)
5: exit block (scope) with call to Foo::~Foo()
Here are some references from the standard:
What program execution guarantees, generally
1.9 Program execution
10 An instance of each object with automatic storage duration (3.7.2) is
associated with each entry into its
block.
The foo is of automatic storage duration and:
3.7.2 Automatic storage duration
1 Local objects explicitly declared auto or register or not explicitly declared
static or extern have automatic storage duration. The storage for
these objects lasts until the block in which they are created exits.
What is actual effect of return statement
6.6.3 The return statement
2 (...) the value of the expression is returned to the caller of the function
and
6.6 Jump statements (return belongs to jump statements)
2 On exit from a scope (however accomplished), destructors (12.4) are called for all
constructed objects with automatic storage duration (3.7.2)
What guarantees that the effect occurs
6.7 Declaration statement
2 Variables with automatic storage duration declared in the block are
destroyed on exit from the block
and
12.4 Destructors
10 Destructors are invoked implicitly (1) for a constructed
object with static storage duration
(3.7.1) at program termination
(3.6.3), (2) for a constructed object
with automatic storage duration
(3.7.2) when the block in which the
object is created exits (6.7)
It is not easy to grasp single idea form details scattered around all the C++ standard. Hopefully, quick overview will help you to make such analysis yourself too.
|
2,196,405 | 2,196,445 | Virtual functions with two operands that can take many different types | Let me start with a concrete example. In C++, I have a hierarchy of classes under the abstract base class CollisionVolume. Any collision volume needs to be able to detectCollision with any other volume. This collision code is specialized based on the two subclasses in presence, but it is commutative: detectCollision(a, b) == detectCollision(b, a).
I need to use a mechanism similar to virtual functions since the objects will typically be of the abstract base class. However, if I use typical virtual methods, the chosen function can only depend on the type of one of the operand, not both. The only way I was able to do this is using RTTI or an RTTI-like mechanism.
Is there any cleaner way to do this?
| You're looking for multiple dispatch. C++ doesn't have it because it's hard to implement efficiently. Most other statically typed/efficiency-oriented languages don't either. Your RTTI solution is probably about the best way of faking it.
|
2,196,473 | 2,196,503 | C++ Ramifications of ignoring exception from constructor | I've searched SO for an answer to this, but haven't found one.
When an object throws an exception at the end of the constructor, is the object valid or is this one of those 'depends on the construction technique'?
Example:
struct Fraction
{
int m_numerator;
int m_denominator;
Fraction (double value,
int denominator);
};
Fraction::Fraction(double value, int denominator)
: m_numerator(0), m_denominator(denominator)
{
if (denominator == 0)
{
/* E1 */ throw std::logic_error("Denominator is zero.");
}
m_numerator = static_cast<int>(value * static_cast<double>(denominator));
double actual_value = 0.0;
actual_value = static_cast<double>(m_numerator) / static_cast<double>(m_denominator);
double error = fabs(actual_value - value);
if (error > 5.0E-5)
{
/* E2 */ throw std::logic_error("Can't represent value in exact fraction with given denominator");
}
}
The program:
int main(void)
{
try
{
Fraction f1(3.14159264, 4); // Throws exception, E2 above.
}
catch (...)
{
cerr << "Fraction f1 not exactly representable as fraction with denom. of 4.\n";
}
// At this point, can I still use f1, knowing that it is an approximate fraction?
return EXIT_SUCCESS;
}
In this example, can f1 be used after the exception is caught, knowing that it is an approximate value?
The data members have been constructed and initialized.
I don't see any C++ language rule that is violated by the above.
Edit: Changed error delta value from 5.0E05 to 5.0E-5.
| Jonathan's answer is correct. In addition, while the fraction may be in a valid state, I would not recommend using exceptions for flow control, and especially for communication about the state of an object. Instead, consider adding some kind of is_exactly_representable to your Fraction object API that returns a bool.
|
2,196,725 | 2,200,375 | QueueUserWorkItem with COM in C++ | I have a performance issue where clients are creating hundreds of a particular kind of object "Foo" in my C++ application's DOM. Each Foo instance has its own asynchronous work queue with its own thread. Obviously, that doesn't scale.
I need to share threads amongst work queues, and I don't want to re-invent the wheel. I need to support XP, so I can't use the Vista/Win7 thread pool. The work that needs to be done to process each queue item involves making COM calls in the multi-threaded COM apartment. The documentation for the XP thread pool says that it is okay to call CoInitializeEx() with the MTA apartment in the thread worker function callback. I've written a test app and verified that this works. I made the app run 1 million iterations with and without a CoInitializeEx/CoUninitialize pair in the WorkItem callback function. It takes 35 seconds with the CoInit* calls and 5 seconds without them. That's way too much overhead for my application. Since the thread pool is per-process and 3rd-party code runs in my process, I'm assuming it isn't safe to CoInitializeEx() once per thread and never CoUninitialize().
Given all of that, is there any way that I can use the Win32 thread pool? Am I missing something, or is the XP thread pool pretty useless for high-performance COM applications? Am I just going to have to create my own thread-sharing system?
| Have you verified what is taking so long? i.e. is it the call to CoInitializeEx()? You definitely don't need to call CoInitialize once per task. You also don't say how many threads you spawn, i.e. if your running on a dual core and your work is CPU intensive don't expect more than a 2x speedup, and if your work isn't CPU intensive then it's waiting on some resource (memory, disk, net) and speedups will be similarly constrained, perhaps made worse if there is a lock being held for that resource.
If you can use Visual Studio 2010 take a look at the Parallel Pattern Library and Asynchronous Agents Library, there are a couple tools that can help make this take less code to write.
If you can't you can at least try placing a token in TLS that represents whether COM has been initialized on that thread and use the presence of this token to bypass your calls to CoInitialize when they aren't needed.
|
2,196,841 | 2,197,203 | can I use breakpoints with try catch statements with qt creator? | if an exception is thrown inside a try/catch, can i put a breakpoint there to get into debu mode before the program exits?
| Tested here with a simple code, were I called a function that always throw. The breakpoints inside de catch block not ignored, and the debug mode started normally.
Anyway, qtCreator uses GDB for debugging (At least on my machine). You can find out more about how GDB handle exceptions debugging here http://www.caf.dk/cafonly/gnu/gdb/gdb_31.html
|
2,196,858 | 2,196,894 | End of multi-dimensional array using compact pointer notation | For a 4-D array, I'm trying to average the values using compact pointer notation. Using examples from my text, it says I can use something like this:
void DisplayAverage(double (*set)[DIM1][DIM2][DIM3])
double *ptr;
double subTotal2 = 0;
for (ptr = (double *)set; ptr < (double *)set + DIM0 * DIM1 * DIM2 * DIM3; ptr++) {
subTotal2 += *ptr;
subTotal2 /= (DIM0 * DIM1 * DIM2 * DIM3);
cout << "Using compact pointer operations, total: " << subTotal2 << "\n";
}
}
That code works. However, if I try to use another notation from the text:
for (ptr = (double *)set; ptr < (double *)(&set + 1); ptr++) {
to access the array, I get no output. Any thoughts? Thanks.
| You have one address-of too much:
// notice: "set" instead of "&set"
for (ptr = (double *)set; ptr < (double *)(set + DIM0); ptr++) {
You were adding one to the address of your parameter (and thus were pointing to nowhereland), instead of DIM0 to the value of your parameter (which will bring you to after the array data, which is your goal).
Notice that the parameter is a pointer to an array of dimensions [DIM1][DIM2][DIM3]. In other words, the argument you pass to the function can be an array of type double[DIM0][DIM1][DIM2][DIM3], which will decay to the pointer type of that parameter. You have DIM0 rows, so you add DIM0 to that pointer to reach the position after the last cell.
What you were probably having in mind was adding one to the pointer to the whole array. This will work if you have the following declaration, instead.
void DisplayAverage(double (*set)[DIM0][DIM1][DIM2][DIM3]);
You now need to pass the argument using &arg instead of just arg, to actually pass the address of the array, instead of letting it decay to its inner dimension type. The loop can then be written as
for (ptr = (double *)set; ptr < (double *)(set + 1); ptr++) {
|
2,196,891 | 2,196,921 | Returning an iterator to an element in STL Container | how would you check if the iterator that was returned by the function points to something in container class?
| Iterators are passed around as [begin,end) pairs, with the end value signifying "not found" or other forms of the empty sequence. Return that from your function, or return a pair<bool,iterator> (or similar).
|
2,196,995 | 2,197,015 | Is there any advantage of using map over unordered_map in case of trivial keys? | A recent talk about unordered_map in C++ made me realize that I should use unordered_map for most cases where I used map before, because of the efficiency of lookup ( amortized O(1) vs. O(log n) ). Most times I use a map, I use either int or std::string as the key type; hence, I've got no problems with the definition of the hash function. The more I thought about it, the more I came to realize that I can't find any reason of using a std::map over a std::unordered_map in the case of keys with simple types -- I took a look at the interfaces, and didn't find any significant differences that would impact my code.
Hence the question: is there any real reason to use std::map over std::unordered_map in the case of simple types like int and std::string?
I'm asking from a strictly programming point of view -- I know that it's not fully considered standard, and that it may pose problems with porting.
Also, I expect that one of the correct answers might be "it's more efficient for smaller sets of data" because of a smaller overhead (is that true?) -- hence I'd like to restrict the question to cases where the amount of keys is non-trivial (>1 024).
Edit: duh, I forgot the obvious (thanks GMan!) -- yes, maps are ordered of course -- I know that, and am looking for other reasons.
| Don't forget that map keeps its elements ordered. If you can't give that up, obviously you can't use unordered_map.
Something else to keep in mind is that unordered_map generally uses more memory. map just has a few house-keeping pointers, and memory for each object. Contrarily, unordered_map has a big array (these can get quite big in some implementations), and then additional memory for each object. If you need to be memory-aware, map should prove better, because it lacks the large array.
So, if you need pure lookup-retrieval, I'd say unordered_map is the way to go. But there are always trade-offs, and if you can't afford them, then you can't use it.
Just from personal experience, I found an enormous improvement in performance (measured, of course) when using unordered_map instead of map in a main entity look-up table.
On the other hand, I found it was much slower at repeatedly inserting and removing elements. It's great for a relatively static collection of elements, but if you're doing tons of insertions and deletions the hashing + bucketing seems to add up. (Note, this was over many iterations.)
|
2,197,024 | 2,197,041 | #include confusion and classes | I have been making several games with the Allegro API and C++. I have also been putting all my classes in 1 big main.cpp file. I tried many times to make .h and .cpp files, but my big problem is I have trouble with #including at the right place. For example, I want all my classes to access the allegro library without #including allegro.h everywhere. Could someone please explain how to correctly #include things. In .Net, everything seems to come together, but in c++ one thing cannot be used before it is included. Is there also a way to globally include something throughout my entire program?
Thanks
|
I want all my classes to access the allegro library without #including allegro.h everywhere.
Why? That is how you do it in C++ land.
Could someone please explain how to correctly #include things. In .Net, everything seems to come together, but in c++ one thing cannot be used before it is included
Conceptually, in .NET, it is not much different at all. You still have to place "using " at the top. The difference there is that, in .NET, you could also write this every time if you wanted to:
void Foo( System.Drawing.Drawing2D.BitmapData bData ) { }
|
2,197,141 | 2,197,180 | Function template specialization importance and necessity | I read C++ Primer, and it says function template specialization is an advanced topic, but I am totally lost. Can anybody offer an example why function template specialization is important and necessary?
Why don't function templates support partial specialization while class templates do? What's the underlying logic?
| Basically the idea is that you can write templates that behave in a generic way for the general case, but can still handle special cases. One example of where specialization is used is in std::vector. std::vector<bool> is a specialization that packs the bool elements such that they only use one bit per element, not one byte. std::vector<T> works like a normal dynamic array for all other types.
The more advanced use for specialization is metaprogramming. For example, here's an example (from Wikipedia) of how to use template specialization to compute factorials at compile time.
template <int N>
struct Factorial
{
enum { value = N * Factorial<N - 1>::value };
};
template <>
struct Factorial<0>
{
enum { value = 1 };
};
|
2,197,225 | 2,197,235 | Using string functions (.substr) on arrays of strings | I have an array of strings, and need to grab substrings (the strings in between commas, in this case) and put them into another array of strings.
I declare it as strings[numberOfTapes], so when I am searching for the commas I go character by character in a nested for loop, like so:
for(int j = 0; j < tapes[i].length(); j++){
if(tapes[i][j] == ','){
input[counter2] = tapes[i][j].substr(i-counter, counter);
}
}
For which I get the following error:
request for member 'substr' in tapes[i].std::basic_string::operator[]
[with _CharT = char, _Traits = std::char_traits, _Alloc = std::allocated]
(((long unsigned int)))', which is of non class type 'char'
I'm going through the string character by character with j. Is there a way to get .substr to work with the tapes[i][j] format, or do I need to implement this differently to work?
| tapes[i][j] is the character ',', and that character has no substr method. You probably wanted to call substr on the string object tapes[i], not on the single character.
Also: You call substr(i-counter, counter) after you found a comma at position j. Is that your intention?
|
2,197,412 | 2,197,445 | Reverse C-style String? - C++ | I want to use pointers to reverse a char array in C++. I was wondering if there is anything that I should do differently? Am I doing this correctly? Is there a more efficient way to accomplish this?
My small program:
int main ( )
{
char buffer[80];
PrintHeader();
cout << "\nString reversal program";
cout << "\nType in a short string of words.";
cout << "\nI will reverse them.";
cout << "\n:";
cin.getline(buffer, 79);
cout << "\nYou typed " << buffer;
reverse (buffer);
cout << "\nReversed: " << buffer;
cout << endl;
system("PAUSE");
return 0;
}
void reverse(char* string)
{
char* pStart, *pEnd;
int length;
char temp;
length = strlen(string);
pStart = string;
pEnd = &string[length - 1];
while(pStart < pEnd)
{
temp = *pStart;
*pStart = *pEnd;
*pEnd = temp;
pStart++;
pEnd--;
}
}
| void str_reverse( char *str ) {
char *str_end = strchr( str, 0 );
std::reverse( str, str_end );
}
if you're supposed to write a loop,
void str_reverse( char *str ) {
std::size_t len = std::strlen( str );
for ( std::size_t index = 0; index != len / 2; ++ index ) {
std::swap( str[ index ], str[ len - index - 1 ] );
}
}
or, of course, if you can use a C++ string,
void str_reverse( std::string &str ) {
std::reverse( str.begin(), str.end() );
}
|
2,197,677 | 2,197,713 | Mac vs. Ubuntu for C/C++ development? | I'm looking to buy a personal machine for development and I'm deciding whether to go with a Mac or a PC (on which I'd run Ubuntu). My plans for the next year or so involve getting more heavily into C/C++ and networking than I currently am. Are there any differences I should be aware of between the two OSes as far as C/C++ system libraries and such go?
| If you have a lot of excess cash laying around, get the mac with the option to run Ubuntu in a VM. Otherwise a pc gives just about as much flexibility. As far as the actual development environment, both are going to be similarly good, but Ubuntu might be just a bit more developer friendly: apt certainly does make it easy to get additional libraries, etc. It might also depend on what IDE or tool chain you want to use.
|
2,197,834 | 2,197,861 | Is the following valid C++ code? | If it is, what is it supposed to do?
typedef struct Foo_struct{
Dog d;
Cat* c;
struct Foo_struct(Dog dog, Cat* cat){ this->d = dog; this->c = cat;}
} Foo;
(back story: porting a program written in Visual C++ (on Windows) to g++ (on MacOSX); no idea what this code is suppoesd to do).
Thanks!
| I don't think it is. (And Comeau agrees with me.) You cannot define a constructor like this.
In C++, struct names are first-class citizens. There's no need to employ the old typedef trick from C. Also, d and c should be initialized in a member initialization list. This would be valid (and better (C++):
struct Foo {
Dog d;
Cat* c;
Foo(Dog dog, Cat* cat) : d(dog), c(cat) {}
};
The code defines a struct (in C++, the same as a class, except that its members are public by default) with a constructor to initialize its members upon creation.
Edit: As Travis said in his comment, you might want to consider passing dog as a const reference instead of copying it:
Foo(const Dog& dog, Cat* cat) : d(dog), c(cat) {}
If Dog (which we haven't seen) is a class with more than one built-in member, this might be considerably cheaper than passing it per copy.
|
2,198,146 | 2,198,177 | memory questions, new and free etc. (C++) | I have a few questions regarding memory handling in C++.
What's the different with Mystruct *s = new Mystruct and Mystruct s? What happens in the memory?
Looking at this code:
struct MyStruct{
int i;
float f;
};
MyStruct *create(){
MyStruct tmp;
tmp.i = 1337;
tmp.j = .5f;
return &tmp;
}
int main(){
MyStruct *s = create();
cout << s->i;
return 0;
}
When is MyStruct tmp free'd?
Why doesn't MyStruct tmp get automatically free'd in the end of create()?
Thank you!
| When you use the new keyword to get a pointer, your struct is allocated on the heap which ensures it will persist for the lifetime of your application (or until it's deleted).
When you don't, the struct is allocated on the stack and will be destroyed when the scope it was allocated in terminates.
My understanding of your example (please don't hesitate to inform me if I'm wrong, anyone):
tmp will indeed be "freed" (not the best word choice for a stack variable) at the end of the function since it was allocated on the stack and that stack frame has been lost. The pointer/memory address you return does not have any meaning anymore, and if the code works, you basically just got lucky (nothing has overwritten the old data yet).
|
2,198,163 | 2,198,437 | What are the pros and cons of using Matrices, Euler Angles, and or Quaternions for rotation representation? | Matrices and Euler angles can suffer from Gimbal lock but what are some other arguments for using one over the other?
What do you think DirectX favors?
What do you use in daily C++/C/DirectX programming?
| Euler angles only require three parameters, as opposed to storing a matrix (or three, but that sounds excessive). When you apply the Euler rotation, however, you will possibly end up with something equivalent to three matrix multiplications to create the transformation. If you were only using a matrix, you might not incur such an expensive cost (depending on how the matrix was constructed). Besides Gimbal Lock, there is also a problem with cancellation effects when interpolating matrix representations of rotations that you need to be careful about.
You might want to consider quaternions. They require four parameters of storage, so they are not very heavy. They avoid Gimbal lock and can be interpolated for rendering smooth rotations. One thing that can be interpreted as a downside for the quaternion is that they may not be very intuitive for some. Matrix transformations and Euler angles have a type of roll-yaw-pitch or spin-precession-nutation that is pretty intuitive. Quaternions are more akin to a single rotation about some end-result axis sticking out this or that way.
There are probably cases where someone would prefer one method over the others, so these are just some things to consider when making a decision.
|
2,198,186 | 2,198,221 | Purpose of #ifndef FILENAME....#endif in header file | I know it to prevent multiple inclusion of header file. But suppose I ensure that I will include this file in only one .cpp file only once. Are there still scenarios in which I would require this safe-guard?
| You can guarantee that your code only includes it once, but can you guarantee that anyone's code will include it once?
Furthermore, imagine this:
// a.h
typedef struct { int x; int y; } type1;
// b.h
#include "a.h"
typedef struct { type1 old; int z; } type2;
// main.c
#include "a.h"
#include "b.h"
Oh, no! Our main.c only included each once, but b.h includes a.h, so we got a.h twice, despite our best efforts.
Now imagine this hidden behind three or more layers of #includes and it's a minor internal-use-only header that gets included twice and it's a problem because one of the headers #undefed a macro that it defined but the second header #defined it again and broke some code and it takes a couple hours to figure out why there are conflicting definitions of things.
|
2,198,239 | 2,205,787 | What's the best alternative library to gettimeofday() in C++? | Is there a more Object Oriented alternative to using gettimeofday() in C++ on linux? I like for instance to be able to write code similar to this:
DateTime now = new DateTime;
DateTime duration = new DateTime(2300, DateTime.MILLISECONDS)
DateTime deadline = now + duration;
while(now < deadline){
DoSomething();
delete now;
now = new DateTime()
}
The target is an embedded linux system and there are no Boost libraries, but maybe there is something that is easy to port (something implemented with header files only for example).
| So porting boost wasn't an option for my target. Instead I had to go with gettimeofday(). There are however some nice macros for dealing with timeval structs in sys/time.h
#include <sys/time.h>
void timeradd(struct timeval *a, struct timeval *b,
struct timeval *res);
void timersub(struct timeval *a, struct timeval *b,
struct timeval *res);
void timerclear(struct timeval *tvp);
void timerisset(struct timeval *tvp);
void timercmp(struct timeval *a, struct timeval *b, CMP);
It took a while to find them though because they weren't in the man pages on my machine. See this page:
http://linux.die.net/man/3/timercmp
|
2,198,255 | 2,205,137 | Which kind of cast is from Type* to void*? | In C++ for any data type I can do the following:
Type* typedPointer = obtain();
void* voidPointer = typedPointer;
which cast is performed when I assign Type* to void*? Is this the same as
Type* typedPointer = obtain();
void* voidPointer = reinterpret_cast<void*>( typedPointer );
or is it some other cast?
| It is a standard pointer conversion. Since it is a standard conversion, it doesn't require any explicit cast.
If you want to reproduce the behavior of that conversion with an explicit cast, it would be static_cast, not reinterpret_cast.
Be definition of static_cast given in 5.2.9/2, static_cast can perform all conversions that can be performed implicitly.
|
2,198,316 | 2,198,334 | Why can't I multi-declare a class | I can do this
extern int i;
extern int i;
But I can't do the same with a class
class A {
..
}
class A {
..
}
While in both cases no memory is being allocated.
| The following are declarations:
extern int i;
class A;
And the next two are definitions:
int i;
class A { ... };
The rules are:
a definition is also a declaration.
you have to have 'seen' a declaration of an item before you can use it.
re-declaration is OK (must be identical).
re-definition is an error (the One Definition Rule).
|
2,198,379 | 2,198,400 | Are virtual destructors inherited? | If I have a base class with a virtual destructor. Has a derived class to declare a virtual destructor too?
class base {
public:
virtual ~base () {}
};
class derived : base {
public:
virtual ~derived () {} // 1)
~derived () {} // 2)
};
Concrete questions:
Is 1) and 2) the same? Is 2) automatically virtual because of its base or does it "stop" the virtualness?
Can the derived destructor be omitted if it has nothing to do?
What's the best practice for declaring the derived destructor? Declare it virtual, non-virtual or omit it if possible?
|
Yes, they are the same. The derived class not declaring something virtual does not stop it from being virtual. There is, in fact, no way to stop any method (destructor included) from being virtual in a derived class if it was virtual in a base class. In >=C++11 you can use final to prevent it from being overridden in derived classes, but that doesn't prevent it from being virtual.
Yes, a destructor in a derived class can be omitted if it has nothing to do. And it doesn't matter whether or not its virtual.
I would omit it if possible. And I always use either the virtual keyword or override for virtual functions in derived classes for reasons of clarity. People shouldn't have to go all the way up the inheritance hierarchy to figure out that a function is virtual. Additionally, if your class is copyable or movable without having to declare your own copy or move constructors, declaring a destructor of any kind (even if you define it as default) will force you to declare the copy and move constructors and assignment operators if you want them as the compiler will no longer put them in for you.
As a small point for item 3. It has been pointed out in comments that if a destructor is undeclared the compiler generates a default one (that is still virtual). And that default one is an inline function.
Inline functions potentially expose more of your program to changes in other parts of your program and make binary compatibility for shared libraries tricky. Also, the increased coupling can result in a lot of recompilation in the face of certain kinds of changes. For example, if you decide you really do want an implementation for your virtual destructor then every piece of code that called it will need to be recompiled. Whereas if you had declared it in the class body and then defined it empty in a .cpp file you would be fine changing it without recompiling.
My personal choice would still be to omit it when possible. In my opinion it clutters up the code, and the compiler can sometimes do slightly more efficient things with a default implementation over an empty one. But there are constraints you may be under that make that a poor choice.
|
2,198,471 | 2,198,578 | How to suppress individual warnings in C++? | First of all, sorry if this is an obvious question, but I'm rather new to C++. Also, this code is not originally mine, but I am trying to clean it up.
I'm looking for a compiler independent way to surpress warnings (preferably) for a specific line. I've got the following code:
int MPtag::state_next( int i, int s ){
#if NGRAMS==2
return s+1;
#elif NGRAMS==3
return tag_at(i,0) * num_tags + s+1;
#elif NGRAMS>=4
return tag_at(i,-1) * num_tags*num_tags + tag_at(i,0)*num_tags + s+1;
#endif
}
NGRAMS is currently set to 2.
G++ gives me a warning (with the appropriately paranoid options of course) that the parameter "i" is unused. While this is technically true, it is not always the case. I've thought about commenting out the variable name, but then if NGRAMS were to be changed it would produce a compiler error until uncommented; which is undesirable.
The oldest answer for related question proposes a macro, but another poster say that it is not compiler independent. I've read about #pragma warning but AFAICT that is VS C++ thing. Is there even a proper way to do this?
| The easiest way is of course to make the parameter disappear when not needed, like so:
int MPtag::state_next( int
#if NGRAMS != 2
i
#endif
, int s )
{
#if NGRAMS==2
return s+1;
#elif NGRAMS==3
return tag_at(i,0) * num_tags + s+1;
#elif NGRAMS>=4
return tag_at(i,-1) * num_tags*num_tags + tag_at(i,0)*num_tags + s+1;
#endif
}
This repeats the "knowledge" that i is not needed when NGRAMS is two, but I think it's good enough for such a tiny and highly-localized case.
|
2,198,612 | 2,198,706 | Why is my adjacency list showing duplicate edges? | #include <iostream>
using namespace std;
struct node
{
int v;
node* next;
node (int x, node* t)
{
v = x;
next = t;
}
};
typedef node *link;
int **malloc2d(int, int);
void printMatrix(int **, int);
link *convertToList (int **, link *, int);
void printList (link * a, int size);
// program begins function execution
int main ()
{
// input number of vertices
int i, j, V;
cout << "Enter the number of vertices: ";
cin >> V;
int **adj = malloc2d(V, V); // dynamically allocate matrix
for (i = 0; i < V; i++) // initialize matrix with 0's
for (j = 0; j < V; j++)
adj[i][j] = 0;
for (i = 0; i < V; i++) // initialize diagonal with 1's
adj[i][i] = 1;
// input the edges
cout << "Enter the coordinates for an edge (or 'Ctrl' + 'Z'): ";
while (cin >> i >> j)
{
adj[i][j] = 1;
adj[j][i] = 1;
cout << "Enter the coordinates for an edge (or 'Ctrl' + 'Z'): ";
}
// convert to list
link *aList = new link [V];
aList = convertToList(adj, aList, V);
cout << endl;
// print matrix
cout << "Adjacency Matrix: " << endl;
printMatrix (adj, V);
cout << endl << endl;
// print adjacency list
cout << "Adjacency List: " << endl;
printList (aList, V);
return 0; // indicates successful completion
} // end function main
int **malloc2d(int r, int c)
{
int **t = new int*[r];
for (int i = 0; i < r; i++)
t[i] = new int[c];
return t;
} // end function malloc2d
void printMatrix (int ** a, int size)
{
for (int i = 0; i < size; i++)
for (int j = 0; j < size; j++)
if (a[i][j] == 1)
cout << "There is an edge between " << i << " and "
<< j << "." << endl;
} // end function print
link *convertToList (int ** b, link * a, int size)
{
// create array
for (int i = 0; i < size; i++)
a[i] = 0;
// create lists
for (int i = 0; i < size; i++)
for (int j = i; j < size; j++)
{
if (b[i][j] == 1) // if an edge exists on the matrix
{ // create the edges on the adjacency list
a[j] = new node(i, a[j]);
a[i] = new node(j, a[i]);
}
}
return a;
} // end function convertToList
void printList (link * a, int size)
{
for (int i = 0; i < size; i++)
{
while (a[i]->next != NULL)
{
cout << "There is an edge between " << i << " and "
<< a[i]->v << "." << endl;
a[i] = a[i]->next;
}
}
} // end function print
convertToList: converts an adjacency matrix into an adjacency list.
printList: traverses the adjacency matrix and prints a message for every edge.
Problem: Some edges are being duplicated. I'm not sure if it is a problem when I create the array of lists or when I traverse the adjacency matrix to print it. Any suggestions?
Below is a picture of the program output for 5 vertices with edges (0, 1) and (3, 2). The matrix is correct. The adjacency list is not. Edges (0, 1), (1, 1) and (2, 3) should not be repeated.
| Your print function is also wrong, and it destroys the list while printing without freeing any of the memory. It should read something like this:
void printList (link * a, int size)
{
for (int i = 0; i < size; i++)
{
for (link finger = a[i]; finger != NULL; finger = finger->next)
{
cout << "There is an edge between " << i << " and "
<< finger->v << "." << endl;
}
}
} // end function print
And I think your problem with the adjacency lists is that this code:
for (int j = i; j < size; j++)
{
if (b[i][j] == 1) // if an edge exists on the matrix
{ // create the edges on the adjacency list
a[j] = new node(i, a[j]);
a[i] = new node(j, a[i]);
}
}
should be this:
for (int j = 0; j < size; j++)
{
if (b[i][j] == 1) // if an edge exists on the matrix
{ // create the edges on the adjacency list
a[i] = new node(j, a[i]);
}
}
The code for creating the adjacency lists should mirror the code you have for printing out the matrix.
|
2,198,636 | 2,198,748 | Input output communication between two programs | I have a third party java program called kgsgtp.jar which need to communicate with my own C++ (but mainly just C) program. The documentation for the java program states:
=====================
You just need to make sure that stdin for kgsGtp it connected to
the engine's output and stdout for kgsGtp is connected to the engine's
input. Usually, the easiest way to do this is by forking and execing
kgsGtp from within your engine.
=====================
Now I am a reasonably competent programmer and feel that I could probably arrange all that, given just a few more clues. I suspect that if the description was expanded to erm, 10? lines instead of three and a half then I'd have it sorted in no time.
I'm guessing that what the document means by forking, is using WinExec() or CreateProcess() in my program to execute the java program? I'm also guessing that perhaps when I use the right function, then the fact of one program's stdin corresponding to the other's stdout will happen automatically?
| That description is for unixes, where a sequence of pipe(),dup2(), fork()/exec() calls would be use to do this.
Take a look at the code snippet in the answer from denis here: How do I get console output in C++ with a Windows program? , should get you started.
Edit: more complete example is here: http://support.microsoft.com/kb/190351
|
2,198,908 | 2,198,941 | ofstream - detect if file has been deleted between open and close | I'm wriiting a logger on linux.
the logger open a file on init.
and write to that file descriptor as the program run.
if the log file will be deleted after the file descriptor was created,
no exception/error will be detected .
i have tried:
out.fail()
!out.is_open()
i have google this and find this post .
http://www.daniweb.com/forums/thread23244.html
so i understand now that even if the file was deleted by using rm. it is still exist, it was simply unlinked.
what is the best way to handele this?
1. this is a log application so performance is an issue , i don't want to use stat() on every write
2. i don't care if some of the line in the log files will be missing at the start
3. the user is allowed to delete the log file, to start fresh .the logger should reopen the file.
| Files are 'unlinked' by rm.
A file can have many names. When it has no names left, and nobody has it open, then it is reclaimed by the file system and the space it occupies can be reused.
Linux has an API for 'watching' files called inotify, but this is inviting complexity and race conditions.
So the bigger question is, who else is deleting this file when it is run, and why? Convince them not to!
|
2,198,950 | 2,198,975 | Why is (void) 0 a no operation in C and C++? | I have seen debug printfs in glibc which internally is defined as (void) 0, if NDEBUG is defined. Likewise the __noop for Visual C++ compiler is there too. The former works on both GCC and VC++ compilers, while the latter only on VC++. Now we all know that both the above statements will be treated as no operation and no respective code will be generated; but here's where I've a doubt.
In case of __noop, MSDN says that it's a intrinsic function provided by the compiler. Coming to (void) 0 ~ Why is it interpreted by the compilers as no op? Is it a tricky usage of the C language or does the standard say something about it explicity? Or even that is something to do with the compiler implementation?
| (void)0 (+;) is a valid, but 'does-nothing' C++ expression, that's everything. It doesn't translate to the no-op instruction of the target architecture, it's just an empty statement as placeholder whenever the language expects a complete statement (for example as target for a jump label, or in the body of an if clause).
From Chris Lutz's comment:
It should be noted that, when used as a macro (say, #define noop ((void)0)), the (void) prevents it from being accidentally used as a value (like in int x = noop;).
For the above expression the compiler will rightly flag it as an invalid operation. GCC spits error: void value not ignored as it ought to be and VC++ barks 'void' illegal with all types.
|
2,199,043 | 2,199,956 | C++ Operator overloading example | Well, I'm new to operator overloading, and I found this problem. Instead of documenting myself, I prefer to ask you :D
The point is, I know how to do simple operator overloading, but I'm facing problems with stacking operators. I'll try to put a relatively simple example:
struct dxfdat
{
int a;
string b;
/* here is the question */
}
/* use: */
dxfdat example;
example << "lalala" << 483 << "puff" << 1029 << endl;
"lalala" << 483 << "puff" << 1029 << endl shall be stored in b.
dxfdat& operator<< (T a) and things like that work with one parameter (example << 7), but I would like it to work in a 'cout' fashion.
Sorry to be so lazy.
EDIT:
The real thing... Ok, it is a little bit trickier... actually, b isn't a string, but a vector of other objects, and example << "lalala" << 483 << "puff" << 1029 << endl should just create just one object.
This is what I'm trying (translated), though I have no clue on how to tell it when to create the object (as it goes from left to right, doesn't it?):
struct dxfDato
{
dxfDato(int c = 0, string v = 0, int t = 0) { cod = c; val= v; ty = t; }
int ty;
int cod;
string val;
};
struct dxfItem
{
int cl;
string val;
vector<dxfDato> dats;
vector<dxfItem> sons;
template <class T>
dxfItem &operator<<(const T &t)
{
dxfDato dd;
std::stringstream ss;
ss << t;
val = ss;
dats.push_back(dd); // this way, it creates a lot of objects
return d;
}
};
dxfItem headers;
headers << "lalala" << 54789 << "sdfa" << 483 << endl;
// this should create *just one object* in dats vector,
// and put everything on string val
Thanks for everything,
Note: I had to extract and translate a lot of things to put it here, so I didn't check the code for stupid errors.
(Sorry for expanding the question that much, please tell me if I'm misusing stackoverflow's question system)
| It's quite easy, don't panic :)
You have recognized the problem well: it's very similar to the std::cout - std::endl work.
You could do like such, though I'll rename the types, if you don't mind.
struct EndMarker {};
extern const EndMarker end; // To be defined in a .cpp
class Data
{
public:
Data(): m_data(1, "") {}
// Usual operator
template <class T>
Data& operator<<(const T& input)
{
std::ostringstream aStream;
aStream << input;
m_data.back() += aStream.str();
};
// End of object
Data& operator<<(EndMarker) { m_data.push_back(""); }
private:
std::vector<std::string> m_data;
}; // class Data
It works by adding to the current last element by default, and pushing an empty element at the end.
Let's see an example:
Data data;
data << 1 << "bla" << 2 << end << 3 << "foo" << end;
// data.m_data now is
// ["1bla2", "3foo", ""]
The other solution would be to keep a flag (boolean) to store if a end has been streamed or not, and if it has, creating a new element on the next insertion (and erasing the flag).
It a bit more work on insertion, but you don't have the empty element... your call.
|
2,199,061 | 2,199,231 | LD_DEBUG=files for Windows Visual Studio? | I'm quite stuck on a ddl loader problem under Windows Visual Studio 2009 C++. I have a framwork which loads plugins as DLL files, unfortunatly I have no sourcecode access to the framework. The dependency walker doesn't show any errors, but the framework just says "dependencies not found" when loading the plugin.
I'm quite unfamiliar with debugging under Windows, my next step under Linux would have been to set LD_DEBUG=files and check which DLL's/libraries are loaded.
Is something similar possible under Windows?
| If you use dependency walker it has a menu entry Profile. So if you load the exe to the dependency walker and use profile you might get additional information why dll wasn't resolved.
|
2,199,076 | 2,199,139 | Printf and scanf work without stdio.h, why? |
Possible Duplicate:
Why #include <stdio.h> is not required to use printf()?
Both printf and scanf have been declared in stdio.h. But they work even without that, dropping just a warning message? What's the theory behind this?
| Calling a function without declaring it will create an implicit declaration based on the parameters you give and an assumed return type of int. This lets it get past the compilation stage, since the function could exist somewhere else that isn’t known until link time — C didn’t always have function prototypes, so this is for backwards compatibility. (In C++, it’s an error, and in C99 GCC gives a warning.)
If you look at the man page (on FreeBSD and Darwin, at least) for printf, scanf, puts, etc., it says that it comes from the “Standard C Library (libc, -lc)”. GCC implicitly links with the standard C library. If you link with the -nostdlib flag, you'll get the “undefined symbols” error that you're expecting.
(In fact, when I turn off libc, my GNU/Linux system complains about the absence of _start as well, and my OpenBSD system complains about _start, __guard, and __stack_smash_handler.)
|
2,199,251 | 2,199,390 | What's the point of "typedef sometype sometype"? | Lately I've run into the following construction in the code:
typedef sometype sometype;
Pay attention please that "sometype" stands for absolutely the same type without any additions like "struct" etc.
I wonder what it can be useful for?
UPD: This works only for user defined types.
UPD2: The actual code was in a template context like this:
template <class T>
struct E
{
typedef T T;
...
}
| How about to make Template parameters visible to outside entities?
template <class Foo>
struct Bar
{
typedef Foo Foo;
};
int main()
{
Bar<int>::Foo foo = 4;
}
Note: this is actually not allowed in standard C++, but is specific to MSVC. See comments.
|
2,199,614 | 2,199,662 | C++ How to store collection of templates objects regardless of tempate | I have a problem with implementing database table library. I have a class Column storing different types.
template <class T>
class Column : iColumn<T>
{
...
}
Table is composed of columns, so I need a collection of them (map with string name as a key and column as value). How shall I implement one collection of all table's columns regardless the template type?
Thanks for any hep.
| You should have a common interface.
class Column<T>: public IColumn {
...
};
std::map<std::string,IColumn*> columns;
|
2,199,868 | 2,267,748 | c++ runtime error? how to solve this and check? | #include<iostream>
using namespace std;
int main()
{
int hash, opp, i, j, c = 0;
//cout<<"enter hasmat army number and opponent number\n";
while(cin>>hash>>opp)
{
cout<<opp-hash<<endl;
}
}
time limit for this problem: 3.000 seconds
how can i verify and test this condition?
i'm submitting this to a computer online, how exactly can i know run time error? should i calculate run time and memory?
explain me how to check runtime and memory in c++ in linux, i'm using gcc version 4.4.1 (Ubuntu 4.4.1-4ubuntu9).
| Once you've compiled your program, check its running time by running it with the Unix program time:
time ./myprogram
This will print how much "real" (human) time was taken, and how much CPU (active processing) time.
If you want to check how much memory your program uses, run it in the debugger and set a breakpoint where you want to inspect the memory usage, or just put a long sleep() in your code and run it without the debugger. Then you can use tools like ps or top to see how much memory (virtual, resident, etc.) is in use by your program.
|
2,199,896 | 2,200,087 | Running app as Windows Service reports COM error 80040154 | I'm trying to convert a normal application to a service. The application uses an installed COM component. When its run as a standalone application, this finds and connects to the COM component, however having converted the app to a service, I get the above error.
I understand that this could be related to the fact that in the "environment" of the Services Manager, it's failing to locate the appropriate dlls or registry entries - I'd appreciate any thoughts on how I can "fix" the "environment" of the Services Manager to pickup the appropriate registry entries/dlls (and I believe the box has been restarted after installing the COM component) - this could be also down to the fact that the PATH for the user contains the appropriate directories, and not sure what the PATH for the services manager could be or how to set it... (I'm a unix developer, all this fancy windows stuff is new to me... )
Thanks.
| Clearly your COM server hasn't been properly registered. Once difference for a service is that it usually runs under a different account. Use Regedit.exe and make sure the registration is present in HKLM\Software\Classes\CLSID and not in HKCU. Reregister, this time make sure that you are running Regsvr32.exe in a administrator account with UAC turned off.
|
2,199,951 | 2,216,097 | ComServer that should return a ComObject | What I am trying to do is transfer an object that has been created on the serverside to the client. I have got it to work well when I using c++ on both server and client side, but I do not get my server to work correct with other languages like .Net, It probably doesn't like the pointers!
Does this Serversidecode look correct?
Server Form:
.h
class TForm2 : public TForm
{
__published: // IDE-managed Components
TMemo *Memo1;
private: // User declarations
DummyComObj* formDummy;
public: // User declarations
__fastcall TForm2(TComponent* Owner);
IDummyComObj* Getformdummy();
};
.cpp
__fastcall TForm2::TForm2(TComponent* Owner)
: TForm(Owner)
{
CoCreateInstance( CLSID_DummyComObj,NULL,CLSCTX_ALL,IID_IDummyComObj,(void**)&formDummy);
}
DummyComObj* TForm2::Getformdummy()
{
return formDummy;
}
Server TestComServerImpl:
.cpp
STDMETHODIMP STDMETHODCALLTYPE TServerDidleComTestImpl::GetMyObject(IDummyComObj** outObj)
{
DummyComObj *myDum = Form2->Getformdummy();
*outObj = &myDum;
return S_OK;
}
| Asside from TServerDidleComTestImpl::GetMyObject() not compiling due to you
trying to assign a DummyComObj ** to a DummyComObj*, but you are also
completely ignoring COM reference counting rules.
Try this instead:
Server Form: .h
#include <utilcls.h>
class TForm2 : public TForm
{
__published: // IDE-managed Components
TMemo *Memo1;
private: // User declarations
TComInterface<IDummyComObj> formDummy;
public: // User declarations
__fastcall TForm2(TComponent* Owner);
void Getformdummy(IDummyComObj** outObj);
};
Server Form: .cpp
__fastcall TForm2::TForm2(TComponent* Owner)
: TForm(Owner)
{
CoCreateInstance(
CLSID_DummyComObj,NULL,CLSCTX_ALL,IID_IDummyComObj,(void**)&formDummy);
}
HRESULT TForm2::Getformdummy(DummyComObj** outObj)
{
return formDummy->QueryInterface(IID_IDummyComObj,(void**)outObj);
}
Server TestComServerImpl: .cpp
STDMETHODIMP STDMETHODCALLTYPE
TServerDidleComTestImpl::GetMyObject(IDummyComObj** outObj)
{
return Form2->Getformdummy(outObj);
}
|
2,199,969 | 2,199,999 | Pass the current state of a function into another function in C/C++ | Is there a way to pass the current state of a function into another function in C/C++? I mean all the parameters and local variables by current state. For example:
void funcA (int a, int b)
{
char c;
int d, e;
// Do something with the variables.
// ...
funcB();
// Do something more.
}
void funcB()
{
// funcB() should be able to access variables a,b,c,d & e
// and any change in these variables reflect into funcA().
}
The code is in bad shape if there is a need for funcB() kind of functions. But can it be achieved?
This can help if someone is starting to re-factor a long method with multiple parameters.
| Introduce a common struct.
struct State {
char c;
int d,e;
};
void funcA(int a, int b){
State s;
s.d = 1234; // ...
// ...
funcB(s);
}
void funcB(State& s)
{
//...
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.