c++ - 根据成员变量对不同类对象的向量进行排序
问题描述
假设我有这样的代码
#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;
}
我想根据这些不同动物的速度按降序对这个动物向量进行排序。最好的方法是什么?
解决方案
您可以将std::sort
from<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();
});
推荐阅读
- php - 如何使用选定的类别名称创造价值?
- android - 如何在android中解析带有未知键的json
- php - 如果数据库中没有提供时区,使用 php time() 函数会更好吗
- reactjs - 如何在本地 WiFi 上公开从 WSL 运行的服务器/网站/服务?
- plsql - 有人可以请告诉我有什么问题吗?ORACLE APEX 中的 PLSQL
- sql-server - 如何为 EF 核心迁移历史记录表设置自定义名称并在生成迁移脚本时使用它?
- python - 为什么嵌套字典不能正确附加到列表中?
- javascript - 即使循环还没有完成迭代,一行代码也会运行吗?
- google-apps-script - 异常:获取对象 ContactsApp 上的方法或属性 getContactGroups 时出现意外错误
- python - cppzmq:使用 zmq::send_multipart 时对非套接字的套接字操作