c++ - 使用 std::sort 在自定义类 C++ 中对 vector 进行排序

标签 c++ sorting vector

如何使用 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/

相关文章:

c++ - 当检测到 Cuda API 错误 : cudaMemcpy returned (0xb) 时,如何找到程序崩溃的位置

r - 在不同顺序的字符串中查找字母

sorting - OCaml - 如何对对进行排序?

C++/带有对象指针 vector 的多个文件

c++ - : Expected constructor, 析构函数错误, '<' token 之前的类型转换

c++ - 错误#include'ing <unordered_map>

C++ std::map:获取特定偏移量处的键

c++ - 比较 float - Google 测试框架

java - 按优先级对列表进行排序,然后反转具有相同优先级的元素的顺序

c++ - 在队列中插入 vector 元素