根据不同类对象的成员变量对其向量进行排序



假设我有一个类似的代码

#include <iostream>
#include <vector>
#include <memory>
#using namespace std;
class animal{
protected:
int height;
int speed;
};
class horse:public animal{
public:
horse(){
height=200;
speed=75;
}
};
class cat:public animal{
public:
cat(){
height=30;
speed=20;
}
};
class dog:public animal{
public:
dog(){
height=55;
speed=35;
}
};
int main() {
std::vector<std::unique_ptr<animal>>animalvector;
animalvector.emplace_back((unique_ptr<animal>(new horse)));
animalvector.emplace_back((unique_ptr<animal>(new cat)));
animalvector.emplace_back((unique_ptr<animal>(new dog)));
return 0;
}

我想根据这些不同动物的速度,按降序对这个动物分类。最好的方法是什么?

您可以使用<algorithm>中的std::sort和lambda函数来定义排序谓词。

std::sort(animalvector.begin(),
animalvector.end(),
[](auto const& lhs, auto const& rhs)
{
return lhs->speed > rhs->speed;
});

请注意,speed要么需要是public,要么需要一个公共getter函数。如果你想添加getter方法

class animal
{
public:
int GetHeight() const { return height; }
int GetSpeed() const { return speed; }
protected:
int height;
int speed;
};

然后修改lambda以使用这些getter

std::sort(animalvector.begin(),
animalvector.end(),
[](auto const& lhs, auto const& rhs)
{
return lhs->GetSpeed() > rhs->GetSpeed();
});

最新更新