什么是同时迭代两个或更多容器的最好方法 [英] What's the best way to iterate over two or more containers simultaneously

查看:314
本文介绍了什么是同时迭代两个或更多容器的最好方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C ++ 11提供了多种方法来遍历容器。例如:

C++11 provides multiple ways to iterate over containers. For example:

for(auto c : container) fun(c)



std :: for_each



std::for_each

for_each(container.begin(),container.end(),fun)

但是,建议使用同样大小的两个(或更多)容器来完成类似的操作:

However what is the recommended way to iterate over two (or more) containers of the same size to accomplish something like:

for(unsigned i = 0; i < containerA.size(); ++i) {
  containerA[i] = containerB[i];
}


推荐答案

使用

std::copy_n(contB.begin(), contA.size(), contA.begin())

对于更一般的情况,可以使用Boost.Iterator的 zip_iterator ,有一个小功能,使其可用于基于范围的for循环。在大多数情况下,这将工作:

For the more general case, you can use Boost.Iterator's zip_iterator, with a small function to make it usable in range-based for loops. For most cases, this will work:

template<class... Conts>
auto zip_range(Conts&... conts)
  -> decltype(boost::make_iterator_range(
  boost::make_zip_iterator(boost::make_tuple(conts.begin()...)),
  boost::make_zip_iterator(boost::make_tuple(conts.end()...))))
{
  return {boost::make_zip_iterator(boost::make_tuple(conts.begin()...)),
          boost::make_zip_iterator(boost::make_tuple(conts.end()...))};
}

// ...
for(auto&& t : zip_range(contA, contB))
  std::cout << t.get<0>() << " : " << t.get<1>() << "\n";

Live example。

但是,对于完整的一般性,你可能想要更像 this ,对于没有成员 begin() / end()的数组和用户定义类型, do 在其命名空间中有 begin / 。此外,这将允许用户通过 zip_c ... 函数专门获取 const

However, for full-blown genericity, you probably want something more like this, which will work correctly for arrays and user-defined types that don't have member begin()/end() but do have begin/end functions in their namespace. Also, this will allow the user to specifically get const access through the zip_c... functions.

如果你是一个好主意的错误信息,像我一样,那么你可能想要这个,它检查是否有任何临时容器传递给任何 zip _... 函数,并打印一个不错的错误消息。

And if you're an advocate of nice error messages, like me, then you probably want this, which checks if any temporary containers were passed to any of the zip_... functions, and prints a nice error message if so.

这篇关于什么是同时迭代两个或更多容器的最好方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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