我有一个向量填充了一些顶点对象实例,需要根据它的'x'和它后面的'y'坐标对它进行排序。
vertex.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
#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)
我不知道到底出了什么问题,任何想法?
答案 0 :(得分:6)
您将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());
答案 1 :(得分:1)
您正在排序指针,而不是实际的Vertex对象。试试这个:
std::vector<Vertex> list;
list.push_back(Vertex(0, 0);
list.push_back(Vertex(-3, 0.3);
...
即。摆脱列表容器中的指针和push_back调用中的新指针。
答案 2 :(得分:1)
如果您想自己保存自己编写所有这些类(并违反双下划线规则!),您可以考虑使用
std::vector< std::pair<float, float> >
并使用std::sort
。默认情况下,对按字母顺序进行比较(这是您要求的),因此您不需要任何额外的代码。
答案 3 :(得分:0)
似乎你想要出于某种原因将其排序为绝对值:
试试这个:
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()来获取另一个对象的成员。您可以访问其他成员。
注意:不要在您的标识符中使用双下划线。不希望标识符带有下划线。