18 Aug 2016

c++ tip: 逆序迭代vector时下标类型选取不当引起的程序错误

收藏到CSDN网摘
vector无疑是c++中非常有用的数据结构,实现了通用的迭代器iterator,配合很多STL库函数与算法更是如虎添翼.正序逆序迭代既支持begin(),end(),rbegin(),rend()迭代器遍历,也支持类似于数组的下标遍历[i].今天写代码时遇到程序错误便是由于下标类型选取不当引起的问题.


#include <iostream>
#include <vector>
using namespace std;

int main()
{
vector<int> a;
a.push_back(1);
a.push_back(2);
a.push_back(3);

// all three types can be used to access items from begin to end
// for(vector<int>::size_type i=0;i<a.size();i++)
// for(size_t i=0;i<a.size();i++)
for(int i=0;i<a.size();i++)
{
cout << i << " " << a[i] << endl;
}

// ONLY int can be used to access items from end to begin!!
// for(vector<int>::size_type i=a.size()-1;i>=0;i--)
// for(size_t i=a.size()-1;i>=0;i--)
for(int i=a.size()-1;i>=0;i--)
{
cout << i << " " << a[i] << endl;
}

return 0;
}

No comments :

Post a Comment