【发布时间】:2015-05-26 07:11:50
【问题描述】:
假设我有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)在比较之前。
有什么想法吗?我已经看到了this question 的答案。答案表明我可以使用比较函数bool comp(foo a, int b)。但是,二分查找算法如何知道int b 指的是.bar 而不是.other,因为两者都定义为int?
我还想知道 C++03 和 C++11 的答案是否会有所不同。请标记您的答案 C++03/C++11。谢谢。
【问题讨论】:
-
为什么
some_compare_function会混淆?它的第一个参数始终是要在foos中查找的索引,第二个参数是bar的值。 -
那么,如果
Foo在.bar之前定义了.other,那么.other会被用作key吗?在实际示例中,我的bar深埋在Foo... -
.bar的位置无关紧要。比较功能应该从任何地方获取它,请参阅我的答案。
标签: c++ sorting c++11 binary-search c++03