微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

排序对象的向量

如何解决排序对象的向量

| 我有一个填充有一些顶点对象实例的矢量,需要根据其\'x \'对其进行排序,并在其后的\'y \'坐标对其进行排序。 顶点
#ifndef VERTEX_H
#define VERTEX_H 1

class Vertex
{
private:
  double __x;
  double __y;
public:
  Vertex(const double x,const double y);
  bool operator<(const Vertex &b) const;
  double x(void);
  double y(void);
};

#endif // VERTEX_H
顶点
#include \"vertex.h\"

Vertex::Vertex(const double x,const double y) : __x(x),__y(y)
{
}

bool Vertex::operator<(const Vertex &b) const
{
  return __x < b.x() || (__x == b.x() && __y < b.y());
}

double Vertex::x(void)
{
  return __x;
}

double Vertex::y(void)
{
  return __y;
}
运行.cpp
#include <algorithm>
#include <stdio.h>
#include <vector>

#include \"vertex.h\"

void prnt(std::vector<Vertex *> list)
{
  for(size_t i = 0; i < list.size(); i++)
    printf(\"Vertex (x: %.2lf y: %.2lf)\\n\",list[i]->x(),list[i]->y());
}

int main(int argc,char **argv)
{
  std::vector<Vertex *> list;
  list.push_back(new Vertex(0,0));
  list.push_back(new Vertex(-3,0.3));
  list.push_back(new Vertex(-3,-0.1));
  list.push_back(new Vertex(3.3,0));

  printf(\"Original:\\n\");
  prnt(list);

  printf(\"Sorted:\\n\");
  std::sort(list.begin(),list.end());

  prnt(list);

  return 0;
}
我期望的输出是:
Original:
Vertex (x: 0.00 y: 0.00)
Vertex (x: -3.00 y: 0.30)
Vertex (x: -3.00 y: -0.10)
Vertex (x: 3.30 y: 0.00)
Sorted:
Vertex (x: -3.00 y: -0.10)
Vertex (x: -3.00 y: 0.30)
Vertex (x: 0.00 y: 0.00)
Vertex (x: 3.30 y: 0.00)
但是我实际上得到的是:
Original:
Vertex (x: 0.00 y: 0.00)
Vertex (x: -3.00 y: 0.30)
Vertex (x: -3.00 y: -0.10)
Vertex (x: 3.30 y: 0.00)
Sorted:
Vertex (x: 0.00 y: 0.00)
Vertex (x: -3.00 y: -0.10)
Vertex (x: -3.00 y: 0.30)
Vertex (x: 3.30 y: 0.00)
我不知道到底出了什么问题,知道吗?     

解决方法

        您将ѭ5storing存储在容器中,而不是
Vertex
。调用ѭ7时,实际上是在对指针的值进行排序,而不是对项本身进行排序。 如果您确实需要存储指针(我对此表示怀疑),则可以使用以下变通方法(未经测试):
struct less_than_key {
    inline bool operator() (const Vertex*& v1,const Vertex*& v2) {
        return ((*v1) < (*v2));
    }
};
std::sort(list.begin(),list.end(),less_than_key());
    ,        如果您想避免自己编写所有这些类(并且违反了双下划线规则!),则可以考虑使用一个
std::vector< std::pair<float,float> >
并使用
std::sort
。默认情况下,对是按字典顺序进行比较(这是您要的),因此您不需要任何额外的代码。     ,        您正在排序指针,而不是实际的Vertex对象。尝试这个:
std::vector<Vertex> list;
list.push_back(Vertex(0,0);
list.push_back(Vertex(-3,0.3);
...
即删除列表容器中的指针,并删除对push_back的调用中的新指针。     ,        似乎出于某种原因您想对整数值进行排序: 尝试这个:
bool Vertex::operator<(const Vertex &b) const
{
  return std::abs(__x) < std::abs(b.__x) || (std::abs(__x) == std::abs(b.__x) && std::abs(__y) < std::abs::(b.__y));
}
注意:如果您是同一类,则无需调用b.x()即可获取另一个对象的成员。您可以访问其他成员。 注意:请勿在标识符中使用双下划线。最好不要在标识符前加上下划线。     

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。