c ++按主要排序,然后是次要标准

时间:2015-11-06 16:53:36

标签: c++ sorting operator-overloading

对于一个类项目,我们正在创建一个运行多个线程的grep类型程序,我们需要存储文件名和一个单词匹配的行号。结果需要首先按文件名排序,然后按行号

排序

所以我有

namespace ultragrep
{
    class File {

    public:
        int lineNumber;
        std::string contents;
        std::string fileName;

        File(int ln, std::string lc, std::string fn) : lineNumber(ln), contents(lc), fileName(fn) {};
        File() {};
        ~File(){};

        string ln_toString() {
            return "[" + std::to_string(lineNumber) + "]";
        }

        string contents_toString() {
            return " \"" + contents + "\" ";
        }

    };
    std::ostream& operator<<(std::ostream& out, const File& f) {
        return out << "[" << f.fileName << "]...";
    }

    //operator < so sort works 
    bool operator < (File& lhs, File& rhs)
    {
        return lhs.fileName < rhs.fileName;
    }
}

当我所有的线程都在我的main()中完成时,我有

sort(files.begin(), files.end());

for (ultragrep::File file : files)
{
    cout << file << file.ln_toString() << file.contents_toString()  << endl;
}

这似乎返回了我期待的结果,但不能保证行号也在&#39;中排序。一组结果。

示例结果:

[file1.txt]...[1] "clock hello"
[file4.txt]...[1] "hello hello "
[file4.txt]...[2] "hello"
[file4.txt]...[3] "hello hello hello hello "
[file4.txt]...[5] "hello"
[file6.txt]...[3] "hello" 

是否有一段我可以添加到&lt;超载以考虑二级排序参数?

1 个答案:

答案 0 :(得分:-2)

//operator < so sort works 
bool operator < (File& lhs, File& rhs)
{
    if (lhs.fileName == rhs.fileName)
    {
        return lhs.lineNumber < rhs.lineNumber;
    }
    return lhs.fileName < rhs.fileName;
}
相关问题