18 lines of code AC_sort HDU-1106 (sstream simple solution)

Inspirational use less code for efficient expression.


Problem describe

Enter a line of numbers. If we regard the '5' in this line of numbers as spaces, then we will get a line of non-negative integers separated by spaces (some integers may start with '0', and the '0' in these heads should Ignored, unless the integer is composed of a number of '0', then the integer is 0).
Your task is to sort and output the integers obtained from these divisions in ascending order.

Input

The input contains multiple sets of test cases, and each set of input data has only one line of numbers (no spaces between the numbers), and the length of this line of numbers is not greater than 1000.
Input data guarantee: the non-negative integer obtained by division will not be greater than 100000000; the input data cannot be composed of all '5'.

Output

For each test case, output the result of the integer sorting obtained by the division, separated by a space between two adjacent integers, and each group of output occupies one line.


Thematic analysis

Question: Given a character string, divide it by 5, and sort and output the divided data. The character string cannot be all 5, and the maximum value of each data is 10E.

I have seen a lot of solutions on the Internet. A lot of code even eloquently wrote more than a hundred lines. The so-called lack of consideration, a special judgement to make it . Many of these codes are used in special judgments of conditions.

But I think the original intention of the questioner is not to examine the details, but to examine the usage of C language stroke()函数or C++ sstream.

Here I use the sstream header file split function. The specific approach is:

First, traverse the string and replace all 5 with spaces. Then use stringstream to convert the string into an int variable. With the while loop, the variable will be automatically divided with spaces as the boundary, and then sorted after being stored in the array.

It only took 18 lines of code to successfully AC. Is not it simple! ! !

If you don’t understand the sstream header file, please click here -> the magical sstream header file (free conversion between integer and string)


Code display

#include<bits/stdc++.h> 
using namespace std;
int main() {
    
    
	ios::sync_with_stdio(false);
	string s; 
	while(cin>>s) {
    
    
		int len = s.length(); 
		for(int i = 0; i < len; i++) 
			if(s[i] == '5') s[i] = ' ';
		
		int num;
		vector<int>v;
		stringstream ss; ss << s; 
		while(ss >> num) v.push_back(num);
		
		sort(v.begin(), v.end());
		int len1 = v.size();
		for(int i = 0; i < len1; i++) cout<<v[i]<<(i==len1-1?'\n':' '); 
	}
return 0; }


If this article has helped you, please give the blogger a like! Let more people see it.

Guess you like

Origin blog.csdn.net/weixin_43899069/article/details/108665283