在C++ STL中的unordered_set emplace_hint()函数

在C++ STL中的unordered_set emplace_hint()函数

unordered_set :: emplace_hint()函数是C ++ STL中一种内置函数,仅在插入的值具有给定提示的唯一时才在unordered_set中插入一个新元素。

语法:

unordered_set_name.emplace_hint( position,value )

参数: 此函数接受如上所述的两个参数并描述如下:

  • 位置: 此参数用于描述插入操作的位置。
  • 值: 此参数用于包含需要插入的值。

返回值: 如果值不在unordered_set中,则函数插入该值并返回指向插入元素的迭代器。否则,如果值已存在于unordered_set中,则函数返回指向该元素的迭代器。以下程序说明了C++ STL中的unordered_set::emplace_hint()函数:

程序1:

// CPP program to illustrate
// unordered_set::emplace_hint() function
#include <iostream>
#include <unordered_set>
using namespace std;
 
// main program
int main()
{
 
    // Initialize an unordered_set
    unordered_set<int> uset = { 20, 40, 50, 60 };
 
    // Insert an element that is not present
    uset.emplace_hint(uset.begin(), 80);
 
    // Display uset
    cout << "uset: ";
    for (auto it = uset.begin(); it != uset.end(); it++)
        cout << *it << " ";
}  

输出:

uset: 80 20 40 50 60

程序2:

// CPP program to illustrate
// unordered_set::emplace_hint() function
#include <iostream>
#include <unordered_set>
using namespace std;
 
// main program
int main()
{
 
    // Initialize an unordered_set
    unordered_set<int> uset = { 20, 40, 50, 60 };
 
    // Try to Insert an element that is not present
    uset.emplace_hint(uset.begin(), 50);
 
    // Display uset
    cout << "uset: ";
    for (auto it = uset.begin(); it != uset.end(); it++)
        cout << *it << " ";
}  

输出:

uset: 60 50 40 20

时间复杂度: O(n)

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

C++ 教程