Given a C++ map (or multimap) where the key is an integer, is it possible using STL to request the range of elements whose key is the largest number below a given number?
So if I had:
map = {{1,'x'}, {2, 'g'}, {3, 'n'}, {3, 'm'}, {4, 'z'}, {5, 'a'}}
and I want to find the element(s) just before 4, it would return:
{{3, 'n'}, {3, 'm'}}
(I'm more interested in std::map
but kept the question general for std::multimap
too).
You can use lower_bound()
to find the first element after the ones you want, then decrement the iterator and use equal_range()
to access all the elements matching that one:
#include <iostream>
#include <map>
int main()
{
std::multimap<int, char> const
m{{1,'x'}, {2,'g'}, {3,'n'}, {3,'m'}, {4,'z'}, {5 'a'}};
auto i = m.lower_bound(4);
if (i == m.begin()) {
std::cerr << "No elements less than 4 were found\n";
} else {
--i;
auto const range = m.equal_range(i->first);
for (auto j = range.first; j != range.second; ++j)
std::cout << j->first << ", " << j->second << '\n';
}
}
3, n
3, m
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With