如何在以下程序中进行排序?

时间:2015-01-27 15:16:38

标签: c++

我想知道以下程序中sort()函数的工作方式是什么?

struct Triangle
{
    Vertex* vertices[3];
    Vertex normal;
};
struct VertexIndex
{
    float value; 
    Triangle* triangle;
};
struct Vertex{
    float x,y,z;    
};

   std::vector<VertexIndex>by_z;
  cout<<"test\n";
  for(int i=0; i<triangles.size();i++)
    for(char j=0; j<3; j++)
    {
        VertexIndex vi={
            triangles[i].vertices[j]->z,
            &triangles[i]
        };
        //cout<<&triangles[i]<<"\n";
        by_z.push_back(vi);
    }
std::sort(by_z.begin(),by_z.end());

排序函数按三角形[i] .vertices [j] - &gt; z的顺序对by_z中的内容进行排序,或按三角形的顺序排序[i] ??

2 个答案:

答案 0 :(得分:0)

std::sort要求传递符合Compare要求的函数/函子或类型实现operator<。因此,该代码中的某处必须存在(至少不存在编译器错误)

bool operator<(const VertexIndex& lhs, const VertexIndex& rhs)
{
    //comparison logic here
}

答案 1 :(得分:0)

答案很简单: 随你 bool operator<(const VertexIndex&a,const VertexIndex&b); 要么 bool VertexIndex::operator<(const VertexIndex&other) const; 比较将是标准。

相关问题