std::bad_alloc连接两个向量时

std::bad_alloc when concatenating two vectors

本文关键字:两个 向量 bad alloc 连接 std      更新时间:2023-10-16

连接两个向量时遇到一些问题。

std::vector<Transform3D> out;
for(double theta = 0; theta <= 2*M_PI ; theta+=1 )
{
    for(double phi = 0; phi <= M_PI ; phi+=1 )
    {
        double sphere_x = obj_x + r*cos(theta)*sin(phi);
        double sphere_y = obj_y + r*sin(theta)*sin(phi);
        double sphere_z = obj_z + + r*cos(phi);
        Transform3D<> transformation_matrix = transform(obj_x,obj_y,obj_z,sphere_x,sphere_y,sphere_z);
        if(0.01<(transformation_matrix.P()[0] - current_x) ||
            0.01<transformation_matrix.P()[1] - current_y ||
            0.01<transformation_matrix.P()[2] - current_z)
        {
            cout << "Interpolate: " << endl;
            std::vector<Transform3D> transformation_i = invKin_LargeDisplacement(transformation_matrix);
            out.insert(out.end(),transformation_i.begin(),transformation_i.end());
        }
        else
        {
            cout << "OK" << endl;
            out.push_back(transformation_matrix);
        }
        cout << out.size() << endl;
        cout << sizeof(Transform3D<>) << endl;
    }
}

out.insert(..)似乎导致了bad_alloc,但需要额外的数据。

在调试该问题时,我在运行for循环时打印了矢量的大小,并得到了以下输出:

Interpolate: 
6346700
Interpolate: 
12052200
Interpolate: 
16476100
Interpolate: 
20127501
Interpolate: 
26474201
Interpolate: 
32239601
Interpolate: 
36748301
Interpolate: 
40416502
Interpolate: 
46763202
Interpolate: 
52659402
Interpolate: 
57349102
Interpolate: 
61053903
Interpolate: 
67400603
Interpolate: 
73377503
Interpolate: 
terminate called after throwing an instance of 'std::bad_alloc'
  what():  std::bad_alloc
Aborted (core dumped)

有没有什么方法可以避免得到bad_alloc,同时仍然可以插值?

如果我们假设您的转换是一个具有4x4浮点数组(4字节)的PoD:

转换的大小=4*4*4=64字节
异常情况下的阵列大小=73377503

64*73377503=4696160192字节=4.696160192千兆字节

有了这么大的矢量,我想你的记忆力会耗尽。。。

您的机器中有多少内存?您真的需要4.7Gb的转换数据吗?

如果是这样的话,也许可以考虑压缩内存中的数据和/或将其写入文件缓存。