从零开始的紫书刷题1:stl篇之安迪的第一个字典

本文介绍了如何使用C++的set数据结构,配合string流和tolower/isalpha函数,对输入文本中的单词进行去重并按字典序排序,展示了处理连续字母序列并忽略大小写的问题解决方案。
摘要由CSDN通过智能技术生成

在开始做这个题目之前,我们首先需要知道set的基本用法:

这些是它的常用函数:

insert();//插入一个元素;

count();//判断容器中是否存在某个元素

earse();//删除集合中某个元素

clear();//清空集合

此外,与vector不同的是,set并不能用下标法来来遍历,我们使用迭代器;

set<int> s;
for(set<int>::iterator it=s.begin();it!=s.end();it++)  cout<<*it<<'\n;

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

输入:

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

输出:

a

adventures

blondes

came

......

利用set可以自动排好序(默认升序)的特性,用一个string类型的set容器来存放输入的单词,再利用迭代器将元素输出即可。由于文本存在非字母字符,我们可以使用isalpha()和tolower函数处理字符串(题目要求不区分大小写)。代码如下:

#include <bits/stdc++.h>
using namespace std;
set<string> dict;

int main() {
	string s, buf;
	while (cin >> s) {
		for (int i = 0; i < s.length(); i++)
			if (isalpha(s[i]))
				s[i] = tolower(s[i]);
			else
				s[i] = ' ';
		stringstream ss(s);
		while (ss >> buf)
			dict.insert(buf);
	}

	for (set<string>::iterator it = dict.begin(); it != dict.end(); ++it)
		cout << *it << '\n';
	return 0;
}

这其中还有一个需要提及的是stringtream的使用。我是这样理解的,把每次输入的字符串s经过处理(大写换小写、非字母被去除)存入一片缓冲区,从缓冲区中每读出一个字符串,将它添加到set中。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值