有没有一种方法可以对其中一个元素为引用的pair集合进行排序?
我有一段代码,想要对一个
然而,如果我将引用更改为指针,则其工作方式符合我的期望。
std::vector<Ty>
进行排序,其中Ty
是std::pair<A, B&>
,而A
和B
是类。为了给出一个最小的具体例子,这里是typedef std::pair<int, int&> Ty
的代码。这个代码应该根据pair的第二个元素来排序。void bad() {
typedef std::pair<int, int &> Ty;
int a[N] = {17, 4, 8, 10, 0};
std::vector<Ty> v;
for (int i = 0; i < N; ++i) {
v.emplace_back(i, a[i]);
}
std::sort(v.begin(), v.end(),
[](const Ty &a, const Ty &b) { return a.second < b.second; });
std::cout << "With reference (bad):" << std::endl;
for (auto &x : v) {
std::cout << x.first << ',' << x.second << std::endl;
}
}
这将输出:
With reference (bad):
4,17
3,17
2,17
1,17
0,17
然而,如果我将引用更改为指针,则其工作方式符合我的期望。
void good() {
typedef std::pair<int, int *> Ty;
std::vector<Ty> v;
int a[N] = {17, 4, 8, 10, 0};
for (int i = 0; i < N; ++i) {
v.emplace_back(i, &a[i]);
}
std::sort(v.begin(), v.end(),
[](const Ty &a, const Ty &b) { return *a.second < *b.second; });
std::cout << "With pointer (good):" << std::endl;
for (auto &x : v) {
std::cout << x.first << ',' << *x.second << std::endl;
}
}
输出:
With pointer (good):
4,0
1,4
2,8
3,10
0,17
如果可能的话,我更喜欢使用参考文献; 有没有办法解决这个问题? 我已经尝试使用调试器进行跟踪,但我看不出为什么排序算法不能正确地复制(也许交换?)这些对。
-std=c++11 -stdlib=libc++
),void bad()
实际上运行良好。因此,错误无法重现。 - Walter