sequential container overview(C++ 容器简介)

基本容器有:

vector: flexible sized array, random access
deque: double-ended queue, random access
list: doubly linked list, bi-directional sequential access
forward_list: singly linked list, single directional sequential access
array: fixed size, random access
string: similar to vector, contain characters, fast access

使用原则:

unless you have a reason to use another container, use a vector;
if you have lots of small elements or space overhead matters, don’t use list or forward_list;
require random access, use vector or deque;
need to insert in the middle, use list or forward_list;
insert or delete in the front or back, but not middle, use deque;

container 通用初始化方法:
以string为例:

string s1;
string s2(s1); // == string s2 = s1;
string s3(s2.begin(), s2.end()); // by two iterators
C c{}; // list initialization
string s4("hello"); 
string s5 = "hello";
string s6(10, 'c'); // vector is the same

补充string基本操作:

cin >> s;
cout << s;
getline(cin, s);
s.empty();
s.size();
s[i];
s.push_back('s');
s1 + s2; // concatenation s1 and s2
s1 = s2; //replace s1 with s2
s1 == != < <= > >= s2 // comparison

通用iterator迭代器:

list<int>::iterator iter1 = list.begin();
list<int>::iterator iter2 = list.end();

通用assign and swap:

seq.assign(b, e); // b and e is two iterators
seq.assign(il); // replace elements in seq with initializer list il
seq.assign(n, t); // replace seq with n elements with value t
swap(seq1, seq2);
seq1.swap(seq2);

container 通常支持relational operation
但必须是同一种容器以及同一种类型的元素

== != < > <= >=

通用型resize,除了array都能用

list<int> l;
l.resize(n); // 如果n小于l长度,取前n个,否则不够补0;
l.resize(n, m); //当n大于l长度的时候,不够的补为m

deque: 升级版的stack加上queue

empty();
size();
front();
back();
pop_back(), push_back;
pop_front(), pop_front;
insert(b)
erase(b, e)

list:
基本操作同deque,但是list的erase和insert比deque和vector高效很多。
list和forward_list 不支持下标和.at()操作。
forward_list 没有back类型的操作。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值