1

I want to get a key-val pair from map a which key is less than or equal to a given K. I want to get end (or rend or any error indication) that So simple code and nearly same:

#include <iostream>
#include <map>
using namespace std;

int main() {
    map<int, int> m;
    m[56]= 666;
    auto it = m.lower_bound(1);
    if(it != m.end()) {
        cout << it->first;
    } else {
        cout << "this was expected!=(";
    }
    return 0;
}

I get same bad result for lower_bound and upper_bound. What do I do wrong?

Nasser Al-Shawwa
  • 3,573
  • 17
  • 27
DuckQueen
  • 772
  • 10
  • 62
  • 134

2 Answers2

2

According to cppreference.com:

  1. lower_bound returns Iterator pointing to the first element that is not less than key
  2. upper_bound returns Iterator pointing to the first element that is greater than key

Therefore, in both cases, you should be getting 666 for it->second, because the one element you inserted (key = 56) satisfies those criteria.

Here's how I'd write the conditional:

int main() {
    map<int, int> m;
    m[56] = 666;
    int myKey = 1;
    auto it = m.upper_bound(myKey);

    if (it == m.begin()) {
        cout << "Key less than or equal to " << myKey << " doesn't exist\n"; 
    } else {
        --it; // <- This is the key you are looking for
    }

    return 0;
}

In this case, we check if there's an element greater than your key. If it's the lowest key in the map, then what you're looking for isn't there. Otherwise, we just get the previous element to the one found by upper_bound.

Nasser Al-Shawwa
  • 3,573
  • 17
  • 27
0

As per this explanation

Returns an iterator pointing to the first element in the container whose key is not considered to go before k (i.e., either it is equivalent or goes after).

So getting 56 in your example is expected, since it does not go before 1.

To achive your goal use upper_bound which returns guaranteed higher key than given 'k' and reduce iterator if found:

auto it = m.upper_bound(key);
if (it == m.begin()) {
    // First and all other values are higher than key
    it == m.end();
}
else {
    // Found higher value, one previous is equal or less than key
    it--;
}
miradham
  • 2,285
  • 16
  • 26