我有一个结构列表,正在按其中一个成员进行排序。我正在使用 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;
};
此后我使用了一种完全不同的方法,并且我意识到使用这样的 vector 是一个坏主意(我知道数组 - 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)
这每次都会复制结构,包括 vector 。 vector 的复制速度比普通数组慢。您应该改用它。
bool sort (const square& a, const square& b)
如果您使用的是 C++11,则可以将 vector 替换为 std::array
,因为大小是恒定的。
关于c++ - std::vector 使结构排序变慢?由 小码哥发布于,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25204479/