您的位置:首页 > 编程语言 > C语言/C++

C++ Primer学习笔记——顺序容器操作

2016-02-06 15:11 357 查看
插入元素

c.push_back(t)

除了array和forward_list之外每个顺序容器都支持

容器元素是拷贝,容器中的元素和提供的对象之间没有联系

c.push_front(t)

list,forward_list,deque支持

将元素插入到容器头部

c.insert(p,t)

p迭代器指出了在容器什么位置前放置新元素

c.insert(p,n,t)

将n个数量的元素插入到指定位置

c.insert(p,b,e)

b到e范围内的元素插入到p之前

c.insert(p,{…})

insert返回新添加元素的迭代器,或者第一个新元素的迭代器

emplace函数

在容器中直接构造元素,

//9.18
string word;
deque<string> words;
while (cin >> word)
{
words.push_back(word);
}
//9.20
#include<iostream>
#include<list>
#include<deque>
using namespace std;
int main()
{
list<int> l{ 1, 2, 3, 4, 5 };
deque<int> d1, d2;
auto begin = l.begin();
while (begin!=l.end())
{
if ((*begin) % 2 == 0)
{
d1.push_back(*begin);
}

else
d2.push_back(*begin);
begin++;
}
for (auto &s : d1)
cout << s << " ";
}


访问元素

auto val=c.front();//返回拷贝
auto val1=c.back();
auto &val2=c.front();//返回一个元素的引用

auto val3=*(c.begin());
auto val4=*(--c.end());


下标访问注意越界问题

删除元素

c.pop_back()
c.pop_front()//不支持string和vector

c.erase(p);
c.erase(p,q);//返回删除元素后一个的位置

c.clear();


//9.26
#include<iostream>
#include<vector>
#include<list>

using namespace std;
int main()
{
int ia[] = { 0, 1, 1, 2, 3, 5, 8, 13, 21, 55, 89 };
vector<int> vec(ia,ia+11);
list<int> l(ia, ia + 11);
auto it = vec.begin();
auto it2 = l.begin();
while (it!=vec.end())
{
if (*it % 2 == 0)
it=vec.erase(it);//注意erase有返回值
else it++;
}
while (it2 != l.end())
{
if (*it2 % 2 != 0)
it2=l.erase(it2);
else it2++;
}
for (auto &s : vec)
cout << s << " ";
cout << endl;
for (auto &s : l)
cout << s << " ";
}


forward_list 操作

//9.27
forward_list<int> f{ 1,3,4,5,6,7 };
auto pre = f.before_begin();
auto it = f.begin();
while (it != f.end())
{
if (*it % 2 != 0)
it=f.erase_after(pre);
else
{
pre = it;
it++;
}
}


//9.28
#include<iostream>
#include<forward_list>
#include<string>
using namespace std;
bool f(forward_list<string> &flist, string s1, string s2)
{
auto prev = flist.before_begin();
auto curr = flist.begin();
while (curr != flist.end())
{
if (*curr == s1)
{
curr=flist.insert_after(curr, s2);
return 1;
}
else
{
curr++;
}
prev++;
}
flist.emplace_after(prev, s2);
return 0;
}

int main()
{
forward_list<string> fl{ "a", "b", "d" };
bool flag = f(fl, "e", "c");
for (auto &s : fl)
{
cout << s << " ";
}
return 0;
}


改变容器大小

resize()

容器操作可能使迭代器失效
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: