How to find the first value greater than or equal to a search value in a map with C++

1 Answer

0 votes
#include <iostream>
#include <map>

int main() {
    std::map<int, std::string> mp = {
        {1, "one"},
        {3, "three"},
        {5, "five"},
        {7, "seven"},
        {9, "nine"}
    };

    int searchValue = 4;
    auto it = mp.lower_bound(searchValue);

    if (it != mp.end()) {
        std::cout << "First value greater than or equal to " << searchValue << " is: " 
                  << it->first << " -> " << it->second;
    } else {
        std::cout << "No value found greater than or equal to " << searchValue;
    }
}


 
/*
run:

First value greater than or equal to 4 is: 5 -> five
 
*/

 



answered Jan 20, 2025 by avibootz
...