【发布时间】:2015-10-25 20:55:40
【问题描述】:
我发现自己对何时使用 *it 而不是 it 来迭代 std::vector 感到困惑。是否有任何规则(或容易记住的方法)我可以记住,以免混淆这两种迭代 stl 集合的方法?
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main(){
std::vector<int> x;
x.push_back(3);
x.push_back(5);
for(auto it : x){
std::cout<<it<<std::endl; // Why to use it here and not *it?
}
for( auto it= x.begin(); it!=x.end(); ++it){
std::cout<<*it<<std::endl; // Why to use *it here and not it?
}
}
【问题讨论】:
-
只要
it是需要取消引用的迭代器,就使用*it。和第二个循环一样。 -
for(auto it : x)已经迭代过值,不涉及迭代器。 -
奇怪的问题,如果它的第一个变体类型是int,你怎么能用
*作为int呢?第二个是迭代器。如果您不了解哪种类型是自动的,您可能根本不应该使用“自动”吗?