【问题标题】:Python's enumerate in c++Python 在 C++ 中的枚举
【发布时间】:2017-12-23 00:20:51
【问题描述】:

在 Python 中,而不是

colors = ['red', 'green', 'blue', 'yellow']

for i in range(len(colors)):
    print i, '--->', colors[i]

会写

for i, color in enumerate(colors):
    print i, '--->', color

c++中有类似的东西吗?

【问题讨论】:

标签: c++ enumerator


【解决方案1】:

你实际上可以在 c++17 中实现类似的东西。

这是一个草图(c++-ish 伪代码),我在任何地方都使用值,它们应该被适当的引用/转发替换,您还应该修复获取类型的方式(使用 iterator_traits),可能支持未知大小,可能是实现适当的迭代器接口等

template <typename T>
struct EnumeratedIterator {
    size_t index;
    T iterator;
    void operator++() {
        ++iterator;
    }
    std::pair<size_t, T>() {
        return {index, *iterator};
    }
    bool operator !=(EnumeratedIterator o) {
        return iterator != o.iterator;
    }
}

template <typename T>
struct Enumerated {
    T collection;
    EnumeratedIterator<typename T::iterator> begin() {
        return {0, collection.begin()};
    }
    EnumeratedIterator<typename T::iterator> end() {
        return {collection.size(), collection.end()};
    }
}

auto enumerate(T col) {
    return Enumerated<T>(col);
}

然后像这样使用它

for (auto [index, color] : enumerate(vector<int>{5, 7, 10})) {
    assert(index < color);
}

【讨论】:

    【解决方案2】:

    Boost 提供了一个适配器,可以做类似的事情:

    http://www.boost.org/doc/libs/1_63_0/libs/range/doc/html/range/reference/adaptors/reference/indexed.html

    以下代码摘自上面的链接

    #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;
    }
    
    【解决方案3】:

    也许你可以像这样模仿它:

    int i = 0;
    for (auto color : { "red", "green", "blue", "yellow" })
        std::cout << i++ << "--->" << color << std::endl;
    

    【讨论】:

    • 现在运行这个函数两次,你会得到 4,5,6,7 而不是索引
    • @RiaD 这不是函数
    • @KillzoneKid 不,但是这段代码必须放在函数中的某个地方,当它这样做时,static 将导致重复调用该函数时出现问题。只需删除 static 关键字并将 i 初始化移动到循环之前。
    猜你喜欢
    • 2015-08-08
    • 2010-11-26
    • 1970-01-01
    • 1970-01-01
    • 2019-05-01
    • 2011-05-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多