C++学习札记20140312

本文探讨了在C++中使用迭代器时应注意的关键事项,包括避免在迭代器循环中修改容器大小,如何正确地利用迭代器进行字符串转换,以及通过示例展示了二分搜索算法的实现方式。

谨记,但凡使用了迭代器的循环体,都不要向迭代器所属的容器添加元素!!

vector对象可以动态增长,但不能应用在范围for的语句中对vector对象增加元素,还有任何改变vector对象容量的操作都会使得该对象的迭代器失效!!!

不能解引用迭代器的end成员所指向的元素,因为end是指向迭代器的尾后,解引用就越界操作了

编程练习 要求读入一段文本到vector对象,每个单词存储为vector中的一个元素,把vector对象中每个单词转化为大写字母,输出vector对象中转化后的元素,8个单词为一行,必须使用迭代器访问vector和string对象中的元素

参考程序

#include <iostream>
#include <string>
#include <vector>
#include <cctype>

using namespace std;

int main()
{
	string str;
	vector<string> svec;
	while (cin >> str)
	{
		svec.push_back(str);
	}
	if (svec.size() == 0)
	{
		cout << "NO INPUT!!" << endl;
		return -1;
	}
	static int cnt = 0;
	for (vector<string>::iterator i = svec.begin(); i != svec.end(); i++)
	{
		for (string::iterator index = (*i).begin(); index != (*i).end(); index++)
		{
			if (islower(*index))
			{
				*index = toupper(*index);
				cout << *index;
			}
		}
		cout << ' ';
		cnt++;
		if (cnt % 8 == 0)
		{
			cout << endl;
		}
	}
	return 0;
}

参考程序2

//迭代器加下标运算符
	string str;
	vector<string> svec;
	while (cin >> str)
	{
		svec.push_back(str);
	}
	if (svec.size() == 0)
	{
		cout << "NO WORD" << endl;
		return -1;
	}
	static int cnt = 0;
	for (vector<string>::iterator i = svec.begin(); i != svec.end(); i++)
	{
		for (string::size_type index = 0; index != (*i).size(); index++)
		{
			if (islower((*i)[index]))
			{
				(*i)[index] = toupper((*i)[index]);
				cout << (*i)[index];
			}
		}
		cout << ' ';
		cnt++;
		if ((cnt%8) == 0)
		{
			cout << endl;
		}
	}

使用迭代器经典算法二分搜索

#include <iostream>
#include <string>
#include <vector>
#include <cctype>

using namespace std;

int main()
{
	vector<int> ivec(100);
	for (vector<int>::size_type i = 0; i != ivec.size(); i++)
	{
		ivec[i] = i;
	}
	cout << "Please Input a number You want searching: ";
	int isch;
	cin >> isch;		//输入要搜索的值
	cout << endl;
	auto beg = ivec.begin(), end = ivec.end();
	auto mid = ivec.begin() + (end-beg)/2;		//因为没有两个迭代器相加操作是未定义的,如果相加会出现编译
	while ( mid != end && isch != *mid)
	{
		if (isch < *mid)
		{
			end = mid;
		}
		else
		{
			beg = mid +1;
		}
		mid = beg + (end - beg)/2;
	}
	if (mid == end)
	{
		cout << "Can not find number!!" <<endl;
		return -1;
	}
	if (*mid == isch)
	{
		cout << "Find it!!!" << "    is ";
		cout << mid-ivec.begin() << endl;
		return 0;
	}
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值