简体   繁体   English

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

[英]C++ Vector of Vectors. Array get rotated in 90 degrees

I have a very stupid problem which drives me mad. 我有一个非常愚蠢的问题,这使我发疯。

Input: 输入:

0 3 0
0 3 0
0 3 0

Code: 码:

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);
}

But what I get is: 但是我得到的是:

0 0 0
3 3 3
0 0 0

Can someone explain me why it heapens? 有人可以解释为什么它会堆积吗?

You should be using your formatted input options, and in the case of fixed inputs, just believe them. 您应该使用格式化的输入选项,对于固定输入,只需相信它们即可。

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 );
}

If you wish to print your matrix, also use row→column order: 如果要打印矩阵,请使用行→列顺序:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM