c++ - std::vector 使结构排序变慢?由 小码哥发布于

标签 c++ sorting vector struct

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

相关文章:

javascript - 如何对包含破折号的数值数组进行排序? (仅限 JavaScript)

algorithm - 可以用希尔排序来衡量进度吗?

c++ - 对象成员变量在函数中更新但不持久化

c++ - 如何在 Qt 中获取 Windows 默认文件夹的本地化名称

C++ 游戏状态系统

java - 尝试获取数组中的最大值时出错

c++ - 如何将 unique_ptr 参数推回共享指针的 vector

c++ - vector 大小不会随着变量的添加而增加

c++ - 无法使用C++中的openssl API添加证书策略扩展

c++ - &*x 操作是否创建拷贝?