【问题标题】:std::sort is not moving the elements of a vector [closed]std::sort 没有移动向量的元素[关闭]
【发布时间】:2017-12-29 23:38:46
【问题描述】:

目标很简单,我有一个具有宽度、高度和面积属性的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());

我认为我所做的一切都是正确的,但感谢任何帮助!

【问题讨论】:

  • 你让编译器为你实现复制构造和赋值。它不太可能引入琐碎的错误。
  • 为什么不在赋值运算符中复制区域?
  • 你的问题无法从那个 sn-ps 重现 => 没有帮助

标签: c++ copy operator-overloading


【解决方案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 指出使用自动生成的实现可以自行正确处理此问题,因此如果没有压力情况导致您自己实现这些,请将两者都删除。

【讨论】:

  • 真正的修复最有可能实现复制和赋值。
  • @juanchopanza 同意 - 或者修复它
猜你喜欢
  • 1970-01-01
  • 2022-08-18
  • 1970-01-01
  • 1970-01-01
  • 2012-09-18
  • 2021-12-23
  • 2016-09-01
  • 2016-04-06
  • 1970-01-01
相关资源
最近更新 更多