类(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算法,该算法由一个比较函数调用,当a
被认为小于b
时,该函数返回true
。
STL提供std::sort
来对容器进行排序(有关更多信息,请参阅此处(。它使用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, "Mark", "biology"),
staff(3455, "Mitch", "English"),
staff(1234, "Hen", "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, name: Mark, class: biology
ID: 1234, name: Hen, class: Maths
ID: 3455, name: Mitch, class: English