几种常用ACM模版

-
-
2026-08-19 09:51
素材来源于DeepSeek
为了提高输入输出速度,可以在开头加上以下两行:
std::ios::sync_with_stdio(false);
std::cin.tie(nullptr);
 

1. 万能模版

#include <iostream>

int main(int argc, char* argv[])
{
	int n, nSum = 0;
	while (std::cin >> n)
	{
		nSum += n;
		std::cout << nSum << std::endl;
	}
	return 0;
}

2. 读取一行整数

#include <iostream>
#include <string>
#include <sstream>
#include <vector>

int main(int argc, char* argv[])
{
	std::string strLine;
	std::getline(std::cin, strLine);
	std::stringstream ss(strLine);
	std::vector<int> vNum;
	int n;
	while (ss >> n)
	{
		vNum.push_back(n);
	}
	return 0; 
}

3. 读取第一行元素数量,第二行数组

#include <iostream>
#include <vector>

int main(int argc, char* argv[])
{
	int n;
	std::cin >> n;
	std::vector<int> vNum(n);
	for (int i = 0; i < n; ++i)
	{
		std::cin >> vNum[i];
	}
	return 0;
}

4. 读取二维矩阵

#include <iostream>
#include <vector>

int main(int argc, char* argv[])
{
	int nRows, nCols;
	std::cin >> nRows >> nCols;
	std::vector<std::vector<int>> vGrid(nRows, std::vector<int>(nCols));
	for (int i = 0; i < nRows; ++i)
	{
		for (int j = 0; j < nCols; ++j)
		{
			std::cin >> vGrid[i][j];
		}
	}
	return 0;
}

5. 读取带逗号分隔的数据

#include <string>
#include <iostream>
#include <sstream>
#include <vector>
#include <algorithm.h>

int main(int argc, char* argv[])
{
	std::string strData;
	std::cin >> strData;
	std::stringstream ssData(strData);
	std::vector<int> vNum;
	std::string strToken;
	
	while (std::getline(ssData, strToken, ','))
	{
		if (strToken.empty() || std::all_of(strToken.begin(), strToken.end(), [](char c){return isspace(static_cast<unsigned char>(c));}))
		{
			continue;
		}
		vNum.push_back(std::stoi(strToken));
	}
	
	return 0;
}

6. 读取多行数据直到EOF

#include <string>
#include <iostream>

int main(int argc, char* argv[])
{
	std::string strLine;
	while (std::getline(std::cin, strLine))
	{
		
	}
	return 0;
}


目录