迭代多个seq。 C ++中的容器11 [英] Iterating over more than one seq. container in C++11

查看:97
本文介绍了迭代多个seq。 C ++中的容器11的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要针对以下情况提出一些建议 - 我几个小时都无法弄明白:
如何通过多个seq。容器大小相同(这里:两个向量)的简单方法?

I need a piece of advice for the following situation - I can't figure it out for hours: How to walk through more than one seq . containers of same size (here: two vectors) in a simple way?

int main() {
  int size = 3;
  std::vector<int> v1{ 1, 2, 3 }, v2{ 6, 4, 2 };

  // old-fashioned - ok
  for (int i = 0; i < size; i++) {
    std::cout << v1[i] << " " << v2[i] << std::endl;
  }

  // would like to do the same as above with auto range-for loop
  // something like this - which would be fine for ONE vector.
  // But this does not work. Do I need a hand-made iterator instead?
  for (const auto& i:v1,v2) {
    std::cout << i << " " << i << std::endl;
  }

  return EXIT_SUCCESS;
}

谢谢!

推荐答案

循环的基于范围的被设计为方便迭代一个范围,因为它是迄今为止最常见的情况。如果您需要迭代多个范围(这不是最常见的情况),您仍然可以采用传统方式:

The range-based for loop was designed as a convenience for iterating one range, because it's by far the most common case. If you need to iterate multiple ranges, which is not that most common case, you can still do it the traditional way:

for (auto i1 = begin(v1), i2 = begin(v2), e = end(v1); i1 != e; ++i1, ++i2)
{
  // processing
}

这篇关于迭代多个seq。 C ++中的容器11的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆