c++ - 类内的 stable_sort

标签 c++ sorting struct stable-sort

我在使用 std::stable_sort
时一直遇到类型问题 我不断收到错误消息:

argument of type 'bool (Memory::)(const Mem&, const Mem&)' does not match 'bool (Memory::*)(const Mem&, const Mem&)'

我不明白为什么它显示为指针...如果有人能看一下,将不胜感激。

内存.cpp:

#include <vector>
#include <algorithm>
#include <iostream>
#include <set>

#include "Memory.h"
#include "constants.hpp"

Memory::Memory(int _type) {
    fit_type = _type;
    blocks = 1;
    mem[0].address = 0;
    mem[0].size = 2048;
    mem[0].item_id = EMPTY;
}

void Memory::sort_mem_list() {
    // Sort by address
    std::stable_sort(mem.begin(), mem.end(), Memory::compareByAddress );
}

bool Memory::compareByAddress(const Mem &a, const Mem &b) {
    return a.address < b.address;
}

和内存.hpp

#ifndef MEMORY_H_
#define MEMORY_H_

#include <vector>
#include "process.h"
#include "constants.hpp"

class Memory {
public:
    Memory(int);
    int add_item(Process pr);
    void remove_item();
    void sort_mem_list();
    void set_fit_type(int);
    void memory_dump();

private:
    bool compareBestFit(const Mem & a, const Mem & b);
    bool compareWorstFit(const Mem & a, const Mem & b);
    bool compareByAddress(const Mem & a, const Mem & b);
    bool compareByProcess(const Mem & a, const Mem & b);

    int fit_type;
    int memory_size;
    int blocks;
    std::vector<Mem> mem;
};

#endif /* MEMORY_H_ */

内存(当前在 constants.hpp 中)

struct Mem {
    int address;
    int size;
    int item_id;

    Mem() {
        address = 0;
        size = 0;
        item_id = EMPTY;
    }
    Mem(int a, int b, int c) {
        address = a;
        size = b;
        item_id = c;
    }


};

我确信这是相当简单的事情,我只是以某种方式弄乱了声明,但我已经坚持了一段时间,所以第二双眼睛会很有帮助。

最佳答案

如果您计划使用成员函数作为传递给 std::stable_sort() 的比较器,它需要是一个static 函数。

关于c++ - 类内的 stable_sort,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9780150/

相关文章:

java - 如何对链表进行排序?

Golang 中的 map 集

c# - 如何在 C# 中在运行时转换泛型值?

c++ - 这个 Objective-C Cocos2D 和 CCNode 的 C++ 等价物是什么

c++ - 在 OO 编程中,继承对运行时有哪些负面影响?

php - 自然地按键排序多维数组

c - 如何删除一个数组结构体,并且最后一个索引不能被其他索引替换?

c++ - OpenCV3.10 core.hpp必须用C++编译

c++ - 在其声明之上调用函数

c# - 使用 .Net 如何使用 Sort 方法对数组进行反向排序,即从 Z 到 A?