我總是比較喜歡try_emplace而不是emplace。一個關鍵的區別是,如果密鑰已經存在,則try_emplace不會構造與該密鑰相關聯的對象。這將提高性能,以防該類型的對象創建成本高。
例如,下面的代碼(https://github.com/PacktPublishing/Cpp17-STL-Cookbook/blob/master/Chapter02/efficient_insert_or_reassign_to_map.cpp )
#include <iostream>
#include <functional>
#include <list>
#include <map>
using namespace std;
struct billionaire {
string name;
double dollars;
string country;
};
int main()
{
list<billionaire> billionaires {
{"Bill Gates", 86.0, "USA"},
{"Warren Buffet", 75.6, "USA"},
{"Jeff Bezos", 72.8, "USA"},
{"Amancio Ortega", 71.3, "Spain"},
{"Mark Zuckerberg", 56.0, "USA"},
{"Carlos Slim", 54.5, "Mexico"},
// ...
{"Bernard Arnault", 41.5, "France"},
// ...
{"Liliane Bettencourt", 39.5, "France"},
// ...
{"Wang Jianlin", 31.3, "China"},
{"Li Ka-shing", 31.2, "Hong Kong"}
// ...
};
map<string, pair<const billionaire, size_t>> m;
for (const auto &b : billionaires) {
auto [iterator, success] = m.try_emplace(b.country, b, 1);
if (!success) {
iterator->second.second += 1;
}
}
for (const auto & [key, value] : m) {
const auto &[b, count] = value;
cout << b.country << " : " << count << " billionaires. Richest is "
<< b.name << " with " << b.dollars << " B$\n";
}
}
對於上述代碼
m.try_emplace(b.country, b, 1);
如果不成功插入對將不會構成這增加了性能
'emplace'可能會快幾個週期,因爲它不檢查插入是否發生,但這不是一個真正的好理由。 –
與try_emplace增加的優勢,我總是喜歡這個在emplace –
@HenriMenke:''emplace()''確實檢查重複,*建立''value_type''後*。如果找到重複項,效率會低得多,因爲它需要執行分配(並且在重複的情況下取消分配)。 –