C++ boost多阵列分割故障

C++ boost多阵列分割故障,c++,boost,segmentation-fault,C++,Boost,Segmentation Fault,我在写一个代码,我用一个三维boost多数组来保存坐标。但我总是在某个时候出现分割错误。 boost多阵列大小是如何限制的?我如何绕过这些限制 下面是重现问题的简化测试代码: #include <iostream> #include <fstream> #include <string> #include <vector> #include <string> #include <algorithm> #include <

我在写一个代码,我用一个三维boost多数组来保存坐标。但我总是在某个时候出现分割错误。 boost多阵列大小是如何限制的?我如何绕过这些限制

下面是重现问题的简化测试代码:

#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <string>
#include <algorithm>
#include <map>

#include <boost/multi_array.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/algorithm/string.hpp>
#include "Line.h"

#include <boost/algorithm/string/classification.hpp>
#include <boost/algorithm/string/split.hpp>

typedef struct {
    Eigen::Vector3d coords;
    int gpHostZone;
    int gpHostFace;
    int calculated;
} Vertex;


class LGR {
public:
    LGR (int i, int j, int k) :
        grid(boost::extents[i][j][k])
    {
    };

    std::string name;
    std::vector<int> hostZones;
    std::vector<int> refine;
    boost::multi_array<Vertex*, 3> grid;
    std::vector<double> data;
 };

 int main(void){
   LGR lgr(11,11,21);
   std::cout << lgr.grid.size();
   std::vector<LGR> v;
   std::vector<Vertex> vertexDB;
   for(int i = 0; i < 1; i++ ){

     for(int j = 0; j < lgr.grid.size(); j++ ){
       for(int k = 0; k < lgr.grid[0].size(); k++ ){
         for(int l = 0; l < lgr.grid[0][0].size(); l++ ){
           Vertex coord;
           coord.coords << i,j,k;
           coord.gpHostZone = 0;
           coord.gpHostFace = 0;
           coord.calculated = 0;
           vertexDB.push_back(coord);
           lgr.grid[j][k][l] = &(vertexDB.back());
         }
       }
     }

     for(int j = 0; j < lgr.grid.size(); j++ ){
       for(int k = 0; k < lgr.grid[0].size(); k++ ){
         for(int l = 0; l < lgr.grid[0][0].size(); l++ ){
           std::cout << "At ("<< i << ","<< j << ","<< k << "," << l << ")\n";
           std::cout << lgr.grid[j][k][l]->coords<<"\n\n";
         }
       }
     }
   }
   return 1;
 }
#包括
#包括
#包括
#包括
#包括
#包括
#包括
#包括
#包括
#包括
#包括“Line.h”
#包括
#包括
类型定义结构{
本征::矢量三维坐标;
int gpHostZone;
int-gpHostFace;
int计算;
}顶点;
类LGR{
公众:
LGR(整数i、整数j、整数k):
网格(boost::区段[i][j][k])
{
};
std::字符串名;
std::媒介宿主区;
std::向量细化;
boost::多_阵列网格;
std::矢量数据;
};
内部主(空){
LGR LGR(11,11,21);

std::cout以下是导致未定义行为的明确问题,与
boost::multiarray
无关

这些线路:

std::vector<Vertex> vertexDB;
//...
vertexDB.push_back(coord);
lgr.grid[j][k][l] = &(vertexDB.back());
无法保证您以前分配的地址有效


一个快速修复方法是使用
std::list
,因为向
std::list
添加项不会使迭代器/指针无效。

lgr.grid[j][k][l]=&(vertexDB.back());
--在向量中存储指向项的指针不是一个好主意。如果向量的迭代器变大,指向项的指针变为无效。好吧,现在我觉得有点傻。在您解释过之后,这是一个明显的问题。使用列表对测试代码来说效果很好(不幸的是,我无法测试真正的代码,因为不知何故,我需要的一个类被完全破坏了,现在我必须重新创建它…)。不管怎样,它是有效的。谢谢PaulMcKenzie。。。
std::cout << lgr.grid[j][k][l]->coords<<"\n\n";