5

我已经使用 Google 的 Protcol 缓冲区将一组浮点数序列化为RepeatedField 。

在反序列化数据时,我使用另一个设置类以更适合我的游戏类的形式保存信息。静态CreateFrom方法提取和转换数据。

class VoxelTerrainSettings
{
public:
    std::vector<int> indices;
    btAlignedObjectArray<btVector3> vertices;

    VoxelTerrainSettings(void);
    ~VoxelTerrainSettings(void);

    static VoxelTerrainSettings CreateFrom(const VoxelTerrainProtoBuf::VoxelTerrainSettings &settings)
    {
        VoxelTerrainSettings s;

        int numIndices = settings.indices().size();

        s.indices.reserve(numIndices);

        for (int i = 0; i < numIndices; ++i)
        {
            s.indices.push_back(settings.indices().Get(i));
        }

        int numVertices = settings.vertices().size();

        s.vertices.reserve(numVertices);

        int v = 0;

        for (int i = 0; i < numVertices; ++i)
        {
            s.vertices.push_back(btVector3(settings.vertices().Get(v++), settings.vertices().Get(v++), settings.vertices().Get(v++)));
        }

        return s;
    }

    //VoxelTerrain Load();
};

但是,当前从 RepeatedField 中提取所有元素的方法似乎不是很优雅。

我尝试采用更有效的方法,但它们都抛出了超出范围的错误。

std::copy(settings.vertices().begin(), settings.vertices().end(), vv.begin());
std::copy(&settings.vertices().Get(0), &settings.vertices().Get(settings.vertices().size() - 1), &vv[0]);

我可以使用哪些方法来提高元素提取效率?

4

2 回答 2

9

std::copy 使用 std::front_inserter/std::back_inserter 迭代器类型将值插入容器尝试以下操作:

// inserting into list/deque
std::copy(settings.vertices().begin(), settings.vertices().end(), std::front_inserter(vv));
// inserting into vector
std::copy(settings.vertices().begin(), settings.vertices().end(), std::back_inserter(vv)); 
于 2012-11-12T07:00:27.577 回答
3

最快的是预先预留空间,然后在一个循环中变换优化缓存

s.indices.reserve(settings.indices().size());
s.vertices.reserve(settings.vertices().size());

for (auto& vertex : settings.vertices()) {
   s.indicies.push_back(...);
   s.verticies.push_back(...);
}
于 2017-07-26T15:05:43.243 回答