C++ 带逗号输入数组(大厂笔试输入出现多次)

Posted 行码阁119

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C++ 带逗号输入数组(大厂笔试输入出现多次)相关的知识,希望对你有一定的参考价值。

1、第一种情况

输入形式:

输入的数据在nums中保存

1,2,3,4,60,70,5
# include<iostream>
# include<vector>
# include<string>
using namespace std;

int main() 
	string s;
	cin >> s;
	int start = 0;
	int num = 0;
	vector<int> nums;
	for (int i = 0; i < s.size(); i++) 
		if (s[i] == ',') 
			string temp = s.substr(start, i - start);
			nums.push_back(atoi(temp.c_str()));
			num++;
			start = i + 1;
		
	
	string temp = s.substr(start, s.size() - start + 1);
	nums.push_back(atoi(temp.c_str()));

	for (int i = 0; i < nums.size(); i++) 
		cout << nums[i] << " ";
	

	system("pause");
	return 0;

2、第二种情况:

输入形式:

在nums 数组中保存

8
1,2,30,100,50,2,7,5

输出形式:

1 2 30 100 50 2 7 5

代码:

# include<iostream>
# include<vector>
# include<string>
using namespace std;

int main() 
	int n;
	cin >> n;
	string s;
	cin >> s;
	int start = 0;
	int num = 0;
	vector<int> nums;
	for (int i = 0; i < s.size(); i++) 
		if (s[i] == ',') 
			string temp = s.substr(start, i - start);
			nums.push_back(atoi(temp.c_str()));
			num++;
			start = i + 1;
		
		if (num == n - 1) 
			string temp = s.substr(start, s.size() - start + 1);
			nums.push_back(atoi(temp.c_str()));
			break;
		
	

	for (int i = 0; i < n; i++) 
		cout << nums[i] << " ";
	

	system("pause");
	return 0;

3、第三种情况:

非重叠区间的总长度

在nums 二维数组中保存

# include<iostream>
# include<vector>
# include<string>
# include<algorithm>
using namespace std;


static bool cmp(vector<int>& a, vector<int>& b) 
	if (a[0] == b[0]) 
		return a[1] < b[1];
	
	return a[0] < b[0];


int main() 
	int n;
	cin >> n;
	vector<string> str;
	for (int i = 0; i < n; i++) 
		string mys;
		cin >> mys;
		str.push_back(mys);
	
	vector<vector<int>> nums;
	int t = 0;
	while (t < n) 
		vector<int> q;
		string s = str[t];
		int start = 0;
		int num = 0;
		for (int i = 0; i < s.size(); i++) 
			if (s[i] == ',') 
				string temp = s.substr(start, i - start);
				q.push_back(atoi(temp.c_str()));
				num++;
				start = i + 1;
			
			if (num == 1) 
				string temp = s.substr(start, s.size() - start + 1);
				q.push_back(atoi(temp.c_str()));
				break;
			
		
		t++;
		nums.push_back(q);
	

	sort(nums.begin(), nums.end(), cmp);

	int sum = 0;
	int l = nums[0][0];
	int r = nums[0][1];
	for (int i = 1; i < nums.size(); i++) 
		int l1 = nums[i][0];
		int r1 = nums[i][1];
		if (r <= l1) 
			sum += (r - l);
			l = l1;
			r = r1;
		
		else if (r > l1 && r1 > r) 
			sum += (l1 - l);
			l = r;
			r = r1;
		
		else if (r > l1 && r1 <= r) 
			sum += (l1 - l);
			l1 = r1;
			r = r;
		
	
	sum += r - l;
	cout << sum << endl;
		
	system("pause");
	return 0;

以上是关于C++ 带逗号输入数组(大厂笔试输入出现多次)的主要内容,如果未能解决你的问题,请参考以下文章

C++ 带逗号输入数组(大厂笔试输入出现多次)

笔试数组输入模板

C ++逗号分隔的输入数组代码过早退出

校招C++笔试ACM模式输入处理

校招C++笔试ACM模式输入处理

C++笔试处理复杂输入输出