c++ - 重载比较运算符以在 C++ 中使用 STL 排序

标签 c++ sorting stl operator-overloading stl-algorithm

我正在编写一个程序,它将读取带有社会安全号码(当然不是真实号码)的姓名列表,并根据命令行参数根据姓氏或 ssn 对列表进行排序。为了简单起见,我已经重载了 < 运算符,还重载了输入和输出运算符。一切都编译得很好,直到我在 main 的末尾添加排序函数和输出。我很难过。有任何想法吗?也非常感谢任何其他提示。

#include <algorithm>
#include <iostream>
#include <vector>
#include <cstdlib>
#include <fstream>
using namespace std;

enum sortVar { NAME, SOCSEC };

class record {
    public:
        friend bool operator<(record& rhs, record& name);
        friend ostream& operator<<(ostream& out, record& toWrite);
        friend istream& operator>>(istream& in, record& toRead);
        bool t_sort;    
    private:
        string firstName, lastName, ssn;

};

bool operator<(record& rhs, record& next)
{
    if (rhs.t_sort = false) {
        if (rhs.lastName == next.lastName)
            return rhs.firstName < next.firstName;
        else
            return rhs.lastName < next.lastName;
    }
    else if (rhs.t_sort = true)
        return rhs.ssn < next.ssn;
}

ostream& operator<<(ostream& out, record& toWrite)
{
    out << toWrite.lastName 
         << " " 
         << toWrite.firstName 
         << "    " 
         << toWrite.ssn;
}

istream& operator>>(istream& in, record& toRead)
{
    in >> toRead.lastName >> toRead.firstName >> toRead.ssn;
}

int main(int argc, char* argv[])
{
    if (argc !=3) {
        cerr << "Incorrect number of arguments.\n";
        exit(1);
    }
    if (argv[1] != "name" || argv[1] != "socsec") {
        cerr << "Argument 1 must be either 'name' or 'socsec'.\n";
        exit(1);
    }

    sortVar sortMode;
    if (argv[1] == "name")
        sortMode = NAME;
    else if (argv[1] == "socsec")
        sortMode = SOCSEC;

    ifstream fin(argv[2]);

    vector<record> nameList;
    while(!fin.eof()) {
        record r;
        if (sortMode == NAME)
            r.t_sort = false;
        else if (sortMode == SOCSEC)
            r.t_sort = true;
        fin >> r;
        nameList.push_back(r);
    }

    //sort(nameList.begin(), nameList.end());
    //cout << nameList;

}

最佳答案

这有点奇怪,您的编译器应该对此发出警告

if (rhs.t_sort = false)

您不是在测试 t_sort 的值,而是始终将其设置为 false。

测试 bool 是否为 truefalse 无论如何都是不必要的,因为这就是 if-声明已经在做。

试试这个代码

bool operator<(const record& rhs, const record& next)
{
    if (rhs.t_sort) {
        return rhs.ssn < next.ssn;
    }
    else
    {
        if (rhs.lastName == next.lastName)
            return rhs.firstName < next.firstName;
        else
            return rhs.lastName < next.lastName;
    }
}

关于c++ - 重载比较运算符以在 C++ 中使用 STL 排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9336579/

相关文章:

c++ - Graph 的 map 表示

c++ - VC++ 允许对 STL 容器使用 const 类型。为什么?

c++ - 对这个递归示例有点困惑

c - strcmp 未正确比较指向字符的指针数组中的 2 个相邻字符串

Unix 排序字母数字字符与 ':' 、 '/' 组合的键

r - dplyr::summarize_at – 按传递的变量顺序对列排序,然后按应用函数的顺序排序

c++ - 以不同的方式解释 QCloseEvent

c++ - VC++ LNK2019 错误我似乎无法修复

python - 如何在函数中更改python字典中的类型?

c++ - std::iterator、指针和 VC++ 警告 C4996