Commit 6d266d3e authored by Jason Rhinelander's avatar Jason Rhinelander

algorithms.hpp: range(pair) for range iteration

C++11 doesn't allow: for (auto v : multimap.equal_range(key)) { ... }
because equal_range gives back a pair, which isn't iterable.  Added a
wrapper class and eris::range() function that wraps this pair into an
iterable class, so that I can at least do:

    for (auto v : eris::range(multimap.equal_range(key))) { ... }

This appears to be something that was supported in early C++11 drafts,
but removed
(http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2009/n2977.pdf),
without the suggested solution of having equal_range returning something
iterable actually being implemented.
parent 45a5f5e4
......@@ -76,4 +76,30 @@ all_combinations(
}
}
/** Wrapper class around a pair of iterators that converts the pair into a range, so that a
* for-range statement can be used. The primary target of this is multimap's equal_range method,
* which returns just such a pair. This class is typically invoked via the range() function.
*/
template <class Iter>
class range_ : public std::pair<Iter, Iter> {
public:
range_(std::pair<Iter, Iter> const &pair) : std::pair<Iter, Iter>(pair) {}
Iter begin() const { return this->first; }
Iter end() const { return this->second; }
};
/** Takes a std::pair of iterators that represents a range, and returns an iterable object for that
* range. This is intended to allow for range-based for loops for methods that return a pair of
* iterators representing a range, such as multimap's equal_range() method.
*
* Example:
*
* for (auto &whatever : eris::range(mmap.equal_range(key))) {
* ...
* }
*/
template <class Iter>
range_<Iter> range(std::pair<Iter, Iter> const &pair) {
return range_<Iter>(pair);
}
}
#include <eris/algorithms.hpp>
#include <map>
#include <iostream>
int main() {
std::multimap<int, int> foo;
foo.insert(std::make_pair(3, 4));
foo.insert(std::make_pair(3, 5));
foo.insert(std::make_pair(3, 6));
foo.insert(std::make_pair(4, 7));
foo.insert(std::make_pair(4, 8));
foo.insert(std::make_pair(5, 9));
for (auto f: eris::range(foo.equal_range(3))) {
std::cout << "foo " << f.first << " value: " << f.second << "\n";
}
}
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment