排序对象的向量 [英] Sorting a vector of objects

查看:123
本文介绍了排序对象的向量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个向量填充了一些顶点对象实例,需要根据它的'x'和它的'y'坐标后对它进行排序。

I have a vector filled with some vertex object instances and need to sort it, according to its 'x' and after it its 'y' coordinate.

.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

vertex.cpp

vertex.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;
}

run.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)

我不知道到底发生了什么,任何想法?

I don't know what exactly is going wrong, any idea?

推荐答案

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

You are storing Vertex * in the container not Vertex. When you call std::sort, you're actually sorting the value of the pointers, not the items themselves.

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

If you really need to be storing pointers (which I doubt), you can use a workaround like this (untested):

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

这篇关于排序对象的向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆