用仿函数实现以std::string作为key的map自定义排序

 起因:前缀相同、后半部分为递增数字的std::string作为Map的key时希望按数字部分的大小排序,如预期排序为item0, item1,...item9, item10的一些字符串作为map的key, 在map中默认排序是item0,item1,item10,item2,...item9.

 目标:用仿函数实现以std::string作为key的map自定义排序

 实现:

class SortId //注意:仿函数重载的是()而不是<
{
public:
	bool operator () (const std::string & id1, const std::string & id2) const
	{
		int i=0;
		int m1=0,m2=0;
		while(i='0' && id1[i]<='9')
			{
				m1=i;
				break;
			}
			i++;
		};
		i=0;
		while(i='0' && id2[i]<='9')
			{
				m2=i;
				break;
			}
			i++;
		};
		int a = atoi(id1.substr(m1).c_str());
		int b = atoi(id2.substr(m2).c_str());
		if(a==b)
			return id1 ChildMap;


你可能感兴趣的:(用仿函数实现以std::string作为key的map自定义排序)