简体   繁体   English

在C ++中将lower_bound()与一组对象一起使用

[英]Using lower_bound() with a set of objects in C++

I'm using a set of objects in C++ to get log(n) times for inserting and finding. 我在C ++中使用一组对象来获取插入和查找的log(n)次。 In the code below I'm able to insert elements and make them ordered by x attribute, however, I'm not able to use lower_bound to find the lower bounds based on the same attribute. 在下面的代码中,我能够插入元素并使它们按x属性排序,但是,我无法使用lower_bound来基于同一属性查找下限。 I don't know how to fix that. 我不知道该如何解决。 Any help will be appreciated. 任何帮助将不胜感激。

Most of the examples on sets that I could find were not about a set of objects 我能找到的关于集合的大多数示例都不是关于一组对象的

struct MyObject {
float x = 0;
float y = 0;    
const bool operator < ( const MyObject &r ) const{
    return ( x< r.x);
}
};

set<MyObject> nset;

int main(){

MyObject n1;
n1.x=5;
n1.y=1;

MyObject n2;
n2.x=3;
n2.y=2;

nset.insert(n1);
nset.insert(n2);

// this works, the elementes are sorted according to x
for(auto elem: nset){
    cout << elem.x << endl; 
}

// this doesn't work
set<MyObject>::iterator it = lower_bound(nset.begin(), nset.end(), 1.2);
cout << it->x << endl;

//neither this one
//    set<MyObject>::iterator it = nset.lower_bound(1.2);
//    cout << it->x << endl;

cout << "hello" << endl;
return 0;
}

I want the lower bound function to point me to the lower bound "x" in the set of objects but the code fails to compile. 我希望下限函数将我指向对象集中的下限“ x”,但是代码无法编译。 Compiler error to the first lower bound says: Invalid operands to binary expression ('const MyObject' and 'double') Compiler error to the second lower bound says: No matching member function for call to 'lower_bound' 编译器错误的第一个下限表示:二进制表达式的无效操作数(“ const MyObject”和“ double”)编译器错误的第二个下限表示:没有匹配的成员函数可用于调用“ lower_bound”

EDIT: while the answer provided by user: 1201ProgramAlarm was quite helpful for me to understand and fix the error. 编辑:虽然用户提供的答案:1201ProgramAlarm对我理解和修复错误非常有帮助。 I still think it is more convenient in my case to have a lower_bound function that accepts floats rather than objects. 我仍然认为,在我的情况下,具有一个lower_bound函数来接受浮点数而不是对象会更方便。 So I have implemented the following function to help me achieve that. 因此,我实现了以下功能来帮助我实现这一目标。 Copied below just in case others were interested: 如果其他人感兴趣,请复制以下内容:

set<MyObject>::iterator mylower_bound(set<MyObject> &myset, float val){    
    MyObject f;
    f.x = val;
    set<MyObject>::iterator it = myset.lower_bound(f);   
    return it;
}

nset stores MyObject objects, and lower_bound needs one of the thing stored in the set. nset存储MyObject对象,并且lower_bound需要存储在集合中的东西之一。 You're passing it 1.2 , which is a double, but there is no way to construct a MyObject from a double. 您将其传递给1.2 ,它是一个double,但是无法从double构造MyObject Thus the compilation failure. 从而编译失败。

You'll need to pass a MyObject to nset.lower_bound to do your search. 您需要将MyObject传递给nset.lower_bound进行搜索。

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

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