簡體   English   中英

使用C ++ STL將C樣式的字符串映射到int?

[英]Map C-style string to int using C++ STL?

stringint映射工作正常。

std::map<std::string, int> // working

但是我想將C-style字符串映射到int

例如:

char A[10] = "apple";
map<char*,int> mapp;
mapp[A] = 10;

但是,當我嘗試訪問映射到“蘋果”的值時,我得到的是垃圾值而不是10。為什么它的行為與std::string

 map<char*,int> mapp; 

它們的鍵類型不是“ c string” 至少不是這樣,如果我們將c字符串定義為“帶有空終止符的字符數組”。 鍵類型為char* ,它是指向字符對象的指針。 區別很重要。 您沒有在地圖中存儲字符串。 您正在存儲指針,並且字符串位於其他位置。

除非您使用自定義比較功能對象,否則默認情況下std::map使用operator<(const key_type&,key_type&) 當且僅當兩個指針指向同一個對象時,它們才相等。

這是三個對象的示例:

char A[] = "apple";
char B[] = "apple";
const char (&C)[6] = "apple"

前兩個是數組,第三個是左值引用,該引用綁定到也是數組的字符串文字對象。 作為單獨的對象,它們的地址當然也不同。 因此,如果您要編寫:

mapp[A] = 10;
std::cout << mapp[B];
std::cout << mapp[C];

每個輸出將為0,因為您尚未初始化mapp[B]mapp[C] ,因此它們將由operator[]進行值初始化。 即使每個數組包含相同的字符,鍵值也不同。

解決方案:不要使用operator<來比較指向c字符串的指針。 使用std::strcmp代替。 對於std::map ,這意味着使用自定義比較對象。 但是,您尚未完成警告。 您仍然必須確保字符串必須保留在內存中,只要它們由映射中的鍵指向即可。 例如,這將是一個錯誤:

char A[] = "apple";
mapp[A] = 10;
return mapp; // oops, we returned mapp outside of the scope
             // but it contains a pointer to the string that
             // is no longer valid outside of this scope

解決方案:請注意范圍,或僅使用std::string

可以做到,但是您需要更智能的string版本:

struct CString {
    CString(const char *str) {
        strcpy(string, str);
    }
    CString(const CString &copy); // Copy constructor will be needed.
    char string[50]; // Or char * if you want to go that way, but you will need
                     // to be careful about memory so you can already see hardships ahead.
    bool operator<(const CString &rhs) {
        return strcmp(string, rhs.string) < 0;
    }
}

map<CString,int> mapp;
mapp["someString"] = 5;

但是,您可能會看到,這是一個巨大的麻煩。 可能有些事情我也錯過或忽略了。

您還可以使用比較功能:

struct cmpStr{
    bool operator()(const char *a, const char *b) const {
        return strcmp(a, b) < 0;
    }
};

map<char *,int> mapp;
char A[5] = "A";
mapp[A] = 5;

但是有很多外部內存管理,如果A s內存消失但映射仍然存在,UB會發生什么。 這仍然是一場噩夢。

只需使用std::string

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM