编程论坛
注册
登录
编程论坛
→
C++教室
读入了一系列string对象,如何寻找其中重复次数最多的单词并将其重复次数记下?
ClarenceC
发布于 2014-01-15 15:49, 734 次点击
读入了一系列string对象,如何寻找其中重复次数最多的单词并将其重复次数记下?
8 回复
#2
yuccn
2014-01-15 16:55
为什么不能?
分析出每个单词。之后
strstr,查找第一个,在跳到这个的末尾,再strstr~~~
#3
ClarenceC
2014-01-15 19:48
回复 2楼 yuccn
对不起,我才开始学习,学校都还没开课,我还不了解有些语句。
我是这样写的:
#include <iostream>
#include<string>
using namespace std;
int main()
{
string dangqian,zhiqian;
int x=0,m=1;//x用于计数但前重复次数,遇到更多重复次数时把x的值给m ,x再重新计数
while(cin>>zhiqian>>dangqian){
if(zhiqian==dangqian){
++x;
}else{
if(x>=m){
m=x;
}
x=1;
}
}
cout<<x<<endl;
return 0;
}
但有一个问题 ,当输入为奇数个的时候就有麻烦了。
#4
rjsp
2014-01-16 11:54
程序代码:
#include
<iostream>
#include
<string>
#include
<map>
using
namespace
std;
int
main()
{
map<
string
,size_t> wordnums;
for
(
string
str;
cin
>>str; )
++wordnums[str];
map<
string
,size_t>::const_iterator maxitor = wordnums.begin();
for
( map<
string
,size_t>::const_iterator itor=wordnums.begin(); itor!=wordnums.end(); ++itor )
{
if
( itor->second > maxitor->second )
maxitor = itor;
}
cout
<< maxitor->first << endl;
return
0
;
}
#5
fl8962
2014-01-17 03:54
你这个while循环要如何结束?我觉得你这么写你这个while循环会一直进行下去,你总的有个结束语言吧。。。
#include<iostream>
#include<vector>
#include<string>
using namespace std;
int main()
{
vector<string> shuru;
string word,judge="yes";
while(judge!="no")
{
cin>>word;
shuru.push_back(word);
cout<<" keep input word,press yes.If not press no"<<endl;
cin>>judge;
}
int i,j,t,max=0;
j=shuru.size();
int mark[1000];
for(i=0;i<j;++i)
{
for(t=i+1;t<j;++t)
{
if(shuru[i]==shuru[t])
mark[i]++;
}
}
for(i=0;i<j;++i)
{
if(mark[i]>max)
{
max=mark[i];
}
}
for(i=0;i<j;++i)
{
if(mark[i]==max)
cout<<"the most frequent word is:"<<shuru[i]<<"the numher of this string is:"<<max<<endl;
}
return 0;
}
感觉咱俩都是菜B,上面R版写的代码估计你都看不懂。。。我这个罗嗦的代码给你参考吧。。。
#6
followme001
2014-01-18 20:23
LS好像忘记了赋初值,int mark[1000];这里面是不确定的值,所以没有输出。
#7
ClarenceC
2014-01-19 14:59
谢谢各位,谢谢。
#8
love云彩
2014-01-20 07:12
总觉得有点过于依赖STL了,如果换一种编程语言来实现这个功能,不能用到STL,又不懂数据结构,代码重用性不高
#9
peach5460
2014-01-20 08:37
以下是引用
love云彩
在2014-1-20 07:12:53的发言:
总觉得有点过于依赖STL了,如果换一种编程语言来实现这个功能,不能用到STL,又不懂数据结构,代码重用性不高
不重复造轮子
1