STL set members sorted?

C

chenboston

I am studying STL set and write a small example to understand it. But
my program output does not show that the members are sorted. Could
anyone help me to see what's wrong? Thanks.

// A.h
#include <functional>

class A {
public:
A(int);
int getA();
private:
int a;
};

int compare(A*, A*);

struct Compare : public std::binary_function<A*, A*, bool> {
bool operator()(A *aoo, A *boo) const {
return compare(aoo, boo);
}
};

// A.C
#include "A.h"

A::A(int b) : a(b) {}
int A::getA() { return a; }

int compare(A *aoo, A *boo) {
if (aoo->getA() < boo->getA()) return -1;
if (aoo->getA() > boo->getA()) return 1;
return 0;
}

// Main.C
#include <iostream>
#include <set>
#include "A.h"
using namespace std;

int main() {
set<A *, Compare> aset;
A a2(2), a3(3), a1(1);
aset.insert(&a2); aset.insert(&a3); aset.insert(&a1);
for (set<A *, Compare>::iterator it = aset.begin(); it != aset.end();
it++)
cout << (*it)->getA() << endl;
return 0;
}

$ g++ -o Main Main.C A.C
$ ./Main
1
3
2
 
H

Heinz Ozwirk

int compare(A*, A*);

struct Compare : public std::binary_function<A*, A*, bool> {
bool operator()(A *aoo, A *boo) const {
return compare(aoo, boo);
}
}; ....
int compare(A *aoo, A *boo) {
if (aoo->getA() < boo->getA()) return -1;
if (aoo->getA() > boo->getA()) return 1;
return 0;
}

This does not define a strikt weak ordering, so it is not valid to be used with std::set, std::map or std::multiset. Basically such a function should behave like "less than", but yours implements some sort of "not equal". Change the return statement in operator() above to

return compare(aoo, boo) < 0

HTH
Heinz
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top