可能重复:
为什么要使用迭代器而不是数组下标?
我正在回顾我的C++知识,遇到了迭代器这个概念。我想知道它们有什么特殊之处,以及为什么要使用它们:
using namespace std;
vector<int> myIntVector;
vector<int>::iterator myIntVectorIterator;
// Add some elements to myIntVector
myIntVector.push_back(1);
myIntVector.push_back(4);
myIntVector.push_back(8);
for(myIntVectorIterator = myIntVector.begin();
myIntVectorIterator != myIntVector.end();
myIntVectorIterator++)
{
cout<<*myIntVectorIterator<<" ";
//Should output 1 4 8
}
比这个更好:
using namespace std;
vector<int> myIntVector;
// Add some elements to myIntVector
myIntVector.push_back(1);
myIntVector.push_back(4);
myIntVector.push_back(8);
for(int y=0; y<myIntVector.size(); y++)
{
cout<<myIntVector[y]<<" ";
//Should output 1 4 8
}
是的,我知道我不应该使用std命名空间。我只是从cprogramming网站上拿了这个例子。那么你能告诉我后者为什么更糟糕吗?有什么大的区别吗?