謹記,但凡使用了迭代器的循環體,都不要向迭代器所屬的容器添加元素!!
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;
}
}