I am learning new C++17 features and I came across this:
std::vector<int> nums = { 1, 1, 2, 3 };
std::unordered_map<int, size_t> m;
for (int i = 0; i < nums.size(); ++i)
{
const auto& [inserted_entry, inserted_happen] = m.emplace(nums[i], i);
std::cout << inserted_happen << "\n";
}
The result is:
1
0
1
1
What is happening here? I do not understand.
Also what is inserted_entry?
emplace returns a pair of an iterator to inserted element(or already present element) and a bool representing if the insert was successful.
inserted_happen is a bool.
The second insert fails since 1 already exists as key in the map.
emplace returns std::pair<iterator, bool> which then gets "destructured" and 2 bindings get created. inserted_entry is a reference to the iterator part and inserted_happen is a reference to the bool part.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With