繁体   English   中英

C++ std::set With Custom Class 返回错误的 lower_bound 值

[英]C++ std::set With Custom Class Returning Wrong lower_bound Value

在下面的代码中,有 class TileTQ ,一组Tile s,其中我使用 struct tCmp_id来比较集合元素。 mkTile简单地返回一个给定 id 值的Tile object。 主要是,我向TQ添加了四个元素:4 个图块,id 分别为 1、2、4 和 5。

我还在TQ上调用了upper_boundlower_bound ,它们应该分别给出 2 和 4。 但是,在我运行该程序时,我分别得到 4 和 4 作为输出。 这是代码:

#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;
}

有人可以解释这里发生了什么吗? 我试过在线搜索或编辑tCmp_id ,但到目前为止没有任何效果。 提前致谢

std::set::lower_bound - 返回指向第一个不小于(即大于或等于)键的元素的迭代器。

std::set::upper_bound - 返回指向第一个大于键的元素的迭代器。

由于您使用3作为搜索键,因此在这两种情况下您都会得到4

对于lower_bound 4是第一个不小于 3 的值,即它大于或等于3

对于upper_bound 4是第一个大于3的值。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM