您的位置:首页 > 其它

用自己的比较函数构造STL的set

2009-12-01 13:36 369 查看
http://www.cppreference.com/wiki/stl/set/start

set<Key, Compare, Alloc>

The C++ Set is an associative STL container that contains a sorted set of unique objects of type Key. Sorting is done using the key comparison function Compare (default is set to std::less<Key>)

#include<iostream>
#include<set>
#include<iterator>
#include<algorithm>

using namespace std;

class H
{
public:
H(int x=0)
:n(x){}
const int getN() const
{
return n;
}
int setN(int x)
{
int tmp=n;
n=x;
return tmp;
}
ostream & Print(ostream& os) const
{
os << n;
return os;
}

const bool operator<(const H& h)const
{
return n<h.getN();
}

private:
int n;
};

ostream & operator << (ostream &os ,const H &h)
{
return h.Print(os);
}

int main()
{
set<H> s;
int i;

for(i=10;i>0;--i){
s.insert(H(i));
}
copy(s.begin(),s.end(),ostream_iterator<H>(cout," "));
cout << endl;
set<H>::iterator is=s.find(10);
cout << *is << endl;
}

//////////////////////////////////////////////////////////////////////////////////////

#include<iostream>
#include<set>
#include<iterator>
#include<algorithm>

using namespace std;

class H
{
public:
H(int x=0)
:n(x){}
const int getN() const
{
return n;
}
int setN(int x)
{
int tmp=n;
n=x;
return tmp;
}
ostream & Print(ostream& os) const
{
os << n;
return os;
}

private:
int n;
};

ostream & operator << (ostream &os ,const H &h)
{
return h.Print(os);
}

class Hcmp
{
public:
bool operator()(const H& h1,const H& h2) const
{
return h1.getN() < h2.getN();
}
};

int main()
{
set<H,Hcmp > s;
int i;

for(i=10;i>0;--i){
s.insert(H(i));
}
copy(s.begin(),s.end(),ostream_iterator<H>(cout," "));
cout << endl;
set<H>::iterator is=s.find(10);
cout << *is << endl;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: