C++ STL 中的 set::emplace_hint() 函数
本文将讨论 C++ STL 中的 set::emplace_hint() 函数,包括其语法、工作原理和返回值。
什么是 C++ STL 中的 Set?
C++ STL 中的 Set 是一种容器,它必须包含按一定顺序排列的唯一元素。Set 必须包含唯一元素,因为元素的值标识该元素。一旦将值添加到 Set 容器中,就不能再修改它,尽管我们仍然可以从 Set 中删除或添加值。Set 使用二叉搜索树。
什么是 set::emplace_hint()?
emplace_hint() 函数是 C++ STL 中的一个内置函数,在头文件中定义。此函数在 Set 容器中插入一个新元素,并带有一个位置提示。在 emplace_hint() 中,我们传递元素和一个位置,该位置充当提示。当且仅当没有其他值等于要插入的值时,才会插入该元素。该函数从提示位置开始搜索,并找到要放置元素的位置。
语法
Set1.emplace_hint(iterator position, const type_t& value);
参数
此函数接受两个参数:一个用于提示位置,另一个是要放置的元素。
**位置** - 这是提示位置,搜索从这里开始查找要放置的值的位置。此位置只是为了加快函数的工作速度,此函数并不指定要放置的元素的确切位置。
**值** - 我们必须放置的实际值。
返回值
如果元素成功插入,则此函数返回指向新插入元素的迭代器。
示例
Input: set mySet; mySet.emplace_hint(mySet.begin(), 0); mySet.emplace_hint(i, 1); mySet.emplace_hint(i, 2); mySet.emplace_hint(i, 1); Output: Elements are : 0 1 2
示例
#include <bits/stdc++.h>
using namespace std;
int main(){
set<int> mySet;
auto i = mySet.emplace_hint(mySet.begin(), 0);
i = mySet.emplace_hint(i, 1);
mySet.emplace_hint(i, 2);
mySet.emplace_hint(i, 1);
cout<<"elements are : ";
for (auto i = mySet.begin(); i != mySet.end(); i++)
cout << *i<< " ";
return 0;
}输出
如果我们运行以上代码,则会生成以下输出:
Elements are : 0 1 2
示例
#include <iostream>
#include <set>
#include <string>
int main (){
std::set<std::string> mySet;
auto i = mySet.cbegin();
mySet.emplace_hint (i,"best");
i = mySet.emplace_hint (mySet.cend(),"point");
i = mySet.emplace_hint (i,"is the");
i = mySet.emplace_hint (i,"tutorials");
std::cout<<"string is : ";
for(const std::string& str: mySet)
std::cout << ' ' << str;
std::cout << '\n';
return 0;
}输出
如果我们运行以上代码,则会生成以下输出:
String is : best is the point tutorials
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP