Home > other >  C std::set With Custom Class Returning Wrong lower_bound Value
C std::set With Custom Class Returning Wrong lower_bound Value

Time:01-04

In the code below, there is class Tile, and TQ, a set of Tiles, of which i use the struct tCmp_id to compare the set elements. mkTile simply returns a Tile object given an id value. In main, i add four elements to TQ: 4 tiles, with ids of 1, 2, 4, and 5.

I also call upper_bound and lower_bound on TQ, which should give 2 and 4, respectively. However, on I running the program, I'm getting 4 and 4, respectively, as outputs. Here's the code:

#include <iostream>
#include <algorithm>
#include <set>
#include <vector>
using namespace std;

class Tile {
    public:
        int id;
};
struct tCmp_id {
    bool operator()(Tile a, Tile b) const {
        return a.id < b.id;
    }
};

set<Tile, tCmp_id> TQ;

Tile mkTile(int id){
    Tile t;
    t.id = id;
    return t;
}

int main(){
    TQ.insert(mkTile(1));
    TQ.insert(mkTile(2));
    TQ.insert(mkTile(4));
    TQ.insert(mkTile(5));

    cout << (*TQ.lower_bound(mkTile(3))).id << endl;
    cout << (*TQ.upper_bound(mkTile(3))).id << endl;
}

Can somebody explain what's going on here? I've tried searching online or editing tCmp_id, but nothing's working so far. Thanks in advance

CodePudding user response:

std::set::lower_bound - Returns an iterator pointing to the first element that is not less than (i.e. greater or equal to) key.

std::set::upper_bound - Returns an iterator pointing to the first element that is greater than key.

Since you use 3 as the key to search for, you'll get 4 in both cases.

For lower_bound 4 is the first value not less than 3, i.e. it's greater or equal to 3.

For upper_bound 4 is the first value greater than 3.

  • Related