std::multimap

std::multimap

  • multimap,是一個關聯性容器,用於存放這樣的元素,這些元素是由鍵以及關聯的值組成.容器內容將根據元素的鍵進行排序.而且容器能夠插入多個具備相同鍵的元素.
    less

接口

  • pair<const_iterator,const_iterator> equal_range(const key_type &k)const;返回一個區間,包含容器中全部鍵爲 k 的元素.
    spa

大小寫不敏感的 multimap

  • 首先看一下 multimap 的原型,以下:code

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;
}
本站公眾號
   歡迎關注本站公眾號,獲取更多信息