在stl集合中设置lower_bound

setting lower_bound in stl set

本文关键字:lower bound 设置 stl 集合      更新时间:2023-10-16

我想为多组结构设置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设置为指向字符串测试以"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());