std::向量使结构排序变慢?C++
std::vector making struct sort slow? c++
我有一个结构列表,我正在按其中一个成员进行排序。我正在使用 std::sort 与我自己的比较函数,这部分很好。但是,当我从以下位置更改结构时,我注意到(非常(大的性能差距:
struct square
{
float x;
float y;
float z;
float scale;
float angle;
GLuint texture;
};
自
struct square
{
float x;
float y;
float z;
float scale;
float angle;
GLuint texture;
std::vector <float> color;
};
从那以后,我使用了一种完全不同的方法,我意识到使用这样的向量是一个坏主意(我知道数组的大小 - rgb(,但我想知道为什么我受到性能影响。我正在比较要排序的 z 值。
这是我的排序函数和结构列表:
std::vector <square> square_list;
//Then add a bunch of squares
bool sort (square a,square b)
{
return a.z < b.z;
}
//Here is the sort that is slow
std::sort (square_list.begin(),square_list.end(),sort);
我想知道它是否与重新排序结构列表有关,因为在第二种情况下它们的大小要大得多?
感谢您的任何回复。
bool sort (square a,square b)
这将每次复制结构,包括向量。向量的复制速度比普通数组慢。您应该改用它。
bool sort (const square& a, const square& b)
如果使用 C++11,则可以将矢量替换为 std::array
,因为大小是恒定的。
除了将参数作为常量引用之外,您还可以使用函子进行比较。这通常更快,因为函子更容易内联。
std::vector <square> square_list;
//Then add a bunch of squares
struct sort
{
bool operator() (const square& a, const square& b) const {
return a.z < b.z;
}
}
std::sort (square_list.begin(),square_list.end(),sort);
排序每次
都复制你的值,std::vector预分配一堆内存。复制时间更大
您是否尝试过在向量中存储指针而不是整个结构?
std::vector <square*> square_list;
//Then add a bunch of squares
bool sort (square* a,square* b)
{
return a->z < b->z;
}
//Here is the sort that is slow
std::sort (square_list.begin(),square_list.end(),sort);
相关文章:
- 如何循环打印顶点结构
- 通过方法访问结构
- 使用不带参数的函数访问结构元素
- 预处理器:插入结构名称中的前一个行号
- 为什么在没有显式默认构造函数的情况下,将另一个结构封装在联合中作为成员的结构不能编译
- 孤立代码块在结构中引发异常
- 有什么方法可以遍历结构吗
- 如何在 C# 中映射双 C 结构指针?
- 如何在C++中使用结构生成映射
- 无法将结构注册为增强几何体3D点
- 多成员Constexpr结构初始化
- C++将文本文件中的数据读取到结构数组中
- 如何重构类层次结构以避免菱形问题
- 如何在C++中序列化结构数据
- std::vector的包装器,使数组的结构看起来像结构的数组
- 没有为自己的结构调用列表推回方法
- 奇怪的结构&GCC&clang(void*返回类型)
- 在 c++ 中拥有一组结构的正确方法是什么?
- vscode g++链路故障:体系结构x86_64的未定义符号
- C++概念:如何使用'concept'检查模板化结构的属性?