STL算法设计理念--二元谓词在set集合中的应用

具体看如下代码:

#include<iostream>
#include "string"
#include <vector>
#include <list>
#include "set"
#include <algorithm>
#include "functional"
using namespace std;

template<typename T>
class CompareNoCase
{
public:

	bool operator()(const T& str1,const T& str2) const  //二元谓词
	{
		T str1_;
		str1_.resize(str1.size());
		transform(str1.begin(),str1.end(),str1_.begin(),tolower);   //预定义函数对象

		T str2_;
		str2_.resize(str2.size());
		transform(str2.begin(),str2.end(),str2_.begin(),tolower);

		return (str1_ < str2_);
	}
};

void main()
{
	set<string> set1;
	set1.insert("bbb");
	set1.insert("aaa");
	set1.insert("ccc");
	set<string>::iterator it = set1.find("aAa");  //find函数默认不区分大小写
	if (it == set1.end())
	{
		cout << "没有查找到 aaa" << endl;  //输出:没有查找到aaa
	}
	else
	{
		cout << "查找到 aaa" << endl;
	}


	set<string, CompareNoCase<string>> set2;
	set2.insert("bbb");
	set2.insert("aaa");
	set2.insert("ccc");
	set<string>::iterator it2 = set2.find("aAa");  //find函数默认不区分大小写
	if (it2 == set2.end())
	{
		cout << "没有查找到 aaa" << endl;
	}
	else
	{
		cout << "查找到 aaa" << endl;  //输出:查找到aaa
	}
}

发布了293 篇原创文章 · 获赞 113 · 访问量 25万+

猜你喜欢

转载自blog.csdn.net/tianguiyuyu/article/details/105609505