【问题标题】:When to use *it instead of it for iterating over a vector?何时使用 *it 而不是 it 来迭代向量?
【发布时间】: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呢?第二个是迭代器。如果您不了解哪种类型是自动的,您可能根本不应该使用“自动”吗?

标签: c++ c++11 vector stl auto


【解决方案1】:

基于范围的for元素上循环循环

for(auto e : x) {
    std::cout << e << std::endl;
}

beginend 返回的迭代器是……嗯……迭代器
您必须取消引用它们才能获得一个元素:

for( auto it = x.begin(); it != x.end(); ++it) {
    std::cout << *it << std::endl;
}

【讨论】:

    【解决方案2】:

    it 是迭代器时,*it 给出迭代器对应的值。更好的是,只需使用 range-for 循环:

    for (auto& element : vector) {
        // `element` is the value inside the vector
    }
    

    【讨论】:

      【解决方案3】:

      看看这两种迭代方式:

      for (auto it = begin(list) ; it != end(list) ; it++) {
          auto element = *it;
          // do stuff with element
      }
      
      for (auto element : list) {
          // do stuff with element
      }
      

      将第二种方式视为第一种方式的简写。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2010-11-07
        • 1970-01-01
        • 2011-04-29
        • 1970-01-01
        • 1970-01-01
        • 2012-10-29
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多