Find elements with a key less than the specified one. Multimap

How can I get(find) an element by entering the variable int k through the console, and getting auto itr, so that the code for finding elements with the lowest key is executed? Or is it somehow generally in a different way to implement? ps Sorry and understand if something is clumsy and so on, a beginner.

int main() {
    multimap<int, int> myMultimap;

    for (;;) {
    //...
        case  3: { //Поиск первого элемента с ключом, меньшим заданному ключу
            cout << "Задайте ключ, чтобы найти элементы с ключом, меньшим заданному ключу:\n";
            cin >> k;

            //То что я написал и пытаюсь исполнить для поиска элементов с наименьшим ключом
            multimap<int, int>::key_compare comp = myMultimap.key_comp();
            //auto itr = myMultimap.find(k);
            multimap<char, int>::iterator itr = myMultimap.find(k);
            auto it = myMultimap.begin();
            do {
                cout << (*it).first << " : " << (*it).second << '\n';
            } while (comp((*it++).first, itr));


            //пытался сделать что-то такое, но не такое...
            //for (auto it = myMultimap.begin(); it < myMultimap(i); ++it)
            //{
            //  cout << it->first << " : " << it->second << endl;
            //}
        }
    ///...
}
Author: Harry, 2020-05-14

2 answers

Iterating through all elements with a key, strictly less than k:

for(auto it = myMultimap.begin(); it != myMultimap.lower_bound(k); ++it)
{
    cout << it->first << " : " << it->second << '\n';
}

That's all, you don't have to suffer and compare yourself... In principle, to speed up, you can write

for(auto end = myMultimap.lower_bound(k), it = myMultimap.begin(); it != end; ++it)

Description lower_bound - here.

 4
Author: Harry, 2020-05-15 05:19:13
auto it = myMultimap.begin()
for (; it != myMultimap.end() && it->first < k; it++) 
{
    cout << it->first << " : " << it->second << endl;
}

Iterators cannot be compared for more or less, but only for equality.

Or, you can immediately find an iterator on an element whose key is less than k.

 auto it = myMultimap.lower_bound(k-1);
 2
Author: pagislav, 2020-05-14 23:11:49