为什么 sort() 不起作用? [英] why is the sort() not working?
本文介绍了为什么 sort() 不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我把这个简单的程序读入了一个像13 11 9 10"这样的字符串中.我想拆分字符串然后对它们进行排序.但是 sort() 似乎不起作用,有什么帮助吗?输入:13 11 9 10,输出:13 11 9 10谢谢!
I got this simple program read in a string like "13 11 9 10". I wanna split string then sort them. however the sort() seems not working, any help? input: 13 11 9 10 , output: 13 11 9 10 Thanks!
#include <string>
#include <sstream>
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
vector<int> split(string s)
{
istringstream iss(s);
vector<int> result;
do{
string sub;
iss>>sub;
if(sub!="")
result.push_back((int)atoi(sub.c_str()));
}while(iss);
return result;
}
int main(void)
{
string s;
while(cin>>s)
{
vector<int> vec;
vec=split(s);
sort(vec.begin(), vec.end());
for (int i = 0; i < vec.size(); ++i)
{
cout<<vec[i]<<endl;
}
}
}
推荐答案
那是因为 cin >>s
在第一个空格处停止.
That's because cin >> s
stops at the first whitespace.
换句话说,如果你输入 1 4 2 3
,s
只包含 1
,而不是整行.
In other words, if you type 1 4 2 3
, s
contains 1
only, and not the entire line.
相反,使用以下内容阅读整行:
Instead, use the following to read the entire line:
std::getline(std::cin, s);
这篇关于为什么 sort() 不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文