STL中关联式容器的compare

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

#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);
	}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值