vector< MyClass *>的lower_bound [英] lower_bound for vector<MyClass*>

查看:92
本文介绍了vector< MyClass *>的lower_bound的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个简单的课程:

class MyClass {
public:
    int id;
    string name;

};

我想要一个带有指向此类对象的指针的矢量,该矢量由引用的MyClass id排序.我以为使用lower_bound会很容易,我之前是用对象的矢量(不是指针)完成的.对于对象,我像这样重载了operator<:

I want to have a vector with pointers to objects of this class that is sorted by the referenced MyClass id. I thought that using lower_bound would be easy, I did it before with vectors of objects (not pointers). With objects, I overloaded operator< like that:

bool operator<(MyClass left, int right) {
    return (left.id < right);
}

然后我用lower_bound将新的MyClass对象插入排序的向量.

Then I used lower_bound to insert new MyClass object to sorted vector.

vector<MyClass>::iterator low;
low = lower_bound(vectorname.begin(),vectorname.end(),id);
prP = idContainer.begin();
prP = idContainer.insert(low, newobject); 

我不知道如何使用MyClass指针的向量执行相同的操作.有人可以帮助我实现这一目标吗?

I am lost how to do the same with the vector of MyClass pointers. Can anyone help me achieve that?

推荐答案

std::lower_bound :

template< class ForwardIt, class T >
ForwardIt lower_bound( ForwardIt first, ForwardIt last, const T& value );

template< class ForwardIt, class T, class Compare >
ForwardIt lower_bound( ForwardIt first, ForwardIt last, const T& value, Compare comp );

第一个是您用于vector<MyClass>的那个,默认情况下它使用operator<.第二个允许自定义比较函数,该函数将容器中的元素作为第一个参数,将值作为第二个参数.这就是您要用于vector<MyClass*>的内容:

The first one is the one you used for your vector<MyClass>, it uses operator< by default. The second one allows for a custom comparison function which takes an element from the container as the first argument and the value as the second. That's what you want to use for your vector<MyClass*>:

std::vector<MyClass*> pvec;
auto low = std::lower_bound(pvec.begin(), pvec.end(), id,
    [](const MyClass* c, const MyClass& id) {
        return *c < id;
    });

比较采用两个不同类型的参数有点奇怪,但这就是事实.

It's a little odd that the comparison takes two arguments of different types, but that's just how it is.

注意:您当前的operator< value 接受其参数.这导致不必要的副本.您将需要更改它,以使其通过引用const来获得.

Note: your current operator< takes its arguments by value. That incurs unnecessary copies. You'll want to change that to take them by reference to const.

这篇关于vector&lt; MyClass *&gt;的lower_bound的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆