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;
}
4
  • 2
    Short answer: no (not unless the items in the container are iterators, and you just want to access them). Commented Dec 14, 2013 at 16:21
  • As a side note, you might want to take x by const reference (const auto&) instead of non-const value (auto). Commented Dec 14, 2013 at 16:30
  • thanks guys - I just wanted to keep the example simple, my case is a bit more complicated than that Commented Dec 14, 2013 at 16:38
  • possible duplicate of Range based loop with iterators Commented Dec 14, 2013 at 17:07

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.