在本文中,我们将讨论C ++ STL中的set::emplace_hint()函数,其语法,工作原理和返回值。
C ++ STL中的集合是必须按常规顺序具有唯一元素的容器。集必须具有唯一元素,因为元素的值标识该元素。一旦在集合容器中添加了值,以后就无法修改,尽管我们仍然可以删除或将值添加到集合中。集用作二进制搜索树。
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