序列容器
list容器
list容器是将数据进行链式存储,首先我们要知道链表是什么,链表是由一系列结点组成的、在物理存储单元上非连续的存储结构,数据元素中的逻辑顺序是通过链表中的指针链接实现的,这是因为链表(list)是不支持随机访问的,只支持前置和后移,是一个双向迭代器。不论是插入数据还是删除数据所花费的时间都是固定的,与数据在list容器中的位置无关。
list和vector容器用法基本一样,这里不再做具体介绍。接下来是结合容器的介绍
结合容器
set/mutiset容器
该容器的元素在插入时会进行自动排序,底层是二叉树结构。set不允许有重复数据,mutiset则允许有重复数据。
set容器的构造和赋值、大小等和deque容器差不多,在这里着重说一下利用set容器进行查找和统计。
set容器进行查找和统计
set容器在进行插入数据的时候只有insert可以使用,set有自己独有的接口函数来进行查找和统计数据。
find(i);//查找i是否存在,如果存在则返回该元素的迭代器,否则返回end();
count(i);//统计i的个数
下面看一个例子,比较简单。
#include<iostream>
using namespace std;
#include<set>
void test()
{
set<int>s1;
s1.insert(20);
s1.insert(2);
s1.insert(30);
s1.insert(40);
s1.insert(1);
set<int>::iterator pos = s1.find(40);
if (pos != s1.end())
{
cout << "找到了元素是" << *pos << endl;
}
else
cout << "没找到" << endl;
int num = s1.count(40);
cout << "找到的个数是: " << num << endl;
}
int main()
{
test();
}
运行结果是:
如果是multiset容器的话,就可以插入重复的数据,查找数据返回的数据个数不会只是0和1。
#include<iostream>
using namespace std;
#include<set>
void test()
{
multiset<int>s1;
s1.insert(2);
s1.insert(2);
s1.insert(30);
s1.insert(40);
s1.insert(1);
set<int>::iterator pos = s1.find(2);
if (pos != s1.end())
{
cout << "找到了元素是" << *pos << endl;
}
else
cout << "没找到" << endl;
int num = s1.count(2);
cout << "找到的个数是: " << num << endl;
}
int main()
{
test();
}
得到的结果是:
set排序
set默认排序是从小到大来排列,下面我们尝试从大到小来进行排序,一般使用仿函数来实现。
#include<iostream>
using namespace std;
#include<set>
class MyCompare
{
public:
bool operator()(int v1,int v2)
{
return v1 > v2;
}
};
void test()
{
set<int>s1;
s1.insert(20);
s1.insert(2);
s1.insert(30);
s1.insert(40);
s1.insert(1);
for (set<int>::iterator it = s1.begin(); it != s1.end(); it++)
{
cout << *it << " ";
}
cout << endl;
set<int,MyCompare>s2;
s2.insert(20);
s2.insert(2);
s2.insert(30);
s2.insert(40);
s2.insert(1);
for (set<int, MyCompare>::iterator it = s2.begin(); it != s2.end(); it++)
{
cout << *it << " ";
}
cout << endl;
}
int main()
{
test();
}
还有map容器,大家可以下面了解一下,容器之间大同小异,注意区分即可。