【发布时间】:2012-12-22 04:06:23
【问题描述】:
考虑以下代码:
#include <algorithm>
#include <iostream>
#include <vector>
namespace my_space
{
struct A
{
double a;
double* b;
bool operator<(const A& rhs) const
{
return this->a < rhs.a;
}
};
void swap(A& lhs, A& rhs)
{
std::cerr << "My swap.\n";
std::swap(lhs.a, rhs.a);
std::swap(lhs.b, rhs.b);
}
}
int main()
{
const int n = 20;
std::vector<my_space::A> vec(n);
for (int i = 0; i < n; ++i) {
vec[i].a = -i;
}
for (int i = 0; i < n; ++i) {
std::cerr << vec[i].a << " ";
}
std::cerr << "\n";
std::sort(vec.begin(), vec.end());
for (int i = 0; i < n; ++i) {
std::cerr << vec[i].a << " ";
}
std::cerr << "\n";
}
如果我使用n=20,则会调用自定义交换函数并对数组进行排序。但是如果我使用n=4,数组排序正确,但自定义交换函数不被调用。这是为什么?如果复制我的对象真的很昂贵怎么办?
对于这个测试,我使用的是 gcc 4.5.3。
【问题讨论】:
-
This question 应该会有所帮助。
-
顺便说一句,为什么要使用
std::cerr进行正常输出? -
我不使用
cerr进行正常输出。我将cout用于正常输出,cerr用于错误消息、诊断和调试。在这种情况下,我想我可以使用cout。 -
+1 这个问题让我进行了大量挖掘,尽管我知道原因的大致轮廓。