如何使用 std::sort 对自定义类中的两个 vector 进行排序?
举个例子,假设我有一个类包含两个 vector ,ids 和 marks。初始化 vector 后,我想按标记对此类的元素进行排序,并在 id 中保留排序顺序。
我尝试使用自定义 std::sort
函数来完成此操作。
class Example
{
public:
void init();
static bool sortByMarks(const Example &lhs, const Example &rhs);
//....other functions
private:
vector<int> ids;
vector<int> marks;
//....other variables
}
void Partition::init()
{
ids.resize(5);
marks.resize(5);
for(int i=0;i<5;i++)
ids[i]=i+1;
marks[0]=47;marks[1]=44;marks[2]=88;marks[3]=52;marks[4]=46;
}
bool Partition::sortByMarks(const Example &lhs, const Example &rhs);
{
return lhs.marks < rhs.marks;
}
编辑:[这是通过将 Example::添加到函数调用来解决的] 我在调用此函数时遇到问题。我尝试了以下方法:
Example e;
sort(&e, &e, Example::sortByMarks);
示例输入:
ids : 1,2,3,4,5
标记:47,44,88,52,46
示例输出:
ids : 2,5,1,4,3
标记:44,46,47,52,88
感谢任何帮助!
编辑:标记 vector 是我想要排序的(ids 也应该相应地改变)
最佳答案
我不认为你可以用那样的 vector 来做到这一点。您需要以某种方式将 ids 与标记结合起来,例如使用 map 、成对 vector 或像这样:
class Example{
public:
void init();
void sortByMarks();
private:
struct Students{
int ids;
int marks;
};
std::vector < Students > students;
};
void Example::sortByMarks(){
std::sort(students.begin(), students.end(), [](Students a, Students b){
return a.marks < b.marks;
});
}
int main(){
Example e;
e.sortByMarks();
}
或者您可以编写自己的排序:
void selection_sort(){
int size = marks.size();
for (int i = 0; i < size - 1; i = i + 1){
int min = i;
for (auto j = i + 1; j < size; j = j + 1){
if (marks[j] < marks[min]){ min = j; }
}
std::swap(marks[i], marks[min]);
std::swap(ids[i], ids[min]); // add this extra line
}
}
关于c++ - 使用 std::sort 在自定义类 C++ 中对 vector 进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30797011/