【发布时间】:2011-12-19 01:35:41
【问题描述】:
问题来了:
在我的第一堂课中,我有一个向量、一个双精度变量,并且我重载了比较运算符。以下是相关代码:
class City
{
double distance;
std::vector<int> coordinates;
bool operator<(const City& city) const
{
return this->distance < city.distance;
}
// same for the greater-than operator but changing "<" to ">"
};
在另一个类中,我有一个城市向量,每次满足条件时我都必须对其进行排序。为此,我定义了一个结构如下:
编辑:(引用而不是值)
struct CitySortHelper {
bool operator() (const City &x, const City &y) const { return x < y; }
} city_sort;
现在的问题是,当我对向量进行排序时,出现了新的 City 对象,我无法解释原因:
编辑:
// this prints all current objects in the vector
for (int i = 0; i < totalCities; i++) {
std::cout << cities->at(i) << std::endl;
}
// after the following line I get new City objects in the
// vector, that weren't there before the sort. The new objects
// always have distance = 0 and random values in the coordinates
std::sort(cities->begin(), cities->end(), city_sort);
// using the sort with no predicate also gives the same faulty results
std::sort(cities->begin(), cities->end());
编辑:(复制构造函数和赋值运算符)
City(const City &city)
{
this->distance = city.distance;
this->coordinates = city.coordinates;
}
City& operator= (const City &city)
{
this->distance = city.distance;
this->coordinates = city.coordinates;
return *this;
}
奇怪的是,这只发生在我按升序对 City 对象进行排序时,即如果我将 CitySortHelper 中的比较器运算符从“”,一切正常。
任何想法为什么会发生这种情况?任何帮助表示赞赏。
【问题讨论】:
-
你的 City 类有专门的拷贝构造函数吗?
-
如果可以只使用
std::sort(cities->begin(), cities->end())和std::sort(cities->begin(), cities->end(), std::greater<City>),为什么还需要自定义谓词? -
@KerrekSB 我也试过不使用谓词。在正常情况下,即使用 less-operator 的
std::sort(cities->begin(), cities->end()),我仍然会得到那些新对象。而使用std::greater没有问题。 -
我无法重现您的问题。您需要提供一个完整的、可编译的示例来演示该问题。
-
你说你可以使用std::greater,但我没有看到任何City::operator>()。在我看过的所有 STL impls(即 gcc 就是这样)上,std::greater() 只是转发给 operator>。如果您已经定义了 City::operator>,那么发布它可能会有所帮助。