Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Structured bindings question regarding unordered_map

Tags:

c++

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?

like image 815
Wolfy Avatar asked May 31 '26 19:05

Wolfy


2 Answers

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.

like image 191
Gaurav Sehgal Avatar answered Jun 02 '26 07:06

Gaurav Sehgal


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.

like image 31
ixSci Avatar answered Jun 02 '26 08:06

ixSci