4

Can I use the range for-loop to access the actual iterators instead of the value_type of a container?

Sample code of what I want to do (does not compile, as x is pair ):

#include <iostream>
#include <map>

using namespace std;

std::map<int, float> v;

int main()
{
   for(auto x : v)    
       cout<<x->first<<", "<<x->second<<endl;
   return 0;
}
Babis
  • 147
  • 5
  • 2
    Short answer: no (not unless the items in the container are iterators, and you just want to access them). – Jerry Coffin Dec 14 '13 at 16:21
  • As a side note, you might want to take `x` by const reference (`const auto&`) instead of non-const value (`auto`). – syam Dec 14 '13 at 16:30
  • thanks guys - I just wanted to keep the example simple, my case is a bit more complicated than that – Babis Dec 14 '13 at 16:38
  • possible duplicate of [Range based loop with iterators](http://stackoverflow.com/questions/6953128/range-based-loop-with-iterators) – Ben Voigt Dec 14 '13 at 17:07

2 Answers2

2

No, the range-based for loop abstracts away from iterators. Nevertheless, in your case, you just have to change -> to .:

for(auto x : v)    
    cout<<x.first<<", "<<x.second<<endl;

The range-based for loop exists so that you don't have to deal with iterators. If you do need iterators, you have to write the loop manually, but the actual code is not that much longer:

for (auto it = begin(v), ite = end(v); it != ite; ++it)
  //loop body
Angew is no longer proud of SO
  • 167,307
  • 17
  • 350
  • 455
0

Yes, with an appropriate container adaptor which wraps iterators such that operator*() returns the iterator instead of the value.

I think boost comes with such a wrapper.

Maybe not. But I did find one here on SO: https://stackoverflow.com/a/14920606/103167

And indeed, as Xeo observed, it can be done with Boost, since counting_range performs arithmetic, it works on iterators just as nicely as integers:

for (auto it : boost::counting_range(v.begin(), v.end()))
Community
  • 1
  • 1
Ben Voigt
  • 277,958
  • 43
  • 419
  • 720