[問題] C++ map的用法(solved)

看板C_and_CPP (C/C++)作者 (  )時間11年前 (2014/07/14 17:17), 11年前編輯推噓3(307)
留言10則, 3人參與, 最新討論串1/1
開發平台(Platform): (Ex: VC++, GCC, Linux, ...) VC++, G++ 問題(Question): 我期望可以像python的Dic有一樣(或是類似的功能) 也就是 map[key] = value 這樣的用法, 在C++論壇上是說用map實作是沒問題的。 不過我實際在implement的時候, 當我的key 型態(或是value)是std::string的時候, compile就會出現錯誤,錯誤碼是 error C2784: 'bool std::operator <(const std::move_iterator<_RanIt> &,const std::move_iterator<_RanIt2> &): 無法由 'const std::string',針對 'const std::move_iterator<_RanIt> &' 推算 樣板 引數 (類似的有四項,包括reverse_iterator, _Revanit, pair) 和 error C2676: 二元運算子 '<' : 'const std::string' 沒有定義此運算子或預先定義運 算子可接受的型別轉換 但是如果把 std::string 的部分換成 char * 編譯就沒問題 網路上找到std::string的example也都是編不過.... 但是這個設計,不能使用位址map(使用char*),畢竟每個新的char * 位址都不同 請問各位,要用 std::string map 的話,應該調整什麼? 程式碼(Code):(請善用置底文網頁, 記得排版) <partial> std::string string1, string2; string1 = "parameter"; string2 = "value"; std::map<std::string, std::string> mymap; mymap.insert(std::pair<std::string, std::string>(string1, string2)); </partial> -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 118.166.143.197 ※ 文章網址: http://www.ptt.cc/bbs/C_and_CPP/M.1405329459.A.4C9.html ※ 編輯: chigi (118.166.143.197), 07/14/2014 17:21:16

07/14 17:36, , 1F
理論上這應該要沒問題...你的 VC++ 版本是?
07/14 17:36, 1F

07/14 17:37, , 2F
另外 STL 提供了 make_pair 讓你省去寫 std::pair<> 的麻煩
07/14 17:37, 2F

07/14 17:39, , 3F
visual 2012, 如果可以希望把這個做成到處用的cpp檔..
07/14 17:39, 3F

07/14 17:41, , 4F
雖然可能不太相關, 你有 #include <string> 嗎?
07/14 17:41, 4F

07/14 17:42, , 5F
因為這看起來像是編譯器找不到 operator<(string,string)
07/14 17:42, 5F

07/14 17:46, , 6F
恩,我沒有include <string> XD 我試試看。
07/14 17:46, 6F

07/14 17:47, , 7F
過..過了,來人阿給我一把刀,我要切腹。謝謝LPH66
07/14 17:47, 7F

07/15 05:05, , 8F
其實就算再絕望也不該傳入char*, 這是危險動作
07/15 05:05, 8F

07/15 05:05, , 9F
一般來講需要要當key的話 會hash這個char*內容字串
07/15 05:05, 9F

07/15 05:05, , 10F
要當value的話,請務必用string
07/15 05:05, 10F
文章代碼(AID): #1Jmw0pJ9 (C_and_CPP)
文章代碼(AID): #1Jmw0pJ9 (C_and_CPP)