2015-10-26 65 views
-2

我想在矢量矢量的開始處添加新行。我有一個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時,它會添加一個新行,但也會添加一個新列。

你能幫我嗎?

+4

爲什麼不使用'vector.insert()'來插入新行? – Logicrat

+0

你的代碼中間有一個裸體'vector '。那是什麼?顯然它不會編譯。 –

+0

是的,這是一個錯誤。只是忽略它hahaha – Elena

回答

0

How to add a new row at the begin of a vector of vectors

你可以用std::vector::insert來做到這一點。

When I try to do sizeb+1 it adds a new row but also a new column.

那是因爲你使用循環調整的每一行:

// 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 
+0

我收到「錯誤:沒有可行的重載」='「錯誤。 – Elena

+0

@Elena還行。你的代碼有問題。 – user2079303

+0

和它有什麼不對? – Elena