Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can range based for loop work over a range

Tags:

c++

foreach

c++11

If I have range (pair of 2 iterators) is there a way to write "for each" loop for that uses range, not a raw array or container.

Something like this:

auto rng = std::equal_range(v.begin(),v.end(),1984);
for(const auto& elem: rng) {
    // ...
}
like image 474
NoSenseEtAl Avatar asked Mar 20 '13 17:03

NoSenseEtAl


1 Answers

I don't think it will work like that out of the box as equal_range returns a pair of iterators while, the for cycle over range according to documentation are:

The begin_expr and end_expr are defined to be either:
If (__range) is an array, then (__range) and (__range + __bound), where __bound is the array bound
If (__range) is a class and has either a begin or end member (or both), then begin_expr is __range.begin() and end_expr is __range.end();
Otherwise, begin(__range) and end(__range), which are found based on argument-dependent lookup rules with std as an associated namespace.

I would say you may define begin and end functions that take the pair of iterators and return first and second one resepectively.

like image 133
Ivaylo Strandjev Avatar answered Sep 27 '22 18:09

Ivaylo Strandjev