【问题标题】:Using lower_bound() with a set of objects in C++在 C++ 中将 lower_bound() 与一组对象一起使用
【发布时间】: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
  • 我现在已经编辑包含编译器错误

标签: c++ algorithm set


【解决方案1】:

nset 存储MyObject 对象,而lower_bound 需要存储在集合中的事物之一。您正在传递它1.2,这是一个双精度数,但无法从双精度数构造一个MyObject。因此编译失败。

您需要将MyObject 传递给nset.lower_bound 才能进行搜索。

【讨论】:

  • 您能否详细说明如何传递 MyObject?因为这不起作用: set::iterator it = nset.lower_bound(MyObject(1.2));
  • @user3134575 您需要构造MyObject,就像为要添加到集合中的对象所做的那样。
  • 我想我现在明白你的意思了。我只需要构造另一个像 n3 这样的对象并具有 n3.x=1.2 然后将其传递给函数。谢谢,确实有效。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-24
  • 2012-05-21
相关资源
最近更新 更多