库函数
把一行单词 放进数组中
vector< string> word;
stringstream ss(test);
// stringstream ss;
ss<< text;
string temp;
while (ss >> temp)
{
words.push_back(temp);
}
特别注意 cmp 函数写法
普通写法 定义cmp 函数
1)自定义比较函数cmp
比如:
bool cmp(int a,int b)
{
return b<a;
}
重载<
bool operator< (const Student& s1, const Student& s2)
{
if(s1.age==s2.age)
return s1.name <s2.name;//年龄相同时,按姓名小到大排
else return s1.age > s2.age; //从年龄大到小排序
}
class Solution {
public:
struct cmp
{
bool operator() (const string &a, const string &b)
{
return a.size()<b.size();
}
};
定义结构体
struct cmp
{
bool operator() (const Student& s1, const Student& s2)
{
if(s1.age==s2.age)
return s1.name <s2.name;
else return s1.age < s2.age;
}
};
public:
string arrangeWords(string text) {
stringstream ss;
ss<< text;
string temp;
vector<string> words;
while(ss>> temp)
{
words.push_back(temp);
}
if(!words.empty())
{
words[0][0]=tolower(words[0][0]);
}
stable_sort(words.begin(),words.end(),cmp());
string ans="";
for( auto &s:words)
{
ans+=s;
ans+=" ";
}
if(!ans.empty())
ans[0]=toupper(ans[0]);
ans.pop_back();
return ans;
}
};