Programming C, C++, Java, PHP, Ruby, Turing, VB
Computer Science Canada 
Programming C, C++, Java, PHP, Ruby, Turing, VB  

Username:   Password: 
 RegisterRegister   
 C++ stack malfunctioning?
Index -> Programming, C++ -> C++ Help
View previous topic Printable versionDownload TopicSubscribe to this topicPrivate MessagesRefresh page View next topic
Author Message
HazySmoke)345




PostPosted: Sat Sep 15, 2007 11:47 am   Post subject: C++ stack malfunctioning?

The following code works perfectly:
code:
#include <cstdio>
#include <stack>
using namespace std;
int main(){
        int a = 345; stack<int> S;
        S.push(a);
        printf ("%d", S.top() == a);
return 0;}

It makes sense. I pushed the value 345 into a stack and compared that value immediately to a.

The following code, even though it's very similar to above, doesn't work:
code:
#include <cstdio>
#include <stack>
using namespace std;
typedef struct{int x, y;}point;
int main(){
        point p; stack<point> S;
        p.x = 345; p.y = -345;
        S.push(p);
        printf ("%d", S.top() == p);
return 0;}


The error says:
testing.cpp:9: error: no match for 'operator==' in '(&S)->std::stack<_Tp, _Sequence>::top [with _Tp = point, _Sequence = std::deque<point, std::allocator<point> >]() == p'

I totally don't get it. Why does the stack.top() method work for one integer but not for a collection of two?
Sponsor
Sponsor
Sponsor
sponsor
Mazer




PostPosted: Sat Sep 15, 2007 12:30 pm   Post subject: RE:C++ stack malfunctioning?

Have you tried defining the == operator for your new structure? I could be wrong, but I don't think it's supposed to provide one by default.
OneOffDriveByPoster




PostPosted: Sat Sep 15, 2007 5:22 pm   Post subject: Re: RE:C++ stack malfunctioning?

Mazer @ Sat Sep 15, 2007 12:30 pm wrote:
Have you tried defining the == operator for your new structure? I could be wrong, but I don't think it's supposed to provide one by default.


Try std::pair<int, int> (#include <utility>)--it's great.
md




PostPosted: Sat Sep 15, 2007 6:55 pm   Post subject: RE:C++ stack malfunctioning?

IIRC the compiler will generate a compare function for any user defined types. What exactly does std::stack<>::top() return? Perhaps it's not returning what you think...

What's wrong with
c++:
struct point { int x, y; };


There is nothing I hate more then needless typedefs.
wtd




PostPosted: Sun Sep 16, 2007 2:43 am   Post subject: RE:C++ stack malfunctioning?

Using std::pair<T> would be the better option.
Display posts from previous:   
   Index -> Programming, C++ -> C++ Help
View previous topic Tell A FriendPrintable versionDownload TopicSubscribe to this topicPrivate MessagesRefresh page View next topic

Page 1 of 1  [ 5 Posts ]
Jump to:   


Style:  
Search: