2

I have a Boost multi-index container for storing MyClass members. It has a unique (first_field) and non-unique (second field) indices:

typedef multi_index_container<
MyClass,
indexed_by<
        ordered_unique<member<MyClass, std::string, MyClass.first_field>>,
        ordered_non_unique<member<MyClass &, std::string, MyClass.second_field>>>
> MyClass_Set;

If I search the container by the second index:

auto it = container.get<1>().find("second_field_value_to_be_searched);

I get a const iterator back. How do I iterate over ALL elements in the container that matches the above predicate?

motam79
  • 3,542
  • 5
  • 34
  • 60
  • `container.get<1>()` returns a container view ordered by index 1. `find` returns an iterator into *that* view. You advance it while the predicate holds. – n. m. could be an AI Jun 21 '18 at 03:46

1 Answers1

5

So, use equal_range instead:

auto r = container.get<1>().equal_range("second_field_value_to_be_searched");

This yields a pair of iterators. You can iterate them as usual, or wrap them in an iterator range:

for (auto& record : boost::make_iterator_range(r)) {
}
sehe
  • 374,641
  • 47
  • 450
  • 633
  • 1
    Thanks. There was no way for me to figure this out from the documentation. – motam79 Jun 21 '18 at 22:35
  • BTW, when I iterate through the results. they are not sorted by the first index. Is this expected? – motam79 Jun 21 '18 at 22:54
  • Yes, that's expected. Anyways, `equal_range` is a [concept from STL](https://en.cppreference.com/w/cpp/algorithm/equal_range), which is available on all ordered node-based standard library containers (e.g. [{multi}set](https://en.cppreference.com/w/cpp/container/set/equal_range), [{multi}map](https://en.cppreference.com/w/cpp/container/map/equal_range), obviously more useful on the non-unique variants. Unsurprisingly, the MulitIndex order indices copy that interface: [set operations](https://www.boost.org/doc/libs/1_65_0/libs/multi_index/doc/reference/ord_indices.html#set_operations) – sehe Jun 22 '18 at 10:09
  • If you want items to be ordered by composite key (so e.g. items returned by a query for the first part key are ordered by the second), look at [`composite_key`](https://www.boost.org/doc/libs/1_67_0/libs/multi_index/doc/reference/key_extraction.html#composite_key) which is also described in the [tutorial section](https://www.boost.org/doc/libs/1_67_0/libs/multi_index/doc/tutorial/key_extraction.html#composite_keys). You can also look at some of my examples, [e.g](https://stackoverflow.com/questions/50576367//50579142#50579142) – sehe Jun 22 '18 at 10:17