C++ std::lower_bound() 函数来查找索引排序向量的插入点

C++ std::lower_bound() function to find insertion point for an index-sorted vector

本文关键字:排序 索引 向量 查找 入点 插入 函数 lower std bound C++      更新时间:2023-10-16

假设我有vector<Foo>,并且它的索引在vector<int>中按类Foo.bar的关键字段进行外部排序。 例如

class Foo {
public:
     int bar;
     int other;
     float f;
     Foo(int _b, int _o, float _f): bar(_b), other(_o), f(_f) {}
};
vector<Foo> foos;
vector<int> sortedIndex;

sortedIndex包含 foos 的排序索引。

现在,我想插入一些东西来foos,并在sortedIndex中保持外部排序(排序键是.bar(。 例如

foos.push_back(Foo(10,20,30.0));
sortedIndex.insert(
                   lower_bound(sortedIndex.begin(),
                               sortedIndex.end(),
                               10 /* this 10 won't work*/,
                               some_compare_function
                   ),
                   1,
                   foos.size()-1
);

显然,数字 10 不起作用:向量sortedIndex包含索引,而不是值,some_compare_function会感到困惑,因为它不知道何时使用直接值,以及何时在比较之前将索引转换为值(foo[i].bar而不仅仅是i(。

知道吗? 我已经看到了这个问题的答案。 答案建议我可以使用比较函数bool comp(foo a, int b)。 然而,二叉搜索算法怎么知道int b指的是.bar而不是.other,因为两者都被定义为int

我还想知道 C++03 和 C++11 的答案是否会有所不同。请将您的答案标记为C++03/C++11。 谢谢。

>some_compare_function不会"混淆"。它的第一个参数始终是 sortedIndex 的元素,第二个参数是要比较的值,在您的示例中10。所以在 C++11 中,你可以像这样实现它:

sortedIndex.insert(
    lower_bound(sortedIndex.begin(),
        sortedIndex.end(),
        10,
        [&foos](int idx, int bar) {
            return foos[idx].bar < bar;
        }
    ),
    foos.size()-1
);