调试 C++ Primer Exercise 5.14 的心得体会

题目:

Write a program to read strings from standard input looking for duplicated words. The program should find places in the input where one word is followed immediately by itself. Keep track of the largest number of times a single repetition occurs and which word is repeated. Print the maximum number of duplicates, or else print a message saying that no word was repeated.

程序:

#include <iostream>
#include <string>
#include <vector>
using namespace std;

int main()
{
	string word_now;
	string word_last = "";
	vector<string> champion;
	int sum_last = 1;
	int sum_now = 1;
	while (cin >> word_now)
	{
		if (word_now == word_last)
			sum_now++; // the same word, count!
		else
		{
			if (sum_now > sum_last)
			{
				sum_last = sum_now;
				champion.clear();
				champion.push_back(word_last);
			} // now it is the largest, mop away the previous memory and write in new contents.
			else
			{
			    if (sum_now == sum_last)
				    champion.push_back(word_last);
			} // as large, its a champion as well as previous ones
			sum_now = 1;
		}
		word_last = word_now;
	}
	// Now test the last word.
	if (sum_now > sum_last)
	{
		sum_last = sum_now;
		champion.clear();
		champion.push_back(word_now);
	}
	else
	{
	    if (sum_now == sum_last)
		    champion.push_back(word_now);	
	}
	// output
	if (sum_last == 1) cout << "No word was repeated." << endl;
	else
	{
		if (champion.size() == 1) cout << "The max number of duplicates is " << sum_last << ".\nIt is:";
		else cout << "The max number of duplicates is " << sum_last << ".\nThey are:";
		for (auto c : champion) cout << c << " ";
		cout << endl;
	}
	return 0;
}

注:champion不一定只有一个!所以用 vector 存储。

一开始连续都只输出No word was repeated.,后来发现是忘记第30行内容。
启示:loop 进入新一轮准备工作要做好

后来输出champion的值时有时出现两个,发现是判断最后一词时忽略了顺序造成的影响。在37行sum_last = sum_now;的操作后,43行的 if 一定成立。
启示:要检查程序实际运行逻辑,改变参数要关注对之后内容的影响


【C++ Primer(5th Edition) Exercise】练习程序 - Chapter5(第五章)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值