9.2

本节大意
介绍了迭代器的基本使用,以及关于其范围的讨论。

细节摘录
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;
} 


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值