C++中STL详解(二)

一 set

set翻译为集合,是一个内部自动有序且不含重复元素的容器。

1 set的定义

#include <set>
using namespace std;
set<typename> name;   //typename可以为任何基本类型也可以为容器类型

//set的数组定义
set<int> a[100];      //a[0]-a[99]中的每一个元素都是一个set容器

2 set容器中元素的访问

set只可以通过迭代器访问:

set<int>::iterator it;

得到迭代器it之后,可以通过*it来访问set里的元素。另:除了vector和string,STL容器都不允许使用*(it+i)的方式访问。

#include <iostream>
#include <set>

using namespace std;

int main()
{
    set<int> q;
    q.insert(3);
    q.insert(4);
    q.insert(5);
    q.insert(4);
    for(set<int>::iterator it=q.begin();it!=q.end();it++)
    {
        cout<<*it<<endl;
    }
    return 0;
}

3 set常用函数

(1)insert()

insert(x)可以将x插入到set容器中,并自动递增排序和去重,时间复杂的为O(logN),N为set内的元素个数

(2)find()

find(value)返回set中对应值为value的迭代器,时间复杂的为O(logN)N为set内的元素个数

#include <iostream>
#include <set>

using namespace std;

int main()
{
    set<int> q;
    q.insert(3);
    q.insert(4);
    q.insert(5);
    q.insert(4);

    set<int>::iterator it=q.find(3);
    cout<<*it<<endl;
    return 0;
}

(3)erase()

erase()有2种方法:

1)删除单个元素

q.erase(it)/q.erase(value)

it为迭代器,时间复杂度为O(1),可以结合find函数来使用。

value为所删除元素的值,时间复杂度为O(logN)N为set内的元素个数

#include <iostream>
#include <set>

using namespace std;

int main()
{
    set<int> q;
    q.insert(3);
    q.insert(4);
    q.insert(5);
    q.insert(4);

    set<int>::iterator it=q.find(3);
    q.erase(it);
    q.erase(4);
    for(it=q.begin();it!=q.end();it++)
    {
        cout<<*it<<endl;
    }
    return 0;
}

2)删除一个区间的所有元素

q.erase(first,last)删除[first,last)区间的元素,时间复杂度为O(last-first)

(4)size()

获取元素个数,时间复杂度为O(1)

(5)clear()

清空所有元素,时间复杂度为O(N),N为set中元素个数。

二 multiset

详见博客

三 unordered_set

详见博客

四 pair

详见博客

五 map/multimap/unordered_map

关于map见博客

#include <iostream>
#include <map>

using namespace std;

int main()
{
    map<int,string> student;
    student.insert(pair<int,string>(1,"huihui"));
    student.insert(pair<int,string>(2,"pengpeng"));
    student.insert(pair<int,string>(3,"liuliu"));

    for(map<int,string>::reverse_iterator it=student.rbegin();it!=student.rend();it++)   //注意是it++且reverse_iterator
    {
        cout<<it->first<<":"<<it->second<<endl;
    }
    return 0;
}

关于multimap见博客

关于unordered_map见博客

猜你喜欢

转载自blog.csdn.net/qq_40123329/article/details/86666233