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

更新於:2020-03-05

瀏覽量:108

啟動您的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.