c++ - 对对象 vector 进行排序

标签 c++ sorting object vector

我有一个填充了一些顶点对象实例的 vector ,需要根据它的“x”坐标和它的“y”坐​​标对其进行排序。

顶点.h

#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

顶点.cpp

#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)

我不知道到底出了什么问题,知道吗?

最佳答案

您正在将 Vertex * 存储在容器中,而不是 Vertex。当您调用 std::sort 时,您实际上是在对指针的值进行排序,而不是对项目本身进行排序。

如果您真的需要存储指针(我对此表示怀疑),您可以使用这样的解决方法(未经测试):

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());

关于c++ - 对对象 vector 进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6434357/

相关文章:

c++ - 在不安装整个库的情况下在 VSCode 和 OpenCV 中编辑 C++ 项目

c++ - 适用于 mac 的免费 c++ 编译器不使用 xcode

c++ - 如何在 Windows 中创建线程安全的单例模式?

javascript - JSON 与 JavaScript 对象数组。为什么第二种方法的结果与第一种方法不同?以及如何实现这一目标?

C++0x 元组没有迭代器,对吗?

r - 将NA移到数据框中每一列的末尾

java - Stream sorted() 导致意外结果

c# - 在 C# 中按片假名对日语文本进行排序

javascript - 分配变量后对象行为发生变化

javascript - ReactJS基于Object设置动态输入值