2010-11-27 30 views
14

大文字小文字を区別しない挿入方法またはstd :: setの文字列を検索する方法は?例 -大文字と小文字を区別しないstd ::文字列のセット

std::set<std::string> s; 
s.insert("Hello"); 
s.insert("HELLO"); //not allowed, string already exists. 
+1

あなたは「大文字と小文字を区別挿入」が何を意味するのかビットを明確にすることはできますか? – Jon

答えて

31

利用可能であるあなたは、カスタムコンパレータを定義する必要があります。私はこれを読んだものから、

struct InsensitiveCompare { 
    bool operator() (const std::string& a, const std::string& b) const { 
     return stricmp(a.c_str(), b.c_str()) < 0; 
    } 
}; 

std::set<std::string, InsensitiveCompare> s; 
+11

私がInsensitiveCompareを読んだとき、私は義母を考えるのを助けることができませんでした。 +1。 – Fozi

+0

文字列にNUL文字がある場合、この方法は正しく機能しません。 [この質問](https://stackoverflow.com/questions/11635/case-insensitive-string-comparison-in-c)を参照してください。 – Sauron

2

のstd ::セットについて

は(ほとんどのstdコンテナがそうであるように)あなた自身の比較子を提供する可能性を提供しています。次に、好きなタイプの比較を実行できます。全例がhere

0

は(stricmpよりもポータブルである)stricmp()が実際にはstdライブラリの一部ではないので、ほとんどのコンパイラベンダーのみが実装しています。その結果、私の解決策はあなた自身のロールバックだけです。

#include <string> 
#include <cctype> 
#include <iostream> 
#include <set> 

struct caseInsensitiveLess 
{ 
    bool operator()(const std::string& x, const std::string& y) 
    { 
    unsigned int xs (x.size()); 
    unsigned int ys (y.size()); 
    unsigned int bound (0); 

    if (xs < ys) 
     bound = xs; 
    else 
     bound = ys; 

    { 
     unsigned int i = 0; 
     for (auto it1 = x.begin(), it2 = y.begin(); i < bound; ++i, ++it1, ++it2) 
     { 
     if (tolower(*it1) < tolower(*it2)) 
      return true; 

     if (tolower(*it2) < tolower(*it1)) 
      return false; 
     } 
    } 
    return false; 
    } 
}; 

int main() 
{ 
    std::set<std::string, caseInsensitiveLess> ss1; 
    std::set<std::string> ss2; 

    ss1.insert("This is the first string"); 
    ss1.insert("THIS IS THE FIRST STRING"); 
    ss1.insert("THIS IS THE SECOND STRING"); 
    ss1.insert("This IS THE SECOND STRING"); 
    ss1.insert("This IS THE Third"); 

    ss2.insert("this is the first string"); 
    ss2.insert("this is the first string"); 
    ss2.insert("this is the second string"); 
    ss2.insert("this is the second string"); 
    ss2.insert("this is the third"); 

    for (auto& i: ss1) 
    std::cout << i << std::endl; 

    std::cout << std::endl; 

    for (auto& i: ss2) 
    std::cout << i << std::endl; 

} 

大文字小文字を区別しないセットと同じ 発注示す通常のセットと出力:

This is the first string 
THIS IS THE SECOND STRING 
This IS THE Third 

this is the first string 
this is the second string 
this is the third 
+0

小さな発言:たとえば、ギリシャ語のテキストでは、通常は 'tolower'だけで大文字と小文字を区別しない比較を実装することはできないため、これはうまくいきません。この不可能のための教科書の例は、大文字と小文字を区別しないΣΣΟΣであり、これはσσοςと同じです(これはギリシャ語で「多くの人」と同じです)。 –

関連する問題