C++ map emplace_hint() 函数

30 Aug 2024 | 3 分钟阅读

C++ map emplace_hint() 函数用于通过使用提示作为元素位置将新元素插入到容器中来扩展 map 容器。元素是直接构造的(既不复制也不移动)。

元素的构造函数通过向此函数传递参数 args 来调用。只有当键尚未存在时才进行插入。

语法

参数

args:用于构造要插入到 map 中的元素的参数。

position:插入新元素的建议位置。

返回值

它返回一个指向新插入元素的迭代器。如果元素已存在,则插入失败并返回一个指向现有元素的迭代器。

示例 1

让我们看一个简单的例子来将元素插入到 map 中。

输出

Map contains following elements
a = 10
b = 20
c = 30
d = 40
e = 50

在上面的示例中,它只是将元素与给定的键值对和位置一起插入到 map m 中。

示例 2

让我们看一个简单的例子。

输出

  map starting data: 3 elements: 
(Rakesh,Accounting) (Ram,Accounting) (Sunil,Engineering) 

map modified, now contains 4 elements: 
(Deep,Engineering) (Rakesh,Accounting) (Ram,Accounting) (Sunil,Engineering)

示例 3

让我们看一个简单的示例,将元素插入到具有给定位置的 map 中。

输出

mymap contains: [a:12] [b:10] [c:14]

示例 4

让我们看一个简单的例子来插入元素。

输出

Enter the number of fmly members : 3
Enter the name and age of each member: 
Ram 42
Sita 37
Laxman 40

Total memnber of fmly is:3
Details of fmly members: 

Name    |  Age 
__________________________
Laxman | 40 
Ram      | 42 
Sita       | 37

在上面的示例中,它只是根据用户的选择将元素插入到 map 的开头。

下一个主题C++ Map