您的位置:首页 > 编程语言 > C语言/C++

C++ Primer复习和学习笔记 第六章 语句

2015-01-01 11:06 316 查看
/*
编写一个小程序,从标准输入读入一系列 string 对象,寻找连续重复出现的单词。程序应该找出满足以下条件的
单词的输入位置:该单词的后面紧跟着再次出现自己本身。跟踪重复次数最多的单词及其重复次数。输出重复次
数的最大值,若没有单词重复则输出说明信息。例如,如果输入是: how, now now now brown cow cow 则输出应表明“now”这个单词出现了三次。
*/
#include "iostream"//本程序使用栈实现具体的功能  关键是vs.push_back()   vs.pop_back()
#include "vector"
#include "string"

using namespace std;

int main()
{
	vector<string>  vs;
	string str;
	while (cin>>str)
	{
		vs.push_back(str);
	}
	int num_new=1;
	int num_old=0;

	string  str_old;
	string  str_new;

	vector<string>  vs_heap;
	vector<string>::iterator  vs_heap_head=vs.begin();

	for (vector<string>::iterator iter=vs.begin();iter!=vs.end();++iter)
	{
		if (vs_heap.size()==0)
		{
			vs_heap.push_back(*iter);
		}
		else//vs_heap.size()!=0			
		{
			if (vs_heap[vs_heap.size()-1]==*iter)
			{
				vs_heap.push_back(*iter);
				++num_new;
				str_new=*iter;
				
			} 
			else//vs_heap[vs_heap.size()-1]!=*iter
			{
				while (vs_heap.size()!=0)
				{
					vs_heap.pop_back();
					
				}
				num_new=1;
				vs_heap.push_back(*iter);
			}
		}
		if (num_new>num_old)
		{
			num_old=num_new;
			str_old=str_new;
		}
	}

	if (num_old==1)
	{
		cout<<"没有找到相应的重复的元素!"<<endl;
	}
	else//num_old!= 1
	{
		cout<<"重复最多的字符串是"<<str_old<<"--------"<<"重复的次数是"<<num_old<<endl;
	}
	return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: