2017-10-07 333 views
0

我有一個非常愚蠢的問題,這讓我很生氣。C++向量的向量。陣列旋轉90度

輸入:

0 3 0 
0 3 0 
0 3 0 

代碼:

vector <vector <int>> lab; 
int W; // number of columns. 
int H; // number of rows. 
cin >> W >> H; cin.ignore(); 
for (int i = 0; i < H; i++) { 
    string LINE; 
    getline(cin, LINE); 
    vector <int> row; 
    for (int j=0;j<LINE.length();j++){ 
     if (LINE[j]!=' '){ 
      row.push_back(LINE[j]-'0'); 
     } 
    } 
    lab.push_back(row); 
} 

但我得到的是:

0 0 0 
3 3 3 
0 0 0 

有人能解釋我爲什麼heapens?

+0

顯示您的打印代碼。 – konserw

回答

0

您應該使用格式化的輸入選項,如果是固定輸入,請相信它們。

typedef int Matrix_Element; 
typedef std::vector <Matrix_Element> Matrix_Row; 
typedef std::vector <Matrix_Row> Matrix; 

Matrix m; 
unsigned rows, cols; 

std::cin >> rows >> cols; 
for (unsigned r = 0; r < rows; r++) 
{ 
    MatrixRow row; 
    for (unsigned c = 0; c < cols; c++) 
    { 
    MatrixNumber n; 
    std::cin >> n; 
    row.emplace_back(n); 
    } 
    m.emplace_back(row); 
} 

如果你想打印矩陣,也使用行→列的順序:

for (auto row : m) 
{ 
    for (auto n : row) 
    std::cout << n << " "; 
    std::cout << "\n"; 
}