在现代C++中,有没有类似于python中基于范围的“enumerate”循环
Is there an equivalent to the range-based `enumerate` loop from python in modern C++?
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
,其中两个成员index
和value
分别表示元素在自适应范围内的位置和值。[…]
该功能以某种形式存在于Python、Rust、Go(备份到该语言中)以及许多C++库中:
ranges-v3
、folly
、boost::ranges
(indexed
)。这一特征的存在或缺乏是反复出现的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;
}
- 为什么在全局范围内使用"extern int a"似乎不行?
- 尝试通过多个向量访问变量时,向量下标超出范围
- 错误:未在此范围内声明'reverse'
- 正在将指针转换为范围
- 使用std::transform将一个范围的元素添加到另一个范围中
- 在基于范围的for循环中使用结构化绑定声明
- 如何计算数据类型的范围,例如int
- 为什么 const std::p air<K,V>& 在 std::map 上基于范围的 for 循环不起作用?
- 在C++中查找范围的长度
- 如何设置一个范围来提取我想要获得的信息
- 并行用于C++17中数组索引范围内的循环
- 为左值和右值的包装器实现C++范围
- 求出有多少个数字是完美平方,而sqrt()是L,R范围内的素数
- 关于:C++中异常对象的范围:为什么我没有得到副本?
- 超出范围时使用对象
- 不计算一个范围内的完美数
- ";结果类型必须是可从输入范围的值类型""构造的;创建std::vector时
- 基于范围的 for 循环:迭代使用一个元素扩展的向量
- 如何访问超出其块范围的对象?
- 在现代C++中,有没有类似于python中基于范围的“enumerate”循环