lower_bound for vector<MyClass*>

五迷三道 提交于 2019-12-02 00:58:31

There are two overloads of 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 );

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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!