C++ STL 中的 multimap::emplace_hint()


在本文中,我们将讨论 C++ STL 中 multimap::emplace_hint() 函数的工作原理、语法和示例。

什么是 C++ STL 中的 Multimap?

Multimap 是关联容器,类似于 map 容器。它还有助于以特定顺序存储由键值和映射值组合而成的元素。在 multimap 容器中,可以有多个元素与同一个键相关联。数据在内部始终借助其关联的键进行排序。

什么是 multimap::emplace_hint()?

emplace_hint() 函数是 C++ STL 中的内置函数,它在 <map> 头文件中定义。此函数在 multimap 容器中插入一个新元素,并带有一个位置。在 emplace_hint() 中,我们传递带有位置的元素,该位置充当提示。此函数类似于 emplace(),区别在于我们提供了一个位置提示来插入值。此函数还会将 multiset 容器的大小增加 1。

语法

multimap_name.emplace_hint(iterator pos, Args& val);

参数

该函数接受以下参数:

  • pos - 这是迭代器类型的参数,用于提供位置提示。

  • val - 这是我们要插入的元素。

返回值

此函数返回一个迭代器,指向放置/插入元素的位置。

输入

std::multimap<char, int> odd, eve;
odd.insert({‘a’, 1});
odd.insert({‘b’, 3});
odd.insert({‘c’, 5});
odd.emplace_hint(odd.end(), {‘d’, 7});

输出

Odd: a:1 b:3 c:5 d:7

示例

在线演示

Code:
#include <bits/stdc++.h>
using namespace std;
int main(){
   //create the container
   multimap<int, int> mul;
   //insert using emplace
   mul.emplace_hint(mul.begin(), 1, 10);
   mul.emplace_hint(mul.begin(), 2, 20);
   mul.emplace_hint(mul.begin(), 3, 30);
   mul.emplace_hint(mul.begin(), 1, 40);
   mul.emplace_hint(mul.begin(), 4, 50);
   mul.emplace_hint(mul.begin(), 5, 60);
   cout << "\nElements in multimap is : \n";
   cout << "KEY\tELEMENT\n";
   for (auto i = mul.begin(); i!= mul.end(); i++){
      cout << i->first << "\t" << i->second << endl;
   }
   return 0;
}

输出

如果我们运行上述代码,它将生成以下输出:

Elements in multimap is :
KEY ELEMENT
1 40
1 10
2 20
3 30
4 50
5 60

更新于: 2020年4月22日

132 次浏览

开启您的 职业生涯

完成课程获得认证

开始学习
广告
© . All rights reserved.