编程语言
首页 > 编程语言> > 关于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

 

标签:map,multimap,cm,int,c++,插入,print,include
来源: https://blog.csdn.net/digitalkee/article/details/113760965