如何解决如何在 C++ 中对包含类对象的向量进行排序?
class(staff) 包含对象 int ID,string Name,string Class 向量包含
vector <staff> s = { {234,"Mark","biology"},{3455,"Mitch","English"},{1234,"Hen","Maths"}}
如何从 ID 中排序?和打印排序? 谢谢
解决方法
我确定之前已经回答过这个问题,但针对您的具体情况;
#include <algorithm>
#include <iostream>
#include <vector>
#include <string>
struct staff {
int ID;
std::string Name;
std::string Class;
};
int main() {
std::vector <staff> s = {
{ 234,"Mark","biology" },{ 3455,"Mitch","English" },{ 1234,"Hen","Maths" }
};
std::sort(s.begin(),s.end(),[]( const auto& a,const auto& b) { return a.ID < b.ID; });
for (const auto& staff_member : s)
std::cout << staff_member.ID << ": " << staff_member.Name << "," << staff_member.Class << "\n";
return 0;
}
这使用来自 <algorithm>
标头的 std::sort 算法,当 true
被认为小于 a
时,该算法通过返回 b
的比较函数调用。
STL 提供 std::sort
来对容器进行排序(有关详细信息,请参阅 here)。
它利用 operator<
对容器内的元素进行排序,您可以在那里指定用于排序的元素。
调用 std::sort
后,容器已排序,您可以通过遍历它来打印排序。
这是一个快速而完整的示例:
#include <iostream>
#include <vector>
#include <algorithm>
class staff {
public:
explicit staff(const uint32_t id,const std::string& name,const std::string& class_type)
: id_(id),name_(name),class_(class_type) {}
bool operator<(const staff& other) {
return id_ < other.id_; // sort by id
}
void print() const {
std::cout << "ID: " << id_
<< ",name: " << name_
<< ",class: " << class_ << "\n";
}
private:
uint32_t id_;
std::string name_;
std::string class_;
};
static void print_staffs(const std::vector<staff>& staffs) {
for (const staff& staff : staffs) {
staff.print();
}
std::cout << "----------\n";
}
int main()
{
std::vector<staff> staffs = { staff(234,"biology"),staff(3455,"English"),staff(1234,"Maths") };
print_staffs(staffs); // print unsorted
std::sort(staffs.begin(),staffs.end()); // sort
print_staffs(staffs); // print sorted
return 0;
}
这产生:
ID: 234,name: Mark,class: biology
ID: 3455,name: Mitch,class: English
ID: 1234,name: Hen,class: Maths
----------
ID: 234,class: biology
ID: 1234,class: Maths
ID: 3455,class: English
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。