【问题标题】:C++ Vector of Vectors. Array get rotated in 90 degrees向量的 C++ 向量。阵列旋转 90 度
【发布时间】:2017-10-07 21:49:13
【问题描述】:

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

输入:

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

有人能解释一下为什么它会变大吗?

【问题讨论】:

  • 显示您的打印代码。

标签: c++ arrays vector 2d


【解决方案1】:

您应该使用格式化的输入选项,如果是固定输入,请相信它们。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多