c++ - 在 STL 集中设置 lower_bound

标签 c++ stl set

我想为多组结构设置 lower_bound 和 upper_bound 以遍历一个范围。如何为字符串正确设置它?

#include ...
...    
struct foo{
    int bar;
    string test;
};

struct comp{
    inline bool operator()(const foo& left,const foo& right){
        return strcasecmp(left.test.c_str(), right.test.c_str());
    }
};

int main(){
    std::multiset<foo,comp> fooset;
    std::multiset<foo,comp>::iterator it, itLow;

    ...//insert into fooset

    //how do set lower_bound to element where string is "aab" or whatever?

    return 0;
}

如何设置 itLow 以指向字符串 test 以“ab”开头的元素?

我试过:

itLow = fooset.lower_bound("string");

我知道这还不够……但我不确定该怎么做。

谢谢!

最佳答案

您需要从字符串构造一个foo,然后使用lower_bound(或upper_bound,视情况而定)搜索职位:

struct foo {
    int bar;
    string test;

    foo(string i) : test(i) {}
};

std::multiset<foo, comp> fooset;

std:multiset<foo,comp>::iterator it = 
    std::lower_bound(fooset.begin(), fooset.end(), foo("string"), comp());

关于c++ - 在 STL 集中设置 lower_bound,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9827368/

相关文章:

Python 检查项目是否在不同的集合中,并将它们合并

Python 基础知识 为什么 set() 有效但 {} 失败?

c++ - 所有公共(public)结构产生对隐式删除的默认构造函数的调用

c++ - OpenCV:查找轮廓(); - 我使用的是什么内核

c++ - 不同的编译结果 : Mac vs Windows

固定大小 vector 的 C++ vector

C++,为什么 std::set 允许在与 set 元素不同的类型上使用 lower_bound(),但前提是我在 set 声明中添加 less<> ?

c++ - 如何找出两个图像之间的对象差异?

c++ - 从基类指针克隆派生类

c++ - 作用于可 move 但不可复制对象序列的变异 STL 算法的行为