[英]Why does std::sort() change the sorted vector?
这是问题所在:
在我的第一堂课中,我有一个向量,一个双变量,我重载比较运算符。 这是相关代码:
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
中的CitySortHelper
从“<”更改为“>”,一切正常。
任何想法为什么会这样? 任何帮助表示赞赏。
CitySortHelper
需要通过const引用而不是值来获取参数。 要记住的另一件事是sort使用City
赋值运算符; 检查您的赋值运算符是否正常工作。 处理这两个问题应该解决问题。
如果要保留顺序,则不应使用std::sort()
,应使用std::stable_sort()
。 stable_sort
保证元素保持其相对顺序, sort
不保持。
此外,这似乎不是sort
是你的问题。 似乎City对象被推入到某个地方的向量中,并且您没有注意到它们,因为您正在检查变量的大小而不是向量的迭代器。 尝试这样打印,并告诉我们出来的内容:
for (std::vector <City> ::iterator it = cities->begin(); it != cities->end(); ++it) {
std::cout << *it << std::endl;
}
更改您的排序助手
bool operator() ( const City& x , const City& y) const
并检查City复制构造函数和赋值运算符是否正确
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.