c++ - 排序 vector 不起作用

标签 c++ sorting object vector stl

<分区>

我在 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());

关于c++ - 排序 vector 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24700991/

相关文章:

c++ - 对函数的调用是不明确的,但为什么呢?

c++ - reinterpret_cast 本身会导致异常吗?

c++ - c++中成员函数模板的特化

c++ - 使用优化级别编译 C++ 项目

sorting - PS对象排序

r - 如何在 R 中相对于中心按顺时针顺序对点进行排序?

javascript - 在 typescript 中使用任何 Prop 定义对象

c++ - 为什么我的程序无法对整数字符串进行排序?

linux - 执行附加在可执行文件末尾的机器代码

c++ - Qt中的内存管理?