Python's enumerate for C++ [duplicate]

  • A+
Category:Languages

This question already has an answer here:

In Python there is enumerate which takes a sequence/iterator and yields pairs of an integer index and the value itself. In C++ I occasionally find myself writing

for (size_t i = 0; i != vector.size(); ++i) {     auto const &elem = vector[i];     // ... 

Similar to Python I would like to write

for (auto const &it : enumerate(vector)) {     // it.first is the index (size_t)     // it.second is the element (T const&) 

Does such an enumerate exist in either the STL or a common library like Boost?

 


Yes, this is what Boost's adapators::indexed does.

Their example (which also uses the now-redundant Boost.Assign for terse container initialisation) follows:

#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; } 

Nothing in the standard library, though it's not hard to write.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: