2013-09-30 15 views
11

我是新來的stl's。這是我的下面的程序。如何讓stl :: map不區分大小寫

typedef pair<string, int> p; 
int main(int argc, char *argv[]) 
{ 
    map<string,int> st; 
    st.insert(p("hello",1)); //Inserted "hello" as key to map. 
    st.insert(p("HELLO",1)); //Inserted "HELLO" as key to map. 
    cout<<"size="<<st.size()<<endl; //Output is 2 because two records found "hello" and "HELLO" 
    return 0; 
} 

我不想考慮的情況下,反覆變化(大寫爲小寫字或反之亦然)。這裏「st.insert(p(」HELLO「,1));」應該失敗,因此沒有。的記錄應該是「1」而不是「2」。是否有任何標誌設置或類似?

我無法找到相關的問題,因此發佈了這個問題。

任何幫助是感謝。

+3

最簡單的方法是在添加到地圖之前將它們變成小寫。 – zch

回答

26

使用自定義比較:

struct comp { 
    bool operator() (const std::string& lhs, const std::string& rhs) const { 
     return stricmp(lhs.c_str(), rhs.c_str()) < 0; 
    } 
}; 

std::map<std::string, int, comp> st; 

編輯: 如果你不能夠使用stricmpstrcasecmp使用:

#include<algorithm> 
//... 
string tolower(string s) { 
    std::transform(s.begin(), s.end(), s.begin(), ::tolower); 
    return s; 
} 
struct comp { 
    bool operator() (const std::string& lhs, const std::string& rhs) const { 
     return tolower(lhs) < tolower(rhs); 
    } 
}; 

std::map<std::string, int, comp> st; 
+6

我不會推薦第二個選項(使用'tolower'函數),因爲它會創建一個新的字符串。這意味着每個比較運算符有幾個'new'和'delete'。這將極大地減慢你的速度。此外,它平均將「O(1)」(第一個字符中的大多數字符串不同)與「O(s)」比較,其中s是字符串的平均大小。所以,而不是一個單一的字符比較,你得到2'新',2'刪除',2xs'tolower' ...沒有。 – rabensky

+0

你能解釋爲什麼返回<0而不是== 0?我認爲,使用str *** cmp函數時,小於零表示左手邊是右手的子字符串,其中等號匹配爲0. – 2015-11-08 15:13:57

+1

@TechnikEmpire該映射基於「小於」比較:默認比較器是'std :: less'謂詞。通過檢查'stricmp(lhs,rhs)'是否小於0來實現同樣的行爲。 –

2

有兩種方法可以做到這

首先 - 更改「比較」功能忽略案例

第二 - 每當你使用一個字符串來放置或從地圖獲取一個值時,用一個把它變成小寫的函數來包裝它。

對於你首先需要做的是建立一個「功能類」(與運營商級())接收兩個字符串並返回左邊是「小」的比對:

struct my_comparitor{ 
    bool operator()(const std::string &a, const std::string &b){ 
    // return iwhether a<b 
    } 
}; 

std::map<std::string,DATA_TYPE,my_comparitor> my_map; 

對於第二隻是這樣做:

std::map<std::string,DATA_TYPE> my_map; 
my_map.insert(std::make_pair(TO_LOWERCASE("hello"),1)); 
iter=my_map.find(TO_LOWERCASE(key)); 
cout << my_map[TO_LOWERCASE(name)]; 
// etc. 

我不知道如果轉換爲小寫的功能已經是STL的一部分 - 但無論哪種方式,它很容易編寫。