在现代C++中,有没有类似于python中基于范围的“enumerate”循环

Is there an equivalent to the range-based `enumerate` loop from python in modern C++?

本文关键字:范围 enumerate 循环 C++ 有没有 python 类似于 于范围      更新时间:2023-10-16

C++中是否存在与python中基于范围的enumerate循环等价的循环?我会想象这样的事情。

enumerateLoop (auto counter, auto el, container) {
    charges.at(counter) = el[0];
    aa.at(counter) = el[1];
}

这可以用模板或宏来完成吗?

我知道我可以使用一个老派的循环和迭代,直到我达到container.size()。但我感兴趣的是如何使用模板或宏来解决这个问题。

编辑

在注释中的提示之后,我使用了一些boost迭代器。我用C++14得到了另一个可行的解决方案。

template <typename... T>
auto zip(const T &... containers) -> boost::iterator_range<boost::zip_iterator<
decltype(boost::make_tuple(std::begin(containers)...))>> {
  auto zip_begin =
    boost::make_zip_iterator(boost::make_tuple(std::begin(containers)...));
  auto zip_end =
    boost::make_zip_iterator(boost::make_tuple(std::end(containers)...));
  return boost::make_iterator_range(zip_begin, zip_end);
}
template <typename T>
auto enumerate(const T &container) {
return zip(boost::counting_range(0, static_cast<int>(container.size())),
container);
} 

https://gist.github.com/kain88-de/fef962dc1c15437457a8

自C以来,枚举多个变量一直是一种习惯用法。唯一复杂的是,不能在for循环的初始值设定项中声明这两个变量。

int index;
for (auto p = container.begin(), index = 0; p != container.end(); ++p, ++index)

我不认为它比这更简单(或更强大)。

boost中有一个C++11之前的解决方案:boost.range.indexed。不幸的是,它不适用于基于C++11范围的for循环,只适用于旧式的详细循环。然而,使用C++17,它应该(几乎)像使用结构化绑定的python一样简单

然后应该可以实现这样的功能:

for (auto& [n,x] : enumerate(vec)) x = n;

所以,还有一点等待;)

我不久前为此写了一些东西。

从本质上讲,您需要包装迭代器并赋予它成对语义。

AFAIK,语言中没有这样的东西。我认为boost也没有。你几乎必须自己滚。

// Wraps a forward-iterator to produce {value, index} pairs, similar to
// python's enumerate()
template <typename Iterator>
struct EnumerateIterator {
private:
  Iterator current;
  Iterator last;
  size_t index;
  bool atEnd;
public:
  typedef decltype(*std::declval<Iterator>()) IteratorValue;
  typedef pair<IteratorValue const&, size_t> value_type;
  EnumerateIterator()
    : index(0), atEnd(true) {}
  EnumerateIterator(Iterator begin, Iterator end)
    : current(begin), last(end), index(0) {
    atEnd = current == last;
  }
  EnumerateIterator begin() const {
    return *this;
  }
  EnumerateIterator end() const {
    return EnumerateIterator();
  }
  EnumerateIterator operator++() {
    if (!atEnd) {
      ++current;
      ++index;
      atEnd = current == last;
    }
    return *this;
  }
  value_type operator*() const {
    return {*current, index};
  }
  bool operator==(EnumerateIterator const& rhs) const {
    return
      (atEnd && rhs.atEnd) ||
      (!atEnd && !rhs.atEnd && current == rhs.current && last == rhs.last);
  }
  bool operator!=(EnumerateIterator const& rhs) const {
    return !(*this == rhs);
  }
  explicit operator bool() const {
    return !atEnd;
  }
};
template<typename Iterable>
EnumerateIterator<decltype(std::declval<Iterable>().begin())> enumerateIterator(Iterable& list) {
  return EnumerateIterator<decltype(std::declval<Iterable>().begin())>(list.begin(), list.end());
}
template<typename ResultContainer, typename Iterable>
ResultContainer enumerateConstruct(Iterable&& list) {
  ResultContainer res;
  for (auto el : enumerateIterator(list))
    res.push_back(move(el));
  return res;
}

C++17和结构化绑定使其看起来不错-当然比一些带有本地[i = 0](Element&) mutable的丑陋可变lambda或我之前所做的任何事情都要好,我承认可能不是所有东西都应该硬塞进for_each()等人-也比其他需要在for循环之外具有作用域的计数器的解决方案要好。

for (auto [it, end, i] = std::tuple{container.cbegin(), container.cend(), 0};
     it != end; ++it, ++i)
{
      // something that needs both `it` and `i`ndex
}

如果你经常使用这种模式,你可以让它变得通用:

template <typename Container>
auto
its_and_idx(Container&& container)
{
    using std::begin, std::end;
    return std::tuple{begin(container), end(container), 0};
}
// ...
for (auto [it, end, i] = its_and_idx(foo); it != end; ++it, ++i)
{
    // something
}

C++标准建议P2164建议添加views::enumerate,这将为迭代它的用户提供一个范围的视图,同时给出元素的引用和元素的索引

我们提出了一个视图enumerate,其值类型为struct,其中两个成员indexvalue分别表示元素在自适应范围内的位置和值。

[…]

该功能以某种形式存在于Python、Rust、Go(备份到该语言中)以及许多C++库中:ranges-v3follyboost::rangesindexed)。

这一特征的存在或缺乏是反复出现的stackoverflow问题的主题。

嘿,看!我们很出名。

您还可以更优雅地使用自C++11:以来可用的自动范围

int i = 0;
for (auto& el : container){
    charges.at(counter) = el[0];
    aa.at(counter) = el[1];
    ++i;
}

不过,你仍然需要手动计算i

这里有一个基于宏的解决方案,它可能在简单性、编译时间和代码生成质量方面胜过大多数其他解决方案:

#include <iostream>
#define fori(i, ...) if(size_t i = -1) for(__VA_ARGS__) if(i++, true)
int main() {
    fori(i, auto const & x : {"hello", "world", "!"}) {
        std::cout << i << " " << x << std::endl;
    }
}

结果:

$ g++ -o enumerate enumerate.cpp -std=c++11 && ./enumerate 
0 hello
1 world
2 !

Tobias Widlund写了一个很好的MIT许可Python风格的头仅枚举(不过是C++17):

GitHub

博客文章

真的很好用:

std::vector<int> my_vector {1,3,3,7};
for(auto [i, my_element] : en::enumerate(my_vector))
{
    // do stuff
}

Boost::Range自1.56起支持此功能。

#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 : index(input, 0)) // function version
    for (const auto& element : input | indexed(0))      
    {
        std::cout << "Element = " << element.value()
                  << " Index = " << element.index()
                  << std::endl;
    }
    return 0;
}