C ++矢量矢量。阵列旋转90度

时间:2017-10-07 21:49:13

标签: c++ arrays vector 2d

我有一个非常愚蠢的问题让我发疯。

输入:

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

有人可以解释为什么它会变形吗?

1 个答案:

答案 0 :(得分: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";
}
相关问题