如何在二进制C ++中用向量保存struct数组

时间:2013-07-31 04:35:14

标签: c++ vector struct binaryfiles

我需要在二进制文件中保存一个struct数组。但是有一些问题!我的结构中有一些3d矢量数组!这是我的结构:

struct State
{
    vector<bool> ***value;
    vector<int> ***rfcCLB2Bits;
    State()
    {
      new3dArray(value , 60 , 100 , 2);
      new3dArray(rfcCLB2Bits , 60 , 100 , 2);
    }

};

你可能想看看new3dArray函数:

template <class T>
void new3dArray(T ***&u3d, int nx , int ny , int nz)
{
    u3d = new T ** [nx];
    if (NULL == u3d)
    {
      cout <<"erro3"<<endl;
    }
    else
    {
        for (int i = 0; i < nx; i++)
        {
            u3d[i] = new T *[ny];
            if (NULL == u3d[i])
            {
                cout <<"erro4"<<endl;
            }
            else
            {
                for (int j = 0; j < ny; j++)
                {
                    u3d[i][j] = new T [nz];
                    if (NULL == u3d[i][j])
                    {
                        cout <<"erro5"<<endl;
                    }
                }
            }
        }
    }
}

最后我的保存和加载代码:

int main()
{
    State *states;
    int k ;
    cin >> k;
    states = new State[k];

    ...

    string location = "save1.bin";
    ofstream fs(location, std::ios::out | std::ios::binary | std::ios::app);
    fs.write(reinterpret_cast<const char *>(states), sizeof(states));
    fs.close();

    ...

    ifstream file (location, ios::in|ios::binary|ios::ate);
    if (file.is_open())
    {
        file.seekg (0, ios::beg);
        file.read ((char*)&states, sizeof(states));
        file.close();
    }

    ...
}

但它没有用!我必须做什么?

0 个答案:

没有答案