|
最近复习STL ,练习一个简单题目"找出一句话(单词用空格隔开)中最长的单词和最短的单词"
我先把单词都存到一个string向量中,但不知道是否有有方法可以直接找出最大或最小,感觉我直接写的有些麻烦
希望指点一下 ,红色部分如何更简捷些就能求出向量中各元素的长度
程序代码:
#include<iostream>
#include<string>
#include<vector>
using namespace std;
int main()
{
int max=0,min=10;
string sen("i have got a beautiful dream");//随便一句话(空格隔开各个单词)
string::size_type pos=0,pp=0;
vector<string> word,wmax,wmin;
vector<string>::iterator p;
while((pos=sen.find_first_of(" ",pos))!=string::npos)//通过空格分解单词
{
word.push_back(sen.substr(pp,pos-pp));//把单词存到容器中
pp=++pos;
}
pos=sen.rfind(" ")+1;
word.push_back(sen.substr(pos,sen.size()-pos)); //把最有一个单词存到容器中
p=word.begin();
while(p!=word.end())
{
max=(*p).size()>=max?(*p).size():max;
min=(*p).size()<=min?(*p).size():min;
++p;
}
for(p=word.begin();p!=word.end();++p)
{
if((*p).size()==max)
wmax.push_back(*p);
else if((*p).size()==min)
wmin.push_back(*p);
} //我写的好麻烦
p=wmax.begin();//简单的分别输出最长和最短的单词(s)
cout<<"the longest word:";
while(cout<<" ",p!=wmax.end()) cout<<*p++;
cout<<"\nlength is "<<max<<endl;
p=wmin.begin();
cout<<"the shortest word:";
while(cout<<" ",p!=wmin.end()) cout<<*p++;
cout<<"\nlength is "<<min<<endl;
return 0;
} |
|