Babis
Babis

Reputation: 147

Accessing iterators in a range for loop (c++11)

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

Upvotes: 4

Views: 276

Answers (2)

Ben Voigt
Ben Voigt

Reputation: 283883

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()))

Upvotes: 0

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

Upvotes: 2

Related Questions