谨记,但凡使用了迭代器的循环体,都不要向迭代器所属的容器添加元素!!
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;
}
}