C++ std::lower_bound() 函数来查找索引排序向量的插入点
C++ std::lower_bound() function to find insertion point for an index-sorted vector
假设我有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
);
相关文章:
- 如何根据排序索引的向量对 std::index 集进行排序?
- 保持排序的数据结构,允许log N插入时间,并且可以返回我在log N中查找的元素的索引
- 排序谓词没有传递对索引对象的引用?
- 如何在对向量排序后更改索引值?c++
- 在不进行排序的情况下查找数组中n个最小值的索引
- 如何解决索引和排序问题
- 使用C++中的排序对索引进行排序
- 如何使equal_range迭代器在 Boost 多索引中按不同的索引排序?
- 为什么我的代码没有对数组中第二个索引上的数据进行排序?
- 根据某些条件对索引子集进行排序
- 如果我将索引变量更改为零,并且合并函数中的k = 0,则获得合并排序的错误结果
- 如何对同一数组索引下的结构成员进行排序?
- 如何在保留原始索引的同时对向量的向量进行排序
- 如何获取向量的排序索引
- 基于其他信息的C 排序索引
- 如何将未排序数组的排序索引放入新数组中
- boost多索引排序索引中插入的匹配函数
- c++就地排序索引文件(使用堆排序)
- C++快速排序索引0返回-842150451
- 快速排序索引问题