c++ - 为什么使用 < 运算符的 vector 比较会对每个项目进行两次比较?

标签 c++ operator-overloading stdvector

在本例中,比较两个带有 < 运算符的 vector 会得到运算符 <,该运算符定义在 Integer 类中,每个元素被调用两次。但是,在使用 == 运算符比较两个 vector 时不会发生这种情况。

#include<iostream>
#include<vector>

class Integer {
    public:
        Integer(int value) : m_value(value) {}
        friend bool operator<(const Integer& lhs, const Integer& rhs);
        friend bool operator==(const Integer& lhs, const Integer& rhs);

    private:
        int m_value;

}; 
bool operator<(const Integer& lhs, const Integer& rhs) {
            std::cout << lhs.m_value << " < " << rhs.m_value << '\n';
            return lhs.m_value < rhs.m_value;
}
bool operator==(const Integer& lhs, const Integer& rhs) {
            std::cout << lhs.m_value << " == " << rhs.m_value << '\n';
            return lhs.m_value == rhs.m_value;
}


int main()
{
    std::vector<Integer> ivec1 {1,2,3};
    std::vector<Integer> ivec2 {1,2,3};
    std::cout << (ivec1 < ivec2) << '\n';
    std::cout << (ivec1 == ivec2) << std::endl;
    return 0;
}

此代码打印:

1 < 1
1 < 1
2 < 2
2 < 2
3 < 3
3 < 3
0
1 == 1
2 == 2
3 == 3
1

为什么会这样?

最佳答案

如果a < b返回 false , 它不会告诉你是否 b < a ,你必须测试它。那是因为 std::vector 的逐元素排序一对元素可以有三个结果 a, b :

  • a < b , vector 比较返回 true .
  • b < a , vector 比较返回 false .
  • 以上都不是,必须测试下一对元素。

所以它必须比较两个方向。通过向类中添加标识数据,您可以更清楚地看到这一点:

#include<iostream>
#include<vector>

class Integer {
    public:
        Integer(int value, char tag) : m_value(value), m_tag(tag) {}
        friend bool operator<(const Integer& lhs, const Integer& rhs);
        friend bool operator==(const Integer& lhs, const Integer& rhs);

    private:
        int m_value;
        char m_tag;

}; 
bool operator<(const Integer& lhs, const Integer& rhs) {
            std::cout << lhs.m_value << ' ' << lhs.m_tag << " < " << rhs.m_value << ' ' << rhs.m_tag << '\n';
            return lhs.m_value < rhs.m_value;
}
bool operator==(const Integer& lhs, const Integer& rhs) {
            std::cout << lhs.m_value << ' ' << lhs.m_tag << " == " << rhs.m_value << ' ' << rhs.m_tag << '\n';
            return lhs.m_value == rhs.m_value;
}


int main()
{
    std::vector<Integer> ivec1 {{1, 'a'} ,{2, 'a'}, {3, 'a'}};
    std::vector<Integer> ivec2 {{1, 'b'} ,{2, 'b'}, {3, 'b'}};
    std::cout << (ivec1 < ivec2) << '\n';
    std::cout << (ivec1 == ivec2) << std::endl;
    return 0;
}

这会产生:

1 a < 1 b    
1 b < 1 a    
2 a < 2 b    
2 b < 2 a    
3 a < 3 b    
3 b < 3 a    
0    
1 a == 1 b    
2 a == 2 b    
3 a == 3 b    
1

[Live example]

关于c++ - 为什么使用 < 运算符的 vector 比较会对每个项目进行两次比较?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51187597/

相关文章:

c++ - CppUnitTestFramework 和测试 "vector subscript out of range"

c++ - OpenCV 从中心 x,y 绘制矩形

c++ - 用另一个数组初始化指向数组的指针的点

c++ - 如何获取当前持有的变体类型,并定义该类型的新变量

c++ - 模板类中运算符 [] 的可变模板重载

c++ - 重载运算符时 C++ 代码出错

c++ - 如何限制类在声明它的 namespace 之外的可见性?

javascript 忽略-if-null 运算符?

c++ - 如何将 std::array 元素附加或插入 std::vector?

c++ - 如何根据 .first 值从 std::pair 的 std::vector 中删除元素?