循环访问C++中的对象对(或更多)
Iterating through pairs (or more) of objects in C++
我知道你可以像这样循环访问一个容器:
for(double x : mycontainer)
这类似于Python的
for x in mylist:
但是,有时我需要访问另一个具有相同索引的容器中的元素,并且我必须创建一个普通的 for 循环。或者,在 Python 中,我可以做(对于两个或多个列表):
for (x,y) in zip(xlist, ylist):
C++有类似的东西吗?
我知道
的最接近的东西是boost::combine
(虽然,我没有看到它的文档 - 实际上,有添加它的trac票)。它在内部使用boost::zip_iterator
,但更方便:
现场演示
#include <boost/range/combine.hpp>
#include <iostream>
int main()
{
using namespace boost;
using namespace std;
int x[3] = {1,2,3};
double y[3] = {1.1, 2.2, 3.3};
for(const auto &p : combine(x,y))
cout << get<0>(p) << " " << get<1>(p) << endl;
}
输出为:
1 1.1
2 2.2
3 3.3
我知道的最
接近的类似物是 Boost 的 zip 迭代器。
在典型情况下,您将boost::make_zip_iterator
与boost:make_tuple
一起使用,因此最终会得到如下结果:
boost::make_zip_iterator(boost:make_tuple(xlist.begin(), ylist.begin()))
和:
boost::make_zip_iterator(boost::make_tuple(xlist.end(), ylist.end()))
不幸的是,这比Python版本要冗长得多,但有时这就是生活。
相关文章:
- 按基类对象访问派生类资源时出错
- 使用基类对象访问派生的仅类方法
- 从 const 对象访问非 const 方法
- 如何在C++中使用类对象访问指针数据成员
- 如何通过不同的指针使用类的对象访问结构?(链表)(C++)
- 使用二进制搜索树中的迭代器对象访问左侧节点
- 为什么引用类型在使用临时对象访问时是左值
- 从父对象 c++ 访问子方法
- 无法通过指针或对象 c++ 访问受保护的成员
- 为什么可以从类中的对象访问类的私有变量
- 对类似"struct {double, int}"对象使用reinterpret_cast进行对象访问
- 通过无符号 char 别名进行对象访问,加载和存储时会发生什么?
- 从对象访问结构枚举
- 如何全局创建对象并使用该对象访问全局范围内的公共成员函数
- 在C 中,可以从第三个共享对象访问其他两个不同共享对象
- 如何在C 中提供一个可呼叫的对象访问,例如lambda
- C 向量对象访问
- C++是否可以从同级第二个派生对象访问第一个派生对象的受保护基础数据成员?
- 如何从类内实例化的对象访问私有变量
- 多态性:通过类文本或对象访问静态成员