C++ std::lower_bound() function to find insertion point for an index-sorted vector(C++std::Below_Bound()函数,用于查找索引排序向量的插入点)
问题描述
假设我有vector<Foo>
,它的索引在vector<int>
中通过类Foo
中的关键字字段进行外部排序。例如
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
)。
有什么想法吗?我已经看到了this question的答案。答案是我可以使用比较函数bool comp(foo a, int b)
。然而,既然两者都被定义为int
,那么二分搜索算法如何知道int b
指的是.bar
而不是.other
?
我还想知道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
);
这篇关于C++std::Below_Bound()函数,用于查找索引排序向量的插入点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C++std::Below_Bound()函数,用于查找索引排序向量的插入点


基础教程推荐
- CString 到 char* 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01