cc23d_demo-23_21days_Cpp_函数对象c++ 调用操作符的重载与函数对象-二元函数对象-代码示范

cc23d_demo-23_21days_Cpp_函数对象c++ 调用操作符的重载与函数对象-二元函数对象-代码示范

二元谓词

set容器,自动排序

#include <iostream>
#include <set>//set集
#include <string>
#include <algorithm>

using namespace std;
class CCompareStringNoCase
{

public:
	bool operator()(const string&str1, const string& str2) const//不区分大小写----二元谓词
	{
		string str1LowerCase;
		str1LowerCase.resize(str1.size());
		//transform算法
		transform(str1.begin(),str1.end(),str1LowerCase.begin(),tolower);
		//传的tolower函数指针,也可以传函数
		string str2LowerCase;
		str2LowerCase.resize(str2.size());
		transform(str2.begin(), str2.end(), str2LowerCase.begin(), tolower);
		return(str1LowerCase > str2LowerCase); //大于符号,降序排序,小于-升序
	}
};

int main()
{
	//set<string> names;//不写,则是默认的二元谓词,是---区分大小写
	set<string,CCompareStringNoCase> names;//自己写,就可以,不区分大小写,二元谓词可以改变容器的默认的行为
	//cout << "hello" << endl;
	names.insert("Tina");
	names.insert("jim");
	names.insert("Jack");
	names.insert("Sam");
	/*names.insert("3");
	names.insert("1");
	names.insert("2");*/
	names.insert("hello");
	//set<string>::iterator iNameFound = names.find("Jim");
	set<string,CCompareStringNoCase>::iterator iNameFound = names.find("Hello111---");
	for (set<string, CCompareStringNoCase>::iterator ii = names.begin(); ii != names.end(); ii++)
		cout << *ii << " " << endl;
	if (iNameFound != names.end())
	{
		cout << "找到了。。。" << *iNameFound << endl;
	}
	else
	{
		cout << "没找到。。。"  << endl;
		//cout << "没找到。。。" << *iNameFound << endl;//----------------------------如果没有找到,下标溢出了,就报错咯
	}
	getchar();
	return 0;
}
发布了356 篇原创文章 · 获赞 186 · 访问量 89万+

猜你喜欢

转载自blog.csdn.net/txwtech/article/details/103754300