填充std :: vector时出现"vector <T>太长"错误

use*_*180 1 c++ vector

我试图用称为细胞的对象填充二维向量(817乘577).这些单元格具有一组成员值(浮点数,其他向量等).在某个时刻程序停止并抛出错误"vector<T> too long".这是单元格的类定义和完整的循环:

struct cell
    {
    int x;
    int y;
    int country;
    vector<int> popO;
    vector<int> popS;
    vector<float> Rainfall;
    double Cropland;
    vector<movement> outm;
    vector<movement> inm;
    vector<double> AgeMaleFemale;
    vector<double> AgeMaleFemaleMortality;
    double Fertility;
    };
vector<vector<cell>> cells;
void fillCells(dataserver D)
        {
        cout<<"start filling"<<endl;
        int rows=577;
        int columns=817;
        cell X;
        vector<vector<cell>> output(rows,vector<cell>(columns,X));
        cout<<"start loop"<<endl;
        for (int i=0;i<rows;i++)
            {
            cout<<i<<" ";
            for (int j=0;j<columns;j++)
                {
                int p=-9999;
                cell tmpC;
                tmpC.x=i;
                tmpC.y=j;
                tmpC.country=D.CO[i][j];
                tmpC.popO.resize(3,0);
                tmpC.popO[0]=int(D.PO[0][i][j]);
                tmpC.popO[1]=int(D.PO[1][i][j]);
                tmpC.popO[2]=int(D.PO[2][i][j]);
                tmpC.Rainfall.resize(10,0);
                for (int k=0;k<10;k++)
                    {
                    tmpC.Rainfall[k]=D.R[k][i][j];
                    }
                tmpC.popS.resize(10,0);
                tmpC.Cropland=D.CPC[i][i];
                if (tmpC.country!=-9999)
                    {
                    tmpC.Fertility=D.F[tmpC.country];
                    tmpC.AgeMaleFemale.resize(18,0);
                    tmpC.AgeMaleFemale=D.AMF[tmpC.country];
                    tmpC.AgeMaleFemaleMortality.resize(18,0);
                    tmpC.AgeMaleFemaleMortality=D.M[tmpC.country];
                    }
                output[i][j]=tmpC;
                }
            }
        cells=output;
        }
Run Code Online (Sandbox Code Playgroud)

谷歌搜索了一下我发现sizeof(cell)乘以向量中的单元格数量应该小于vector :: max_size()

sizeof(cell)是144 - > 144*817*577 = 67882896

max_size是268345455

那时候所有的细胞都不应该有足够的空间,或者我错过了什么?提前致谢!

一些额外的信息:

在Windows 7 64bit上运行,使用Visual Studio 2010进行编译,32位

关于max_size的信息实际上来自这里: stl"vector <T>太长了"

小智 9

由于我没有足够的代表评论,所以你得到它作为答案.

错误文本听起来像你在Windows机器上 http://msdn.microsoft.com/en-us/library/2af6btx2%28v=vs.80%29.ASPX

而且我认为这与调整大小有关,因为创建一个太大的向量会抛出bad_alloc(在linux上,所以在windows上可能会有所不同).

尝试并将所有调整大小的调用包装在一个

try {
    // resize call here
} catch (Exception &e) {
    std::cerr << e.what() << std::endl
              << "Some text that identifies the line" << std::endl;
}
Run Code Online (Sandbox Code Playgroud)

  • 这就是代表障碍不起作用的原因.人们认为代表障碍是迫使他们打破系统,而不是说"哦,好吧,我现在会闭嘴".令人讨厌的是,这是一个糟糕的例子,因为你的"评论"是富有洞察力和有用的.谢谢发帖!我的意思是,真的,这是一个答案...... (6认同)