Mii*_*cck 2 c++ sorting struct vector
我有一个结构列表,我正在由其中一个成员排序.我正在使用std :: sort和我自己的比较函数,那部分很好.但是,当我从以下位置更改结构时,我注意到(非常)大的性能差距:
struct square
{
float x;
float y;
float z;
float scale;
float angle;
GLuint texture;
};
Run Code Online (Sandbox Code Playgroud)
至
struct square
{
float x;
float y;
float z;
float scale;
float angle;
GLuint texture;
std::vector <float> color;
};
Run Code Online (Sandbox Code Playgroud)
我已经使用了一种完全不同的方法,我意识到使用这样的矢量是一个坏主意(我知道数组的大小 - 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);
Run Code Online (Sandbox Code Playgroud)
我想知道它是否与重新排序结构列表有关,因为它们的大小在第二种情况下要大得多?
感谢您的回复.
bool sort (square a,square b)
Run Code Online (Sandbox Code Playgroud)
这会每次复制结构,包括向量.复制比正常数组复制速度慢.你应该使用它.
bool sort (const square& a, const square& b)
Run Code Online (Sandbox Code Playgroud)
如果您使用的是C++ 11,则可以使用std::array大小为常量替换向量.