c++ - 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 这样的通用库中是否存在这样的内容?
解决方案
是的,这就是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;
}
标准库中什么都没有,虽然写起来不难。
推荐阅读
- dart - 加载图像时,CircularProgressIndicator 小部件不会消失
- c# - 将像素列表声明为带有附加变量的 blob
- javascript - 使用 Ionic 3 从 Firebase 中删除数据
- c - 在不知道维度的情况下,在 C 中创建指向多维数组的指针
- python - 多处理:使用带有大字典的`pool.starmap`
- javascript - 在 promise.all 完成后执行操作?
- mongodb - 您如何按单位而不是小数截断或舍入数字?
- python - 在 django 中根据基于关系的键、值创建表单
- ios - 如何为分布式应用程序实现非对称加密,其中密钥都可以存储为字符串?
- c++ - 为什么 std::map::emplace 使用会泄漏内存?