C++ STL 中的 emplace 與 insert


emplace 操作避免不必要地複製物件,與 insert 操作相比,它以更高的效率完成插入操作。Insert 操作引用一個物件。

演算法

Begin
   Declare set.
   Use emplace() to insert pair.
   Use insert() to insert pair by using emplace().
   Print the set.
End

示例程式碼

#include<bits/stdc++.h>
using namespace std;
int main() {
   set<pair<int, char>> s;
   s.emplace(7, 'a');
   s.insert(make_pair(6, 'b'));
   for (auto it = s.begin(); it != s.end(); ++it)
      cout << " " << (*it).first << " " << (*it).second << endl;
   return 0;
}

輸出

7 a
6 b

更新時間: 30-Jul-2019

1K+ 瀏覽

開啟您的職業生涯

完成課程即可獲得認證

開始學習
廣告