C++ ACM 模式通用数组输入输出模板
本文介绍了在 ACM/ICPC 模式下,使用 C++ 处理数组输入输出的通用模板。内容涵盖单组、多组以及不确定长度数组的输入方式,配合快速 I/O 提升性能,并提供默认空格分隔输出和避免末尾多余空格的处理方法。模板可直接用于比赛,减少输入输出处理时间,让选手专注于算法实现。
2026-03-252 min 阅读
C++ACMI/O
在 LeetCode 中,我们通常用函数参数传入数组并返回结果。但在 ACM/ICPC 模式下,一切都基于 标准输入输出,你必须自己解析输入并将结果输出到标准输出。本文整理了一个 C++ 通用模板,适合单组、多组或未知长度数组输入,比赛中可以直接使用。
1. 快速 I/O 配置
在比赛中,输入输出往往是性能瓶颈,特别是大数据量。推荐在模板开头加上:
ios::sync_with_stdio(false);
cin.tie(nullptr);
ios::sync_with_stdio(false);关闭 C++cin/cout与 C 的scanf/printf同步,提高性能。cin.tie(nullptr);解除cin与cout的绑定,减少不必要的刷新。
注意:一旦使用这两行,不要再混用 scanf/printf。
2. 单组数组输入输出
假设输入:
5
1 3 2 4 5
- 第一行:数组长度
n - 第二行:数组元素,空格分隔
C++ 实现:
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n;
cin >> n;
vector<int> arr(n);
for(int i = 0; i < n; ++i) cin >> arr[i];
// 输出数组
for(int x : arr) cout << x << " ";
cout << "\n";
return 0;
}
默认输出每个元素后加一个空格,最后再换行。 如果题目要求不能有多余空格,可以参考最后一节说明。
3. 多组输入(固定组数)
输入格式:
2
3
1 2 3
4
2 4 6 8
- 第一行:组数
t - 每组第一行:数组长度
n - 每组第二行:数组元素
C++ 实现:
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int t;
cin >> t;
while(t--) {
int n;
cin >> n;
vector<int> arr(n);
for(int i = 0; i < n; ++i) cin >> arr[i];
// 输出当前数组
for(int x : arr) cout << x << " ";
cout << "\n";
}
return 0;
}
4. 多组输入(不确定组数,直到 EOF)
如果题目没有给出组数,输入一直读到文件末尾:
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int x;
vector<int> arr;
while(cin >> x) { // 读到 EOF 自动结束
arr.push_back(x);
}
for(int x : arr) cout << x << " ";
cout << "\n";
return 0;
}
5. 一行数组输入(长度未知)
输入格式:
1 3 2 4 5
实现:
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
string line;
getline(cin, line);
stringstream ss(line);
vector<int> arr;
int x;
while(ss >> x) arr.push_back(x);
for(int x : arr) cout << x << " ";
cout << "\n";
return 0;
}
getline + stringstream可处理任意长度数组- 自动忽略多余空格
6. 避免最后多余空格
在默认模板中,每个元素输出后都加了一个空格,最后再换行。这在大多数题目中不会出错,但如果题目严格要求末尾不能有多余空格,可以改成:
for(int i = 0; i < arr.size(); ++i) {
if(i > 0) cout << " ";
cout << arr[i];
}
cout << "\n";
- 这样第一个元素前不会加空格
- 后续元素前加空格,末尾不会有多余空格
7. 总结
- 在 ACM/ICPC 模式下,数组输入输出需要自己处理
- 使用快速 I/O 提升性能
- 模板适用单组、多组或不确定长度数组
- 默认输出用
cout << x << " "简单快速,如果题目严格要求末尾无空格,再用条件判断