首页 > 解决方案 > Python 的 C++ 枚举

问题描述

在 Python 中,enumerate它接受一个序列/迭代器并产生一对整数索引和值本身。在 C++ 中,我偶尔会发现自己在写

for (size_t i = 0; i != vector.size(); ++i) {
    auto const &elem = vector[i];
    // ...

类似于 Python 我想写

for (auto const &it : enumerate(vector)) {
    // it.first is the index (size_t)
    // it.second is the element (T const&)

enumerate在 STL 或像 Boost 这样的通用库中是否存在这样的内容?

标签: c++c++11

解决方案


是的,这就是Boost 的adapators::indexed所做的。

他们的示例(也使用现在冗余的 Boost.Assign 进行简洁的容器初始化)如下:

#include <boost/range/adaptor/indexed.hpp>
#include <boost/assign.hpp>
#include <iterator>
#include <iostream>
#include <vector>


int main(int argc, const char* argv[])
{
    using namespace boost::assign;
    using namespace boost::adaptors;

    std::vector<int> input;
    input += 10,20,30,40,50,60,70,80,90;

    for (const auto& element : input | indexed(0))
    {
        std::cout << "Element = " << element.value()
                  << " Index = " << element.index()
                  << std::endl;
    }

    return 0;
}

标准库中什么都没有,虽然写起来不难


推荐阅读