如何在向量向量的开头添加新行

时间:2015-10-26 11:41:59

标签: c++ vector

我想在矢量矢量的开头添加一个新行。我有一个3x3矢量,我想要一个4x3。这是我的代码:

typedef vector<int> state;
typedef vector<vector<int> > board;

int val;
string s;

while (getline (in, s)) {
    istringstream iss (s);

    while (iss >> val)
        boards.push_back(val);
}

sizeb = boards.front();

for (auto it = boards.cbegin()+1; it <= boards.cbegin()+pow(sizeb, 2); ++it)
    sstart.push_back(*it);

start.resize(sizeb); 

for (int i = 0; i < sizeb; ++i)
    start[i].resize(sizeb);

for (int i = 0; i < sizeb; i++)
    for (int j = 0; j < sizeb; j++)
        start[i][j] = sstart[(i * sizeb) + j];

当我尝试执行sizeb + 1时,它会添加一个新行,但也会添加一个新列。

你能帮帮我吗?

1 个答案:

答案 0 :(得分:0)

  

如何在矢量矢量的开头添加新行

您可以使用std::vector::insert

执行此操作
  

当我尝试执行sizeb + 1时,它会添加一个新行,但也会添加一个新列。

那是因为你使用循环调整每一行的大小:

// I'm assuming that start is the vector of vectors

start.resize(sizeb); // this changes the number of rows

for (int i = 0; i < sizeb; ++i)
    start[i].resize(sizeb); // these change the number of columns in each row