当前位置: 移动技术网 > 移动技术>移动开发>IOS > STL中关联式容器的compare

STL中关联式容器的compare

2020年07月27日  | 移动技术网移动技术  | 我要评论

关联式容器排序准则(执行期指定)

#ifndef _COMPARE_H
#define _COMPARE_H
#include<algorithm>
#include<string>
#include<iostream>
#include<iomanip>
class RuntimeStringCmp
{
	
public:
	enum cmp_mode
	{
		normal, nocase
	};
	RuntimeStringCmp(const cmp_mode& m = normal) :mode(m) {}
	bool operator()(const std::string& s1, const std::string& s2)const
	{
		if (mode == normal)
			return s1 < s2;
		else
			return lexicographical_compare(s1.begin(), s1.end(), s2.begin(), s2.end(), nocase_compare);
	}
	

private:
	const cmp_mode mode;
	static bool nocase_compare(char C1, char C2)
	{
		return toupper(C1) < toupper(C2);
	}
	
};

typedef std::map<std::string, std::string, RuntimeStringCmp> StringStringMap;

template <typename T>
void print(T& maps)
{
	std::cout.setf(std::ios::left, std::ios::adjustfield);
	typedef T::const_iterator pos;
	for (pos iter = maps.begin(); iter != maps.end(); ++iter)
	{
		std::cout << std::setw(15) << iter->first << " " << iter->second << std::endl;
	}
	std::cout << std::endl;
		
		
}
void fillAndPrint(StringStringMap& coll)
{
	coll["Deutschland"] = "Germay";
	coll["deutsch"] = "German";
	coll["Haken"] = "snag";
	coll["arbeiten"] = "work";
	coll["Hund"] = "dog";
	coll["gehen"] = "go";
	coll["Unternehmen"] = "enterprise";
	coll["unternehmen"] = "undertake";
	coll["gehen"] = "walk";
	coll["Hestatter"] = "undertaker";
	print(coll);
}
#endif // !_COMPARE_H

测试

#include<map>
#include<iostream>
#include"compare.h"
int main()
{

	StringStringMap colll;
	fillAndPrint(colll);
	RuntimeStringCmp ignorecase(RuntimeStringCmp::nocase);
	StringStringMap coll2(ignorecase);
	fillAndPrint(coll2);

	std::cout << "Hello World!" << std::endl;


}

运行结果

在这里插入图片描述

分析

RuntimeStringCmp ignorecase(RuntimeStringCmp::nocase);
///<在运行程序期间决定关联式容器的排序准则,“忽略大小写”
StringStringMap coll2(ignorecase);

注意

如果将比较函数的operator函数对象定义为以下:

bool operator()(const std::string& s1, const std::string& s2)
	{
		if (mode == normal)
			return s1 < s2;
		else
			return lexicographical_compare(s1.begin(), s1.end(), s2.begin(), s2.end(), nocase_compare);
	}

会出现这样的错误:
在这里插入图片描述
分析:出现这样的原因跟关联式容器map的“key”是常数类型有关,函数对象不能修改“key”
所以,必须将函数对象定义为const函数对象:

bool operator()(const std::string& s1, const std::string& s2)const 
	{
		if (mode == normal)
			return s1 < s2;
		else
			return lexicographical_compare(s1.begin(), s1.end(), s2.begin(), s2.end(), nocase_compare);
	}

本文地址:https://blog.csdn.net/weixin_44312010/article/details/107581087

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网