1.STL中迭代器的使用
C++迭代器使用错误总结
注意:
1.使用迭代器可以十分方便的变量容器中的元素
2.使用迭代器时无法输出元素所在的位置,只能知道元素在内存中的地址
3.对于vector,可以直接利用下标来访问元素
(1)输出Vector的中的元素
vector vecClass;
int nSize = vecClass.size();
//打印vecClass,方法一:
for(int i=0;i<nSize;i++)
{
cout<<vecClass[i]<<" ";
}
cout<<endl;
需要注意的是:以方法一进行输出时,数组的下标必须保证是整数。
//打印vecClass,方法二:
for(int i=0;i<nSize;i++)
{
cout<<vecClass.at(i)<<" ";
}
cout<<endl;
//打印vecClass,方法三:输出某一指定的数值时不方便
for(vector<float>::iterator it = vecClass.begin();it!=vecClass.end();it++)
{
cout<<*it<<" ";
}
cout<<endl;
(2)使用正向迭代器反向迭代会出现问题,因为end()是不允许被访问的
错误的使用方法
vector<char>::iterator it;
for (it = str.end(); it != str.begin(); --it) {
cout << *it << " ";
}
end()访问不到,越界
正确的使用方法
#include <iostream>
#include <list>
using namespace std;
int main()
{
// list container for character elements
list<char> coll;
// append elements from 'a' to 'z'
for (char c='a'; c<='z'; ++c) {
coll.push_back(c);
}
list<char>::const_iterator pos;
for (pos = coll.begin(); pos != coll.end(); ++pos) {
cout << *pos << ' ';
}
cout << "\n";
//用正向迭代器倒序输出。
for (pos = --coll.end(); pos != --coll.begin(); --pos) {
cout << *pos << ' ';
}
cout << endl;
}
输出结果为
a b c d e f g h i j k l m n o p q r s t u v w x y z
z y x w v u t s r q p o n m l k j i h g f e d c b a