c++ - 按成员变量的字母顺序对指向对象的指针数组进行排序

标签 c++ arrays sorting compare operator-overloading

<分区>

我有一个包含成员变量 name 的 Person 对象数组。我正在尝试使用重载比较运算符按字母顺序排列它们,该运算符使用 string::compare 来比较对象中的字符串。

bool Person::operator==(Person p) {
    if (name.compare(p.name) == 0) {
        return true;
    }
    else {
        return false;
    }
}

这行得通并给出了正确的结果,但我不知道如何使用它来按字母顺序排列数组中的名称。

我环顾四周,看到关于 string::compare 的文档说

relation between compared string and comparing string

  • 0 They compare equal
  • <0 Either the value of the first character that does not match is lower in > the compared string, or all compared characters match but the compared string > is shorter.
  • ,>0 Either the value of the first character that does not match is greater >in the compared string, or all compared characters match but the compared string is longer.

尽管如此,我无法找到解决我的问题的方法。

我正在努力做的事情是否走在正确的轨道上,或者是否有更好的方法?

最佳答案

您的运算符定义正确,但不是您要查找的运算符。您想定义运算符 <,然后使用 std::sort。

关于c++ - 按成员变量的字母顺序对指向对象的指针数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41944273/

相关文章:

c++ - 什么对我来说更好 : vector or list?

c++ - 我一直在尝试实现和 AVL 树,但我不断收到这 2 个错误 C2954 和 C2955,并且不知道如何解决它们

c++ - MSVC++ 6.0 : C1509 “Too many exception handler states in function”

c++ - 我可以执行哪种技术并同时获得相同功能的输出?

javascript - 如何在 javascript/jquery/underscore 中将数组减少到特定数量?

c++ - C++中的排序如何工作?

PostgreSQL 使用西里尔文排序 "ь"

c++按值传递的复制构造函数参数

python - 如何在迭代时使用 .delete() 删除 numpy 中的特定数组?

javascript - state中如何使用setState拼接成数组?