关于c++中map插入元素的问题
                                                            生活随笔
收集整理的這篇文章主要介紹了
                                关于c++中map插入元素的问题
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.                        
                                ?1.為何map<int,int>和map<string,int> 有不同的操作呢?
#include <string> #include <iostream> #include <list> #include <vector> #include <set> #include <map> using namespace std; int main() { multimap<int,int> m = {{1,1},{2,2}}; pair<int,int> p{2,3}; //下面的一句代碼想給m增加一個元素,這個元素關鍵字是2值是3 m[p.first] = p.second;return 0; }編譯的時候引發錯誤? ?m[p.first] = p.second;? 就這句,說明不能通過map_object[key] = value? 的方法增加元素嗎?map_objece是一個map類型的對象,key是關鍵字,value是一個值,但是看下面的一個例子
#include <iostream> #include <list> #include <vector> #include <set> #include <map> using namespace std; int main() { multimap<int,int> m = {{1,1},{2,2}}; pair<int,int> p{2,3}; //下面這句就錯了,g++給出的錯誤提示是:no match for ‘operator[]’ (operand types are //‘std::multimap<int, int>’ and ‘int’) //我的理解就是:multimap<int,int> and int 沒有匹配的操作符號[] //map<int,int>沒有匹配的操作[],難道關鍵字其他類型就可以? m[1] = 2; map<int,int> m2; //下面這句同樣錯誤 m2[1] = 2; map<string,int> m3; //下面就可以呀,可以按照 map_object[key] = value 的格式賦值(事實上,這是python字典賦值方式) m3["name1"] = 2; cout << m3["name1"] << endl;return 0;}結論,map<type1,type2> ,用python3方式賦值的時候,type1是string的時候是可以的,是不是只要關鍵字不是int就可以?
#include <string> #include <iostream> #include <list> #include <vector> #include <set> #include <map> using namespace std; void print_(map<char,int>& ); int main() { multimap<int,int> m = {{1,1},{2,2}}; pair<int,int> p{2,3}; map<char,int> cm; //下面這句話就是可以的,也就是關鍵字類型事char是可以的 cm['a'] = 1234; print_(cm);return 0;} void print_(map<char,int> & m) { for(auto i : m){cout << "key :" << i.first << endl;cout << "value:" << i.second << endl;}} ~下面把map的關鍵字還是char類型,值類型換成string,還是可以的,
#include <string> #include <iostream> #include <list> #include <vector> #include <set> #include <map> using namespace std; void print_(map<char,string>& ); int main() { multimap<int,int> m = {{1,1},{2,2}}; pair<int,int> p{2,3}; map<char,string> cm; cm['a'] = "1234"; print_(cm);return 0; } void print_(map<char,string> & m) { for(auto i : m){cout << "key :" << i.first << endl;cout << "value:" << i.second << endl;}} ~琢磨著,估計關鍵字類型不是int類型(或者unsigned,size_t那些整形)就可以了,下面試試把關鍵字改成float看可以不:
#include <string> #include <iostream> #include <list> #include <vector> #include <set> #include <map> using namespace std; void print_(map<float,string>& ); int main() { multimap<int,int> m = {{1,1},{2,2}}; pair<int,int> p{2,3}; map<float,string> cm; cm[1.234] = "1234"; cm[2.323] = "434"; print_(cm);return 0;} void print_(map<float,string> & m) { for(auto i : m){cout << "key :" << i.first << endl;cout << "value:" << i.second << endl;} }運行結果如下:?
key :1.234 value:1234 key :2.323 value:434只要key不是int或者是其它整形,都是可以通過map[key] = value;來賦值
總結
以上是生活随笔為你收集整理的关于c++中map插入元素的问题的全部內容,希望文章能夠幫你解決所遇到的問題。
 
                            
                        - 上一篇: python3 创建简单的游戏窗口,并有
- 下一篇: c语言字符串的一个简单例子,把一个字符串
