【问题标题】:Iterating over all pairs of elements in std-containers (C++)迭代标准容器中的所有元素对(C++)
【发布时间】:2009-12-01 08:50:12
【问题描述】:

迭代 std 容器中所有元素对的最佳方法是什么,例如 std::liststd::setstd::vector 等?

基本上做这个的等价物,但使用迭代器:

for (int i = 0; i < A.size()-1; i++)
    for(int j = i+1; j < A.size(); j++)
        cout << A[i] << A[j] << endl;

【问题讨论】:

    标签: c++ stl iterator


    【解决方案1】:

    最简单的方法就是直接重写代码:

    for (auto i = foo.begin(); i != foo.end(); ++i) {
      for (auto j = i; ++j != foo.end(); /**/) {
         std::cout << *i << *j << std::endl;
      }
    }
    

    用 C++98/03 的 const_iterator 替换 auto。或者放在自己的函数中:

    template<typename It>
    void for_each_pair(It begin, It end) {
      for (It  i = begin; i != end; ++i) {
        for (It j = i; ++j != end; /**/) {
           std::cout << *i << *j << std::endl;
        }
      }
    }
    

    【讨论】:

    • auto 不是当前标准的一部分。
    • 没错,这里是懒惰。已添加评论。
    • 实际上,使用 TAD 可能更清洁。
    【解决方案2】:

    只是为了遍历,使用 const_iterators。如果要修改值,请使用迭代器。

    例子:

    typedef std::vector<int> IntVec;
    
    IntVec vec;
    
    // ...
    
    IntVec::const_iterator iter_cur = vec.begin();
    IntVec::const_iterator iter_end = vec.end();
    while (iter_cur != iter_end) {
        int val = *iter_cur;
        // Do stuff with val here
        iter_cur++;
    }
    

    【讨论】:

      猜你喜欢
      • 2010-12-21
      • 2023-02-22
      • 1970-01-01
      • 2015-06-06
      • 2010-09-23
      • 2015-05-11
      • 1970-01-01
      • 2012-03-28
      相关资源
      最近更新 更多