在Python中enumerate,有一个序列/迭代器,并产生一对整数索引和值本身.在C++中,我偶尔会发现自己写作
for (size_t i = 0; i != vector.size(); ++i) {
auto const &elem = vector[i];
// ...
Run Code Online (Sandbox Code Playgroud)
与Python类似,我想写
for (auto const &it : enumerate(vector)) {
// it.first is the index (size_t)
// it.second is the element (T const&)
Run Code Online (Sandbox Code Playgroud)
这样的enumerate存在于STL还是像Boost这样的公共库中?
Lig*_*ica 13
是的,这就是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;
}
Run Code Online (Sandbox Code Playgroud)
标准库中没有任何内容,但写起来并不难.