写在前面: 我是「虐猫人薛定谔i」,一个不满足于现状,有梦想,有追求的00后
quad
本博客主要记录和分享自己毕生所学的知识,欢迎关注,第一时间获取更新。
quad
不忘初心,方得始终。自己的梦想,终有一天会实现!
quad❤❤❤❤❤❤❤❤❤❤
文章目录
- 顺序容器概述
- 容器库概览
- 顺序容器操作
- 向顺序容器添加元素
- 访问元素
- 删除元素
- 特殊的forward_list 操作
- 改变容器大小
- 容器适配器
- 栈适配器
- 队列适配器

顺序容器概述
顺序容器 为程序员提供了控制存储和访问顺序的能力。元素在顺序容器中的顺序与其加入容器时的位置相对应。
所有顺序容器都提供了快速顺序访问元素的能力。但是,这些容器在以下方面都有不同的性能折中:
- 向容器添加或从容器中删除元素的代价
- 非顺序访问容器中元素的代价
确定使用哪种顺序容器
容器库概览
容器类型上的操作形成了一种层次:
- 某些操作是所有容器类型都提供的
- 另外一些操作仅针对顺序容器、关联容器或无序容器
- 还有一些操作只适用于一小部分容器
迭代器的范围
迭代器的范围被称为左闭合区间
[
b
e
g
i
n
,
e
n
d
)
[begin, end)
[begin,end)
表示范围自begin开始,于end之前结束。迭代器begin和end必须指向相同的容器。end可以与begin指向相同的位置,但不能指向begin之前的位置。
容器定义和初始化
容器赋值运算
顺序容器操作
顺序容器和关联容器的不同之处在于两者组织元素的方式。这些不同之处直接关系到了元素如何存储、访问、添加以及删除。
向顺序容器添加元素
注意: 向一个vector、string或deque插入元素会使所有指向容器的迭代器、引用和指针失效。
容器元素是拷贝
当我们用一个对象来初始化容器时,或将一个对象插入到容器中时,实际上放入到容器中的对象值的一个拷贝,而不是对象本身。就像我们将一个对象传递给非引用参数一样,容器中的元素与提供值的对象之间没有任何关联。随后对容器中元素的任何改变都不会影响到原始对象,反之亦然。
#include <iostream>
#include <list>
using namespace std;
int main()
{
list<string> lst;
auto iter = lst.begin();
string word;
while (cin >> word)
{
iter = lst.insert(iter, word); // 相当于push_front
}
for (auto it = lst.begin(); it != lst.end(); ++it)
{
cout << *it << " ";
}
return 0;
}
访问元素
删除元素
删除元素的成员函数并不检查其参数。在删除元素之前,我们必须确保它(们)是存在的。
例题:循环删除一个list中的所有奇数元素
#include <iostream>
#include <list>
using namespace std;
int main()
{
list<int> lst;
for (int i = 0; i < 100; ++i)
{
lst.push_back(i);
}
auto it = lst.begin();
while (it != lst.end())
{
if (*it % 2)
{
it = lst.erase(it);
}
else
{
++it;
}
}
for (auto it = lst.begin(); it != lst.end(); ++it)
{
cout << *it << " ";
}
return 0;
}
例题:删除偶数元素,复制每个奇数元素
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int> nums;
for (int i = 0; i < 100; ++i)
{
nums.push_back(i);
}
auto iter = nums.begin();
while (iter != nums.end())
{
if (*iter % 2)
{
iter = nums.insert(iter, *iter);
iter += 2;
}
else
{
iter = nums.erase(iter);
}
}
for (auto it = nums.begin(); it != nums.end(); ++it)
{
cout << *it << " ";
}
return 0;
}
特殊的forward_list 操作
#include <iostream>
#include <forward_list>
using namespace std;
int main()
{
forward_list<int> flst = {0,1,2,3,4,5,6,7,8,9};
auto prev = flst.before_begin();
auto curr = flst.begin();
while (curr != flst.end())
{
if (*curr % 2)
{
curr = flst.erase_after(prev);
}
else
{
prev = curr;
++curr;
}
}
for (auto it = flst.begin(); it != flst.end(); ++it)
{
cout << *it << " ";
}
return 0;
}
改变容器大小
容器适配器
除了顺序容器外,标准库还定义了三个顺序容器适配器:stack、queue和priority_queue
默认情况下,stack和queue是基于deque实现的,priority_queue是在vector之上实现的。
每个容器适配器都基于底层容器类型的操作定义了自己的特殊操作。我们只可以使用适配器操作,而不能使用底层容器类型的操作。
栈适配器
队列适配器
奥利给对年轻人的意义,其实,两句诗就能高度概括: 把那些哭泣,悲伤,不堪呼啸出去 再以欢笑的声音返回 ——余秀华《荒原》 这么一个积极向上的主播,他要是倒了,那年轻人们,就又少了一盏炬火。 朝阳怪鸽给我们喊了无数次“加油,奥力给”。 这一次,或许该我们返还一句“加油,奥利给”了。
最后
以上就是爱笑帽子最近收集整理的关于不再恐惧!C++ 顺序容器顺序容器概述容器库概览顺序容器操作容器适配器的全部内容,更多相关不再恐惧!C++内容请搜索靠谱客的其他文章。
发表评论 取消回复