有没有办法让排序处理对的集合,其中一个元素是一个引用?我有代码,我想排序std::vector<Ty>,其中Ty是std::pair<A, B&>和A和B是类.为了给出一个最小的具体示例,这里是代码typedef std::pair<int, int&> Ty.这应该根据该对的第二个元素对向量进行排序.
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;
}
}
Run Code Online (Sandbox Code Playgroud)
这输出:
With reference (bad):
4,17
3,17
2,17
1,17
0,17
Run Code Online (Sandbox Code Playgroud)
但是,如果我将引用更改为指针,它就像我期望的那样工作
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;
}
}
Run Code Online (Sandbox Code Playgroud)
输出:
With pointer (good):
4,0
1,4
2,8
3,10
0,17
Run Code Online (Sandbox Code Playgroud)
如果可能,我更愿意使用参考文献; 有没有什么办法解决这一问题?我已经尝试使用调试器进行跟踪,但是我无法通过排序算法正确地看出为什么没有正确地复制对(可能是交换?).
如果你使用std :: reference_wrapper,那么它按预期工作.在线提供.
int N = 5;
typedef std::pair<int, std::reference_wrapper<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]);
}
// Print, just to be sure :)
for (auto &x : v) {
std::cout << x.first << ',' << x.second << std::endl;
}
std::sort(v.begin(), v.end(),
[](const Ty &a, const Ty &b) { return a.second < b.second; });
std::cout << "With std::reference_wrapper (good):" << std::endl;
for (auto &x : v) {
std::cout << x.first << ',' << x.second << std::endl;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
251 次 |
| 最近记录: |