C++标准库---map综合应用

学习了STL--map,然后通过下面的示例,将练习以下技巧:

1.如何使用map;

2.如何撰写和使用仿函数;

3.如何在执行期定义排序准则;

4.如何在“不在乎大小写”的情况下比较字符串;


示例代码:

//运用map,string并于执行期指定排序准则
#include<iostream>
#include<iomanip>
#include<map>
#include<string>
#include<algorithm>

using namespace std;

class RuntimeStringCmp
{
public:
	enum cmp_mode{normal,nocase};
private:
	const cmp_mode mode;
	static bool nocase_compare(char c1,char c2)//逐字符比较
	{
		return toupper(c1)<toupper(c2);
	}
public:
	RuntimeStringCmp (cmp_mode m=normal):mode(m) {}//默认为normal
	bool operator()(const string& s1,const string& s2) const  //仿函数内部执行细节
	{
		if(mode==normal)
		{
			return s1<s2;//不区分大小写
		}
		else
		{
			return lexicographical_compare(s1.begin(),s1.end(),s2.begin(),s2.end(),nocase_compare);//区分大小写,每个字符都不计大小写比较
		}
	}
};

typedef map<string,string,RuntimeStringCmp> StringStringMap;//使用仿函数来作为排序准则

void fillAndPrint(StringStringMap& coll);

int main()
{
	RuntimeStringCmp normal_;//默认normal

	StringStringMap coll1(normal_);//不加normal_即为默认
	fillAndPrint(coll1);// 安插过程使用operator<,不区分大小写

	RuntimeStringCmp ignorecase(RuntimeStringCmp::nocase);

	StringStringMap coll2(ignorecase);
	fillAndPrint(coll2);// 安插过程使用operator<,区分大小写

	system("pause");
	return 0;
}

void fillAndPrint(StringStringMap& coll)
{
	coll["Deutschland"]="Germany";
	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["Bestatter"]="undertaker";

	StringStringMap::iterator pos;
	cout.setf(ios::left,ios::adjustfield);
	for(pos=coll.begin();pos!=coll.end();++pos)
	{
		cout<<setw(15)<<pos->first.c_str()<<" "<<pos->second.c_str()<<endl;
	}
	cout<<endl;
}

运行结果:


运行结果分析:

1.coll1使用一个型别为RuntimeStringCmp的缺省仿函数,这个函数以元素的operator<来执行比较操作;

2.coll2使用一个型别为RuntimeStringCmp的仿函数,并以nocase为初值,而nocase会令这个仿函数以“大小写无关”模式来完成字符串的比较和排序。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值