【发布时间】:2019-01-25 19:58:45
【问题描述】:
我在 C++ 中使用一组对象来获取 log(n) 次以进行插入和查找。 在下面的代码中,我可以插入元素并使它们按 x 属性排序,但是,我无法使用 lower_bound 来查找基于相同属性的下限。我不知道如何解决这个问题。任何帮助将不胜感激。
我能找到的大多数关于集合的例子都不是关于一组对象的
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;
}
我希望下限函数将我指向对象集中的下限“x”,但代码无法编译。第一个下限的编译器错误说:二进制表达式的操作数无效('const MyObject'和'double') 第二个下限的编译器错误说:没有匹配的成员函数调用'lower_bound'
编辑:虽然用户提供的答案:1201ProgramAlarm 对我理解和修复错误很有帮助。我仍然认为在我的情况下,拥有一个接受浮点数而不是对象的 lower_bound 函数会更方便。所以我实现了以下功能来帮助我实现这一目标。复制如下,以防其他人感兴趣:
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;
}
【问题讨论】:
-
如果您遇到编译器错误,请发布这些错误。也就是说
std::set实现了自己的lower_bound函数,你应该使用它而不是std::lower_bound -
我现在已经编辑包含编译器错误