Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

emplace vs insert in C++ STL


emplace operation หลีกเลี่ยงการ copy object ที่ไม่จำเป็น และทำ insertion ได้มีประสิทธิภาพมากกว่า insert operation Insert operation รับ reference ไปยัง object

Algorithm

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