对不工作的向量排序

sort a vector not working

本文关键字:向量 排序 工作      更新时间:2023-10-16

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

因为您正在存储指向Animal的指针向量,因此您没有给类的operator<()工作的机会。sort函数使用operator<()作为vector对象的类型——在本例中是指向Animal的指针,而不是Animal的实例。

因此,数组是基于operator<()指针进行排序的,正如0x499602D2所说,这将导致指针数组按升序地址排序。

如果您希望它以这种方式工作,要么定义一个自定义比较器,要么使用vector<Animal>而不是vector<Animal*>

考虑到你没有动物向量。

在你的代码中,有一个指向动物的指针向量。

改变
vector<Animal*>

vector<Animal>

并告诉我们是否正在工作。

我假设这是你想要实现的多态性,这就是你使用Animal* s而不是堆栈分配的Animal对象的原因。由于您使用指针作为vector的值类型,因此std::sort()使用operator<()将解析为内置的重载,该重载将简单地比较指针的地址,而不是您的自定义操作符。

方便地,std::sort()将谓词作为可选的第三个参数。您可以传递一个可调用实体作为比较器来调用:

std::sort(animalesConConcha.begin(), animalesConConcha.end(),
[] (Animal* lhs, Animal* rhs) {
    return lhs->nombreArchivo < rhs->nombreArchivo;
});

如果您的编译器不支持lambda表达式,您可以使用带有重载operator()的函数或类实例来代替。