std :: sort不会移动向量的元素[关闭]

问题描述 投票:-2回答:1

目标很简单,我有一个宽度,高度和面积属性的Rectangle类。我为<算子做了一个运算符重载,因为这是std::sort用来进行比较的。

基于我到目前为止在网上找到的内容,似乎这个问题通常源于复制操作符或类的构造函数中的错误。

这是Rectangle类的复制构造函数:

Rectangle::Rectangle(const Rectangle & other)
{
     m_width = other.m_width;
     m_height = other.m_height;
     m_area = other.m_area;
 }

这是我的复制操作员:

 Rectangle & Rectangle::operator=(const Rectangle & rhs)
 {
     if (this != &rhs)
     {
         m_width = rhs.m_width;
         m_height = rhs.m_height;
     }
     return *this;
}

这是<运算符:

bool Rectangle::operator<(const Rectangle & rhs)
{
    return (m_area > rhs.m_area);
}

最后,这是我如何调用sort方法,以防万一:

// rects is a vector<Rectangle> with several rectangles in it
std::sort(rects.begin(), rects.end());

我认为我正在做的一切正确,但任何帮助表示赞赏!

c++ copy operator-overloading
1个回答
1
投票

你的比较只使用m_area - 正如@Galik指出的那样,你没有在你的“复制算子”中设置它。因此,对于所有赋值构造的实例,它没有被初始化和“相同” - 因此没有排序。

根据您创建样本数据的方式,它们都具有未初始化的m_area

修复它是这样的:

 Rectangle & Rectangle::operator=(const Rectangle & rhs)
 {
     if (this != &rhs)
     {
         m_width = rhs.m_width;
         m_height = rhs.m_height;
         m_area = rhs.m_area;    // FIX 
     }
     return *this;
}

@Juanchopanza指出,使用自动生成的实现可以自己正确处理,所以如果没有压力的情况导致你自己实现这些,请删除它们。

© www.soinside.com 2019 - 2024. All rights reserved.