首页 > 解决方案 > 对象指针的C++自定义排序向量

问题描述

我正在尝试按字母顺序对 File* 的向量进行排序。一切似乎都很好。但是当我将 < 更改为 > 时,顺序并没有改变。我试图设置一个断点,return a->getFileName()[0] < b->getFileName()[0];但它没有在那里中断。这让我想知道我的实现是否正确。

bool compare_file(File* a, File* b)
{
    return a->getFileName()[0] < b->getFileName()[0];
}

Directory::Directory(fs::path path, Directory* parent) :
    path(path), parent(parent)
{
    for (const auto& entry : fs::directory_iterator(path))
    {
        if (fs::is_directory(entry))
        {
            //std::cout << entry << std::endl;
            sub_dir.push_back(new Directory(entry, this));
        }
        else
        {
            File* f = new File(entry);
            files.push_back(f);
        }
    }
    std::sort(files.begin(), files.begin(), compare_file);
    std::cout << std::endl;
}

我也尝试实现 operator< 但也没有运气。

class File
{
public:
    const fs::path path;
    std::uintmax_t size;
    fs::file_time_type last_modified_time;

    struct HumanReadable {
        std::uintmax_t size{};
    private: friend
        std::ostream& operator<<(std::ostream& os, HumanReadable hr)
    {
        int i{};
        double mantissa = hr.size;
        for (; mantissa >= 1024.; mantissa /= 1024., ++i) {}
        mantissa = std::ceil(mantissa * 10.) / 10.;
        os << mantissa << "BKMGTPE"[i];
        return i == 0 ? os : os << "B (" << hr.size << ')';
    }
    };

    File(const std::filesystem::path p);
    std::string getFileName(void);
    std::string getDirName(void);
    bool operator==(File& target);

    bool operator < (File* f)
    {
        return getFileName()[0] < f->getFileName()[0];
    }
};

标签: c++sortingvector

解决方案


推荐阅读