vector<string>容器排序以及删除其中相同的string元素

题目要求:

假定已有一个vector,保存了多个故事的文本。我们希望简化这个vector,是的每个单词只出现一次,而不管单词在任意给定文档中到底出现了多少次。

可能这个题目要求读起来有点不好理解,见代码会很清晰:

#include "pch.h"
#include <iostream>
#include<vector>
#include<string>
#include<algorithm>
using namespace std;
void elimdups(vector<string>& word);
int main()
{
	//例 10.9
	/*排序并且删除vector中重复的单词*/
	string b;
	vector<string> a;
	while (cin >> b) {       //当我们输入ctrl+z的时候才会停止,ctrl+z代表一个EOF字符,当cin碰到的时候,cin的状态就会改变
		a.push_back(b);
	}
	elimdups(a);

}
void elimdups(vector<string>& word) {
	sort(word.begin(), word.end());        //利用标准库中的sort函数模板来执行排序
	for (auto b : word)
		cout << b << " ";
	cout << endl;
	 auto b=unique(word.begin(), word.end());
	for (auto b : word)
		cout << b << " ";                         //这里结果会有个疑问,为什么显示倒数第二个the但不显示最后一个turtle呢,
												  //被置为空了吗,那倒数第二个the为什么不被置为空呢
	cout << endl;
	cout << word.capacity() <<" "<< word.size() << endl;
	word.erase(b, word.end());
	for (auto b : word) {
		cout << b << " ";
	}
	cout << endl;
	cout << word.capacity() << " " << word.size() << endl;
}

输入:

fox jumps over quick red red slow the the turtle ctrl+z(cin是while循环中止的条件)

结果如下:

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值