1 2 3 4 5 6
每行一個向量,空格分隔,行數不固定,以 EOF 結束 (Ctrl+Z / Ctrl+D)。
#include <iostream>
#include <sstream>
#include <vector>
#include <string>
using namespace std;
void readMatrix(vector<vector<int>>& matrix)
{
string line;
while (getline(cin, line)) // 讀整行
{
if (line.empty()) continue; // 跳過空行
stringstream ss(line);
vector<int> row;
int val;
while (ss >> val) // 按空格解析整數
row.push_back(val);
if (!row.empty())
matrix.push_back(move(row)); // 移動語義避免拷貝
}
}
int main()
{
vector<vector<int>> mat;
readMatrix(mat);
// 輸出驗證
for (const auto& row : mat) {
for (int v : row) cout << v << ' ';
cout << '\n';
}
return 0;
}
| 技術點 | 作用 |
|---|---|
getline(cin, line) | 按行讀取,保留行邊界 |
stringstream ss(line) | 將行字符串轉為流,支持 >> 運算符 |
ss >> val | 自動跳過空白字符,解析 int |
move(row) | C++11 移動語義,高效轉移所有權 |
if (row.empty()) continue;ss >> val 失敗會停止,可檢查 ss.fail() 跳過row.size() == expectedColsmatrix.reserve(1000); row.reserve(100);int rows, cols;
cin >> rows >> cols;
vector<vector<int>> mat(rows, vector<int>(cols));
for (int i = 0; i < rows; ++i)
for (int j = 0; j < cols; ++j)
cin >> mat[i][j];
「按行讀取 + 字符串流解析」是處理不定列矩陣輸入的通用模板,值得收藏。