首页 > 解决方案 > 根据成员变量对不同类对象的向量进行排序

问题描述

假设我有这样的代码

#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;
}

我想根据这些不同动物的速度按降序对这个动物向量进行排序。最好的方法是什么?

标签: c++class

解决方案


您可以将std::sortfrom<algorithm>与 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();
});

推荐阅读