Enumerating Range For in C++11


C++11 has introduced range-for loops that greatly simply the loop process over STL containers and other iterable entities such as arrays or initializers_lists. While this comes handy some times it is needed to have the index of the iterated entity for performing some other operations. The Python equivalent is enumerate.




A simple template class and associated function template can be created for providing this functionality returning a std::pair

Example usage:

template <class F,class L>
std::ostream & operator << (std::ostream & os, const std::pair<F,L> & p)
{
 os << "(" << p.first << "," << p.second << ")";
 return os;
}

int main(int argc, char * argv[])
{
 std::vector<int> w;
 w.push_back(10);
 w.push_back(30);
 w.push_back(40);
 int w2 [] = {10,20,30,40};
 Example e;
 e.q = w;
 Example e2;
 e2.q = w;

 std::cout << "vector container\n";
 for(auto && q: counted(w))
  std::cout << q << std::endl;

 std::cout << "init list\n";
 for(auto && q: counted({10,20,30,40}))
  std::cout << q << std::endl;

 std::cout << "array\n";
 for(auto && q: counted(w2))
  std::cout << q << std::endl;

 std::cout << "iterator pair\n";
 for(auto && q: counted(w.begin(),w.end()))
  std::cout << q << std::endl;

 std::cout << "with begin/end members\n";
 for(auto && q: counted(e))
  std::cout << q << std::endl;

 std::cout << "with begin/end function\n";
 for(auto && q: counted(e2))
  std::cout << q << std::endl;
}

The implementation is straightforward and it is based over a class template parametrized over the value and iterator, that is instantiated by the counted function template that via overload selects different types.

As bonus I have added a range iterator compatible with the range for statement:

for(auto && q: counter(5,20))
 std::cout << q << std::endl;

Source code: https://gist.github.com/eruffaldi/ac0f3d1189d39e237ce1
C++ Shell Link: http://cpp.sh/5buh



Comments

Popular Posts