STL实现字符串的去重和排序(使用unique和sort)

4 篇文章 0 订阅

最近发现STL中的algorithm中有各种算法可以直接用,现在实现一个字符串的排序和去重功能。

字符串按照首字母和长度排序,去除相同的字符串

效果:

代码:

#if 1

#include <iostream>
#include <string>
#include <vector>
#include<algorithm>
using namespace std;
bool compare1(string a, string b)               //添加长度的规则
{
	return a.size()<b.size();
}
bool compare2(string a, string b)               //添加首字符的排序规则
{
	return a[0]<b[0];
}
int main()
{
	vector<string> s = { "cat","ant" ,"ant","wall",
		"cat","house" , "wall","tent" ,"cat","dog" ,"cat"};
	cout << "排序前:\n";
	for (int j = 0; j < s.size(); j++)
	{
		cout << s[j] << "  "<<endl;
	}
	cout << "排序后:\n";
	vector<string>::iterator it_1 = s.begin();
	vector<string>::iterator it_2 = s.end();
	vector<string>::iterator new_end;
	sort(it_1, it_2, compare2);//排序
	sort(it_1, it_2, compare1);
 	new_end = unique(it_1, it_2);//去重
	s.erase(new_end, it_2);
	for (int j = 0; j < s.size(); j++)
	{

		cout << s[j] << endl;
	}
	system("pause");
	return 0;
}
#endif

函数简单说明

一、排序的函数:sort,sort函数的底层实现是用的快排,sort有两种用法。

1.一种是传入两个参数,迭代器的头指针、尾指针。默认顺序排序

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

int main()
{
	vector<int> num = { 5,4,1,6,9,5,2 };
	vector<int>::iterator ib = num.begin();
	vector<int>::iterator ie = num.end();
	sort(ib, ie);//顺序排序
	for (int i = 0; i < num.size(); i++)//输出
	{
		cout << num[i] << " ";

	}

	system("pause");
	return 0;

}

2.一种是传入三个参数,前两个为迭代器指针,第三个为排序方式

#include <iostream>
#include <vector>
#include<algorithm>
using namespace std;
bool compare(int a, int b)
{
	return a > b;
}
int main()
{
	vector<int> num = { 5,4,1,6,9,5,2 };
	vector<int>::iterator ib = num.begin();
	vector<int>::iterator ie = num.end();
	sort(ib, ie,compare);//按compare函数中的方式排序
	for (int i = 0; i < num.size(); i++)//输出
	{
		cout << num[i] << " ";
	}
	system("pause");
	return 0;
}

二、去重的函数unique

去重的函数一般与删除一起使用,单独使用只是比较了前后相同的值而已。

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

int main()
{
	vector<int> num = { 5,5,4,1,4,3,3};
	vector<int>::iterator ib = num.begin();
	vector<int>::iterator ie = num.end();
	vector<int>::iterator new_end = num.end();
	new_end = unique(ib, ie);//去重
	num.erase(new_end, ie);
	for (int i = 0; i < num.size(); i++)//输出
	{
		cout << num[i] << " ";
	}
	system("pause");
	return 0;
}

发现只能去除临近的相同的数,如果要全部去除,需要先排序完再去重。

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值