9.18
? ? ? ? push_back() 方法
#include<iostream>
#include<deque>
#include<list>
#include<string>
using namespace std;
int main()
{
deque<string> str;
string s;
while (cin>>s)
{
str.push_back(s); //ctrl + z 结束
}
for (deque<string>::iterator it = str.begin(); it != str.end(); ++it)
{
cout << *it << " ";
}
return 0;
}
9.19
???????? push_back() 方法
#include<iostream>
#include<deque>
#include<list>
#include<string>
using namespace std;
int main()
{
list<string> str;
string s;
while (cin>>s)
{
str.push_back(s);
}
for (list<string>::iterator it = str.begin(); it != str.end(); ++it) // it != str.end() 这里,list的话,不能用 < 号比较 ,deque 里可以。
{
cout << *it << " ";
}
return 0;
}
9.20
???????? push_back() 方法
#include<iostream>
#include<deque>
#include<list>
#include<string>
using namespace std;
int main()
{
list<int> nums = {1,2,3,4,5,6,7,8};
deque<int> s1, s2; //s1为奇deque,s2为偶deque
for (auto it=nums.begin();it!=nums.end();++it)
{
if (*it % 2)
{
s1.push_back(*it);
}
else
{
s2.push_back(*it);
}
}
for (auto p = s1.begin(); p != s1.end(); ++p)
{
cout << *p << " ";
}
cout << endl;
for (auto q = s2.begin(); q != s2.end(); ++q)
{
cout << *q << " ";
}
return 0;
}
9.21:
?????????insert()函数返回值是第一个新加入元素的迭代器,即指向新插入元素的迭代器,(c.insert(p,t) : 在迭代器 p 指向的元素之前创建一个值为 t? 或由 args 创建的元素,返回指向新添加的元素的迭代器。)
? ? ? ? 改前:
#include<iostream>
#include<deque>
#include<list>
#include<string>
#include<vector>
using namespace std;
int main()
{
list<string> lst;
string word;
auto iter = lst.begin();
while (cin>>word)
{
iter = lst.insert(iter, word);
}
for (auto p = lst.begin(); p != lst.end(); ++p)
{
cout << *p << " ";
}
return 0;
}
? ? ? ? 改后:
#include<iostream>
#include<deque>
#include<list>
#include<string>
#include<vector>
using namespace std;
int main()
{
vector<string> vec;
string word;
auto vect = vec.begin();
while (cin>>word)
{
vect = vec.insert(vect, word);
}
for (auto p = vec.begin(); p != vec.end(); ++p)
{
cout << *p << " ";
}
return 0;
}
3.22
vector<int>::iterator iter = iv.begin(), mid = iv.begin() + iv.size()/2;
while (iter != mid)
if (*mid == some_val)
iv.insert(mid, 2 * some_val); //会迭代器失效,改为 mid = iv.insert(mid, 2 * some_val);
else
--mid; //mid 在前面已经计算好了,++iter 或 --mid
????????向一个 vector 、string 或 deque 插入元素会使所有指向容器的迭代器、引用或指针失效。(P305)
|