怎么用insert函数给map容器添加元素?

怎么用insert函数给map容器添加元素?,第1张

m1.insert(make_pair("lucy",20))改成m1.insert(make_pair(string("lucy"),20))

make_pair是std::pair的helper function,是个函数模板,根据参数确定匹配的pair的元素类型,所以LZ的用法弄出来的元素是pair&ltchar* int&gt类型的。

insert函数

string&insert ( size_t pos1, const string&str, size_t pos2, size_t n )

Inserts a copy of a substring of str at character position pos1. The substring is the portion of str that begins at the character position pos2 and takes up to n characters (it takes less than n if the end of str is reached before).

string&insert ( size_t pos1, const string&str, size_t pos2, size_t n )

Inserts a copy of a substring of str at character position pos1. The substring is the portion of str that begins at the character position pos2 and takes up to n characters (it takes less than n if the end of str is reached before).

我只知道两种方法:

一、利用下标法:

m1[str] = val

先查找有没有str这个元素,如有,不作任何 *** 作,没有的话,添加str并给str关联的对象赋值也可以只写m1[str]

二、利用函数

m1.insert(e),e为pair型,即,val_type,如果,e.fitst不在map中,刚添加e

m1.insert(beg, end) beg, end, 为元素迭代器,必须是val_tyle型

m1.insert(iter, e) 如果e.first不在m中,创建新元素,并以iter为起点找新元素的位置.

楼上的比我快一步,不好意思!

首先包含头文件

#include <string>

#include <map>

using namespace std

如下写法均合法:

map<string, int>word_count

word_count["string_1"] = 1

word_count.insert(make_pair<string, int>("string_2", 2))

word_count.insert(map<string, int>::value_type("string_3", 3))

在Visual Studio 2010中编译通过。


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/bake/11539082.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-16
下一篇 2023-05-16

发表评论

登录后才能评论

评论列表(0条)

保存