我在 Animal
中有这样的重载运算符
// A must be comparable to be used as keys
bool operator<(const Archivo &right) const
{
return nombreArchivo < right.nombreArchivo;
}
在我的 main
中调用
std::vector<Animal*> animalesConConcha;
// add some objects
std::sort(animalesConConcha.begin(), animalesConConcha.end());
std::cout<<"\n\n\nOrdered:\n";
for(it=animalesConConcha.begin(); it!=animalesConConcha.end(); it++)
{
cout<<(*it)->nombre<<" | "<<(*it)->indice<<endl;
}
但是输出仍然是未排序的。
您在 vector 中存储指针,而不是对象。 std::sort
不取消引用指针,而是比较实际的指针值。 (从技术上讲,这没有保证的行为,因为 <
直接用在指针上。)
解决方案 1:将对象直接存储在 vector 中:
vector<Animal> animalesConConcha;
sort(animalesConConcha.begin(), animalesConConcha.end());
for(it=animalesConConcha.begin(); it!=animalesConConcha.end(); it++)
{
cout<< it->nombre<<" | "<< it->indice<<endl;
}
解决方案 2:为 std::sort
指定自定义比较仿函数:
struct Comparison
{
bool const operator()(Animal *lhs, Animal *rhs) const
{
return (*lhs) < (*rhs);
}
};
sort(animalesConConcha.begin(), animalesConConcha.end(), Comparison());