Andy‘s First Dictionary C++ STL set应用

2023-07-30 10:49:13 浏览数 (1)

题目描述

原文:

Andy, 8, has a dream - he wants to produce his very own dictionary. This is not an easy task for him, as the number of words that he knows is, well, not quite enough. Instead of thinking up all the words himself, he has a briliant idea. From his bookshelf he would pick one of his favourite story books, from which he would copy out all the distinct words. By arranging the words in alphabetical order, he is done! Of course, it is a really time-consuming job, and this is where a computer program is helpful. You are asked to write a program that lists all the different words in the input text. In this problem, a word is defined as a consecutive sequence of alphabets, in upper and/or lower case. Words with only one letter are also to be considered. Furthermore, your program must be CaSe InSeNsItIvE. For example, words like “Apple”, “apple” or “APPLE” must be considered the same.

简单来说:输入一个文本,找出所有不同的单词(连续的字母序列)按照字典序从小到大输出。单词不区分大小写。

Input

The input file is a text with no more than 5000 lines. An input line has at most 200 characters. Input is terminated by EOF.

Output

Your output should give a list of different words that appears in the input text, one in a line. The words should all be in lower case, sorted in alphabetical order. You can be sure that he number of distinct words in the text does not exceed 5000.

Sample Input

Adventures in Disneyland Two blonds were going to Disneyland when they came to a fork in the road. The sign read: "Disneyland Left." So they went home.

Sample Output

a adventures blonds came disneyland fork going home in left read road sign so the they to two went were when

思路分析

主要是通过set的自动排序来完成,当然我们首先得把单词分离出来再装进set里面。

一个英文文本里面空格隔开的会含有一个单词,但是同时也会有其他字符像 " , . !之类的也是会包含在字符串中,因此我们需要转变一下这些字符串,判断单个字符串中的单个字符是不是字母,不是就把它变成空格,是就把它变成小写字母,因为输入是全小写的,那为什么要变成空格呢,因为可以通过stringstream去掉空格,stringstream是一个神奇的东西,可以把空格当成分割。

set自己会完成集合的工作,不会有重复的元素,会自动升序排序,最后输入元素的时候,我们只需要通过迭代器来输入就可以了。

为了自己方便自己调试,我会加入一行代码来让系统知道我数据输入完了:

if(temp=="####")break;

详情见注释^_^ 

代码

代码语言:javascript复制
#include<iostream>
#include<set>
#include<string>
#include<sstream>
using namespace std;
int main() {
	set<string> dictionary;//创建一个集合 
	string temp;//创建一个string类字符串 
	while(cin>>temp){//挨个读取字符串 
		for(auto & i :temp)//提取单词
		if(isalpha(i))
		i=tolower(i);//把大写变小写
		else i=' ';//非字母变空格 
		stringstream turn(temp);//创建stringstream类对象,去掉字符串的空格 
		turn>>temp;//从stringstream类对象里面提取字符串 
		dictionary.insert(temp);//装进集合里面去 
	}
	for(set<string>::iterator i=dictionary.begin();i!=dictionary.end();i  )//用迭代器输出集合里面的元素 
	cout<<*i<<endl;
}

0 人点赞