标题:一个使用set的示例程序 出处:Felix021 时间:Thu, 12 Mar 2009 23:14:53 +0000 作者:felix021 地址:https://www.felix021.com/blog/read.php?1504 内容: 简单写一下吧: 1. 自定义一个struct t,是set里要放的东西。 2. 定义一个仿函数cmper (仿函数functor,其实就是一个重载了operator()用于比较前述struct的类)。 3. 使用这样的语句: set a; 来定义一个包含struct t的set容器。 4. 使用则样的语句: set::iterator ap; 来定义一个对应的迭代器。 @ 2009-03-16补充:其实重载 bool operator < 也可以,就不需要仿函数了。 具体代码如下: #include #include using namespace std; struct t{ //set里的东西 int i; //可以再增加其他内容,为了简单只写了一个 t(){i = 0;} //构造函数 t(int _i):i(_i){} //构造函数 friend inline ostream & operator <<(ostream &os, const t & a){ //重定向operator <<,纯粹是为了方便输出 return (os << a.i); } }; class cmper{ //仿函数 public: bool operator()(const t &a, const t &b)const{ //重载operator () return a.i < b.i; } }; set a; //定义一个set int main(){ a.insert(t(3)); a.insert(t(1)); a.insert(t(2)); set::iterator ap; //定义一个迭代器 for (ap = a.begin(); ap != a.end(); ap++){ //遍历 cout << (*ap) << endl; } return 0; } //重载example struct t{ int i; bool operator < (const t & a)const{ return i < a.i; }; }; Generated by Bo-blog 2.1.0