std::multimap
multimap,是一个关联性容器,用于存放这样的元素,这些元素是由键以及关联的值组成.容器内容将根据元素的键进行排序.并且容器可以插入多个具有相同键的元素.
接口
pair<const_iterator,const_iterator> equal_range(const key_type &k)const;返回一个区间,包含容器中所有键为 k 的元素.
大小写不敏感的 multimap
首先看一下 multimap 的原型,如下:
template <typename KeyType, typename ValType,
typename CompareType = std::less<KeyType>,
typename AllocType = std::allocator<std::pair<const KeyType, ValType> > >
class multimap;
-
其中 CompareType 定义了一种规则,使得可以将所有的 KeyType 对象按照先后顺序进行排序,如:obj1,obj2,obj3,...;该规则接受2个类型均为 KeyType 的参数,如 compare(a,b),若返回真,则表示 a 在 b 之前;否则表明 a 与 b 在同一位置,或者 a 在 b 之后(可以认为当返回真时,a<b;当返回假时,a>=b);
/**
* 该类等同于 less<T>,定义了一个规则,所有 Type 类型的数据都可以根据
* 这个规则进行先后排序,只是该类定义的规则在比较字符串时,采用的是大小
* 写不敏感的比较.
* 被认为是字符串类型:ByteArray,std::string,const char*
*/
template<class Type>
struct CaseLess{
bool operator()(const Type &a,const Type &b){
return a<b;
}
};
template<>
struct CaseLess<std::string>{
bool operator()(const std::string &a,const std::string &b){
return strcasecmp(a.data(),b.data()) < 0;
}
};
template<>
struct CaseLess<const char*>{
bool operator()(const char *a,const char *b){
return strcasecmp(a,b) < 0;
}
};
template<>
struct CaseLess<ByteArray>{
bool operator()(const ByteArray &a,const ByteArray &b){
return strcasecmp(a.constData(),b.constData()) < 0;
}
};
int main(int argc,char *argv[]){
std::map<ByteArray,ByteArray,CaseLess<ByteArray> > test_map;
test_map["Hello"] = "World";
puts(test_map["Hello"].constData());/* World */
puts(test_map["hello"].constData());/* World */
puts(test_map["HeLLo"].constData());/* World */
return 0;
}