C++ 标准模板库STL set 使用方法与应用介绍(一)

本文主要介绍C++标准模板库STL中set和multiset的使用方法,包括容器类的基本构造、常用方法及集合操作,帮助理解其在编程中的应用。
摘要由CSDN通过智能技术生成

这次先看例子程序:


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

int main()
{
    /* type of the collection:
     * - no duplicates
     * - elements are integral values
     * - descending order
     */
    typedef set<int,greater<int> > IntSet;

    IntSet coll1;        // empty set container

    // insert elements in random order
    coll1.insert(4);
    coll1.insert(3);
    coll1.insert(5);
    coll1.insert(1);
    coll1.insert(6);
    coll1.insert(2);
    coll1.insert(5);

    cout<<"typedef set<int,greater<int> > IntSet  由大到小:"<<endl;
    // iterate over all elements and print them
    IntSet::iterator pos;
    for (pos = coll1.begin(); pos != coll1.end(); ++pos)
    {
        cout << *pos << ' ';
    }
    cout << endl;

    // insert 4 again and process return value
    pair<IntSet::iterator,bool> status = coll1.insert(4);
    if (status.second)
    {
        cout << "4 inserted as element "
             << distance(coll1.begin(),status.first) + 1
             << endl;
    }
    else
    {
        cout << "4 already exists" << endl;
    }
    status = coll1.insert(512);
    if (status.second)
    {
        cout << "512 inserted as element "
             << distance(coll1.begin(),status.first) + 1
             << endl;
    }
    else
    {
        cout << "512 already exists" << endl;
    }
    // print all elements of the copy
    cout<<"after pair<IntSet::iterator,bool> status = coll1.insert(4 and 512):"<<endl;
    copy (coll1.begin(), coll1.end(),ostream_iterator<int>(cout," "));
    cout<<endl;
    // assign elements to another set with ascending order
    set<int> coll2(coll1.begin(),coll1.end());
    cout<<"after set<int> coll2(coll1.begin(),coll1.end()) coll2: 由小到大:"<<endl;
    // print all elements of the copy
    copy (coll2.begin(), coll2.end(),ostream_ite
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值