c++ - 对自定义类的向量进行排序不会正确迭代向量
问题描述
我正在尝试为渲染分配实现画家排序算法。代码的前提是我需要找到多边形的平均深度,以及通过 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++;
}
解决方案
就我自己而言,答案竟然是一件非常愚蠢的事情。问题是 Polygon3D 类中使用的复制构造函数 - 我忘记在复制构造函数中复制深度值,这意味着 lhs 没有获得深度值。
推荐阅读
- assembly - X86: `movsxd rdx,edx` 指令是什么意思?
- database - 我可以以某种方式提供额外的上下文以允许 postgres 有效地排序/限制视图而不计算它们的行吗?
- java - 创建自定义参数匹配器混淆实现
- testflight - 上传到 TestFlight 时,Fastlane 获得“train_version 不再是 FastlaneCore 消息中使用的参数”
- javascript - 如何将道具从 connect 的 HOC 传递到 HOC?
- google-bigquery - 查询失败并出现错误 RESOURCE_EXHAUSTED (ORDER BY without ORDER BY)
- docker - Ubuntu18.04下默认无法安装nvidia-docker2
- typescript3.0 - TypeScript const 断言:如何使用 Array.prototype.includes?
- angular - Angular 6 kendo-dropdownlist 有条件地设置 [valueField] 和 [textField]
- dart - Google Rest API:“无效的 JWT:观众检查失败”?我正在使用观众字段 API 建议