std::向量使结构排序变慢?C++

std::vector making struct sort slow? c++

本文关键字:C++ 结构 向量 std 排序      更新时间:2023-10-16

我有一个结构列表,我正在按其中一个成员进行排序。我正在使用 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);