c++ - 实现 operator< 的最佳方式是什么?

标签 c++

抱歉,如果这是一个愚蠢的问题,但这是我很好奇的事情。

我正在为基于姓氏、名字、中间名的排序算法重载小于运算符。我意识到这里没有对错之分,但我很好奇哪种风格在其他程序员中更好或更受欢迎。

bool CPerson::operator<(const CPerson& key) const
{
    if (m_Last < key.m_Last)
        || ( (m_Last == key.m_Last) && (m_First < key.m_First) )
        || ( (m_Last == key.m_Last) && (m_First == key.m_First) && (m_Middle < key.m_Middle) )
        return true;
    return false;
}

bool CPerson::operator<(const CPerson& key) const
{
    if (m_Last < key.m_Last)
        return true;
    else if ( (m_Last == key.m_Last) && (m_First < key.m_First) )
        return true;
    else if ( (m_Last == key.m_Last) && (m_First == key.m_First) && (m_Middle < key.m_Middle) )
        return true;
    else
        return false;
}

bool CPerson::operator<(const CPerson& key) const
{
    if (m_Last < key.m_Last)
        return true;

    if (m_Last == key.m_Last)
        if (m_First < key.m_First)
            return true;

    if (m_Last == key.m_Last)
        if (m_First == key.m_First)
            if (m_Middle < key.m_Middle)
                return true;

    return false;
}

最佳答案

我更喜欢:

bool CPerson::operator<(const CPerson& key) const
{
    if (m_Last == key.m_Last) {
        if (m_First == key.m_First) {
            return m_Middle < key.m_Middle;
        }
        return m_First < key.m_First;
    }
    return m_Last < key.mLast;
}

漂亮且系统化,很明显可以添加新成员。


因为这些是字符串,所以重复比较可能会不必要地降低效率。按照 David Hamman 的建议,这是一个只对每个字符串进行一次比较(最多)的版本:

bool CPerson::operator<(const CPerson& key) const
{
    int last(m_Last.compare(key.m_Last));
    if (last == 0) {
        int first(m_First.compare(key.m_First));
        if (first == 0) {
            return m_Middle < key.m_Middle;
        }
        return first < 0;
    }
    return last < 0;
}

关于c++ - 实现 operator< 的最佳方式是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7225781/

相关文章:

c++ - 错误的函数调用 "IOCTL_DISK_GET_DRIVE_LAYOUT_EX"

c++ - FastCGI与C++除了spawn-fcgi之外的其他启动方式

c++ - 根据其概率选择一个矩阵单元

c++ - 在 Cocoa 上创建后窗口消失

c++ - 没有匹配的构造函数来初始化 Mock Factory

c++ - 通过文件定义和启动嵌套类

c++ - const 成员函数中的成员变量类型

c++ - C++中数组char的初始化

c++ - 至少长度为 L 的最大连续子序列和(递归)

javascript - 如何获取早于 1901 的时间戳