本节大意
介绍了迭代器的基本使用,以及关于其范围的讨论。
细节摘录
1. 算数和关系运算符是vector和deque容器所特有的。
2. 迭代器范围的末端是最后一个元素的下一个元素,而不是最后一个元素。
3. 要特别小心使迭代器失效的操作。
课后习题
1. 错在list容器的迭代器不支持比较操作。
2. 判断容器是否为空。
3.
4. bd是错的
5. it.begin()到it.end(),左闭右开。
6.
7. 有点难,暂留。
8.
9. 头文件该一下,定义部分改改,就可以了。
介绍了迭代器的基本使用,以及关于其范围的讨论。
细节摘录
1. 算数和关系运算符是vector和deque容器所特有的。
2. 迭代器范围的末端是最后一个元素的下一个元素,而不是最后一个元素。
3. 要特别小心使迭代器失效的操作。
课后习题
1. 错在list容器的迭代器不支持比较操作。
2. 判断容器是否为空。
3.
#include <iostream>
#include <list>
using namespace std;
int main()
{
list<int> l;
for (int i=0; i<5; i++) {
l.push_back(i+1);
}
for (list<int> :: iterator it=l.end(); it!=l.begin(); ) {
cout << *(--it) << endl;
}
return 0;
}
4. bd是错的
5. it.begin()到it.end(),左闭右开。
6.
#include <iostream>
#include <vector>
using namespace std;
bool fun(vector<int>::iterator it1, vector<int>::iterator it2, int num)
{
for(vector<int>::iterator it=it1; it!=it2; it++) {
if ((*it) == num) {
return true;
}
}
return false;
}
int main()
{
vector<int> v;
for (int i=1; i<5; i++) {
v.push_back(i);
}
vector<int>::iterator it1 = v.begin(), it2 = v.end();
if (fun(it1, it2, 3)) {
cout << "找到" << endl;
}
else {
cout << "没找到" << endl;
}
return 0;
}
7. 有点难,暂留。
8.
#include <iostream>
#include <vector>
using namespace std;
int main()
{
string s;
vector<string> v;
cout << "输入字符串: " << flush;
while (cin >> s) {
v.push_back(s);
cout << "输入字符串: " << flush;
}
cout << endl << "--------------输出所存字符串---------------" << endl;
for (vector<string>::iterator it=v.begin(); it!=v.end(); it++) {
cout << *it << endl;
}
return 0;
}
9. 头文件该一下,定义部分改改,就可以了。
#include <iostream>
#include <list>
using namespace std;
int main()
{
string s;
list<string> l;
cout << "输入字符串: " << flush;
while (cin >> s) {
l.push_back(s);
cout << "输入字符串: " << flush;
}
cout << endl << "--------------输出所存字符串---------------" << endl;
for (list<string>::iterator it=l.begin(); it!=l.end(); it++) {
cout << *it << endl;
}
return 0;
}