STL set使用例子

时间:2023-01-12 19:39:17

#include<iostream>
#include<set>
using namespace std;

#include<stdlib.h>

#define random rand()

class Edge
{
private:
float errorMetric;
public:
float getErrorMetric() const {return errorMetric;}
Edge(float error):errorMetric(error){}
};

struct lsEdge
{
bool operator() (const Edge& e1, const Edge& e2)
{
if(e1.getErrorMetric()<e2.getErrorMetric()) return true;
else return false;
}

bool operator() (const Edge* e1, const Edge* e2)
{
if(e1->getErrorMetric()<e2->getErrorMetric()) return true;
else return false;
}
};

typedef set<Edge,lsEdge> EdgeSet;
typedef set<Edge*,lsEdge> EdgePSet;
int main()
{
EdgeSet es;
for(int i=0;i<10;i++)
{
Edge e(i%2 + random);
es.insert(e);
}

EdgeSet::iterator it = es.begin();
for(it;it!=es.end();it++)
{
cout<<(*it).getErrorMetric()<<endl;
}
cout<<"-----------"<<endl;
EdgePSet eps;
for(int i=0;i<10;i++)
{
Edge * e = new Edge(random);
eps.insert(e);
}
for(EdgePSet::iterator it=eps.begin();it!=eps.end();it++)
{
cout<<const_cast<Edge*>(*it)->getErrorMetric()<<endl;
}

return 0;
}