Mar 12

一个使用set的示例程序 不指定

felix021 @ 2009-3-12 23:14 [IT » 程序设计] 评论(1) , 引用(0) , 阅读(5634) | Via 本站原创 | |
简单写一下吧:
1. 自定义一个struct t,是set里要放的东西。
2. 定义一个仿函数cmper (仿函数functor,其实就是一个重载了operator()用于比较前述struct的类)。
3. 使用这样的语句: set<struct t, cmper> a; 来定义一个包含struct t的set容器。
4. 使用则样的语句: set<struct t, cmper>::iterator ap; 来定义一个对应的迭代器。

@ 2009-03-16补充:其实重载 bool operator < 也可以,就不需要仿函数了。

具体代码如下:
#include<iostream>
#include<set>
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<t, cmper> a;  //定义一个set

int main(){
    a.insert(t(3));
    a.insert(t(1));
    a.insert(t(2));
    set<t, cmper>::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;
    };
};




欢迎扫码关注:




转载请注明出自 ,如是转载文则注明原出处,谢谢:)
RSS订阅地址: https://www.felix021.com/blog/feed.php
slyar
2009-3-15 17:59
做个标记,以后也许用的到
分页: 1/1 第一页 1 最后页
发表评论
表情
emotemotemotemotemot
emotemotemotemotemot
emotemotemotemotemot
emotemotemotemotemot
emotemotemotemotemot
打开HTML
打开UBB
打开表情
隐藏
记住我
昵称   密码   *非必须
网址   电邮   [注册]