首页 > 解决方案 > 对自定义类的向量进行排序不会正确迭代向量

问题描述

我正在尝试为渲染分配实现画家排序算法。代码的前提是我需要找到多边形的平均深度,以及通过 for 循环分配给它们的深度的多边形列表。

这是多边形声明,以及多边形后期变换的顶点集合,用于计算多边形的深度

std::vector<Polygon3D> _polygons;
std::vector<Vertex> _transvertices;

这是模型类调用的方法,用于使用 std::sort 对 _polygons 向量进行排序

void Model::Sort()
{
    for (int i = 0; i <= GetPolygonCount(); i++)
    {
        _polygons[i].SetDepth((_transvertices[_polygons[i].GetIndex(0)].Get(2) + _transvertices[_polygons[i].GetIndex(1)].Get(2) + _transvertices[_polygons[i].GetIndex(2)].Get(2)) / 3);
    }

    sort(_polygons.begin(), _polygons.end(), sortByDepth);

}

然后此代码链接到此二进制谓词

bool sortByDepth(const Polygon3D &lhs, const Polygon3D &rhs)
{
    float m = lhs.GetDepth(); //For value testing
    float n = rhs.GetDepth(); //For value testing
    return lhs.GetDepth() > rhs.GetDepth();
}

问题是,一旦排序算法开始,lhs 和 rhs 的值永远不会改变 - lhs 的深度总是 0(进一步研究它的分配,它似乎正在创建一个全新的多边形?)并且 rhs 总是有一个值为 30.53(_polygons 顶点中第一个多边形的深度

我担心问题可能在于没有一种形式的迭代器链接到 Polygon3D 类,但我不知道从哪里开始为该类制作迭代器。

任何帮助将不胜感激,我已经查看了太多类似的问题,但它们似乎都不适合我的特定问题。

编辑:

帖子被删除是因为我显然没有提供足够的代码。我试图在另一个项目中重现该问题,但由于某种原因,它在那里迭代得很好。

这是我尝试过的“最短的复制”,但由于某种原因,这似乎与原版没有相同的问题。

#include <vector>
#include <algorithm>

class Polygon3D
{
public:
    Polygon3D(); // Example data for testing purposes
    float GetDepth() const;
    void SetDepth(float depth);
private:
    float _depthAverage;
};

class Model
{
public:
    Model();
    size_t GetPolygonCount() const;
    void Sort();
private:
    std::vector<Polygon3D> _polygons;
    std::vector<int> _vertices;
    std::vector<int> _transvertices;
};


Polygon3D::Polygon3D()
{
    //_depthAverage = float(rand() % 100);
}

float Polygon3D::GetDepth() const
{
    return _depthAverage;
}

void Polygon3D::SetDepth(float depth)
{
    _depthAverage = depth;
}

Model::Model()
{
    for (int i = 0; i < 10; i++)
    {
        _polygons.push_back(Polygon3D());
    }

    this->Sort();
}

size_t Model::GetPolygonCount() const
{
    return _polygons.size() - 1;
}

bool sortByDepth(const Polygon3D& lhs, const Polygon3D& rhs)
{
    float m = lhs.GetDepth();
    float n = rhs.GetDepth();
    return lhs.GetDepth() > rhs.GetDepth();
}

void Model::Sort()
{
    for (int i = 0; i <= GetPolygonCount(); i++)
    {
        _polygons[i].SetDepth(float(rand() % 100) / 3);
    }

    sort(_polygons.begin(), _polygons.end(), sortByDepth);

}

int main()
{
    Model m = Model();
}

编辑2:

我只是使用自动类型变量来手动迭代_polygons,这似乎有效。我不明白为什么 std::sort

auto begin = _polygons.begin();

    while(true)
    {
        begin++;
    }

标签: c++classsortinggraphicsiteration

解决方案


就我自己而言,答案竟然是一件非常愚蠢的事情。问题是 Polygon3D 类中使用的复制构造函数 - 我忘记在复制构造函数中复制深度值,这意​​味着 lhs 没有获得深度值。


推荐阅读