52STL_set&multiset

52STL_set&multiset

基本概念

set&multiset(集与多集) 用来保存大量数据

set——数据不能重复、multiset——数据可以重复

set结构速度较vector结构更快(其使用了二叉树结构)

基本操作

  • insert() 插入后会自动排序
  • count() 和find() count用来统计数据出现的个数,find用来查找数据,但是不能通过find对数据进行修改!
  • erase() 用来删除数据

示例代码

#include <iostream>
#include <set>

using namespace std;

template <typename Container>               //显示模板函数的声明
void PrintContents(const Container &c);

typedef set<int> SETINT;    //定义别名
typedef multiset<int> MSETINT;

int main()
{
    set<int> a;
    multiset<int> ma;

    a.insert(60);
    a.insert(-1);
    a.insert(3000);         //插入后会自动排序
    a.insert(60);           //自动丢弃重复的数据

    PrintContents(a);
//    cout << "显示set里面的数据:" << endl;
//    set<int>:: const_iterator i = a.begin();
//    while(i != a.end())
//    {
//        cout << *i << endl;
//        ++i;
//    }

    ma.insert(3000);
    ma.insert(a.begin(), a.end());  //a中数据全部插入
    ma.insert(3000);                //multiset允许重复

    ma.count(3000);                 //计算3000的个数
    cout << "multiset里有"  << ma.count(3000) << "个3000" << endl;

    PrintContents(ma);

//    cout << "显示multiset里面的数据:" << endl;
//    set<int>:: const_iterator mi = ma.begin();
//    while(mi != ma.end())
//    {
//        cout << *mi << endl;
//        ++mi;
//    }

    SETINT b;

    b.insert(43);
    b.insert(78);
    b.insert(-1);
    b.insert(124);

    SETINT::const_iterator j;

    for(j = b.begin(); j != b.end(); ++j)
        cout << *j << endl;

    //find查找函数

    SETINT::iterator j_found = a.find(-1);     //返回一个迭代器
    if(j_found != b.end())      //检查是否找到
        cout << "找到了:" << *j_found << endl;
    else
        cout << "没找到" << endl;
    cout << endl;

    //不能通过find对数据进行修改

    MSETINT c;
    c.insert(43);
    c.insert(78);
    c.insert(78);
    c.insert(124);
    c.insert(-1);

    MSETINT::const_iterator k;

    cout << "multiset里有" << c.size() << "个数据." << endl;

    PrintContents(c);

    cout << "要删除的数据:";
    int nNumberToErase = 0;
    cin >> nNumberToErase;

    c.erase(nNumberToErase);        //删除数据

    cout << "删除后的数据是:" << endl;
    PrintContents(c);

    c.clear();              //清空
    PrintContents(c);

    return 0;
}

template <typename Container>
void PrintContents(const Container &c)
{
    typename Container::const_iterator i = c.begin();
    while(i != c.end())
    {
        cout << *i << endl;
        ++i;
    }
    cout << endl;
}

发布了59 篇原创文章 · 获赞 3 · 访问量 1837

猜你喜欢

转载自blog.csdn.net/Felix_hyfy/article/details/98397221