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
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