何时使用 *it 而不是 it 来迭代向量?
When to use *it instead of it for iterating over a vector?
我发现自己对何时使用 *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
给出迭代器对应的值。更好的是,只需使用 range-for 循环:
for (auto& element : vector) {
// `element` is the value inside the vector
}
基于范围的 for
循环在 元素上循环 :
for(auto e : x) {
std::cout << e << std::endl;
}
begin
和 end
返回的迭代器是……好吧……迭代器.
您必须取消引用它们才能获得元素:
for( auto it = x.begin(); it != x.end(); ++it) {
std::cout << *it << std::endl;
}
看看这样的两种迭代方式:
for (auto it = begin(list) ; it != end(list) ; it++) {
auto element = *it;
// do stuff with element
}
for (auto element : list) {
// do stuff with element
}
将第二种方式视为第一种方式的shorthand。
我发现自己对何时使用 *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
给出迭代器对应的值。更好的是,只需使用 range-for 循环:
for (auto& element : vector) {
// `element` is the value inside the vector
}
基于范围的 for
循环在 元素上循环 :
for(auto e : x) {
std::cout << e << std::endl;
}
begin
和 end
返回的迭代器是……好吧……迭代器.
您必须取消引用它们才能获得元素:
for( auto it = x.begin(); it != x.end(); ++it) {
std::cout << *it << std::endl;
}
看看这样的两种迭代方式:
for (auto it = begin(list) ; it != end(list) ; it++) {
auto element = *it;
// do stuff with element
}
for (auto element : list) {
// do stuff with element
}
将第二种方式视为第一种方式的shorthand。