Can I use a const reference as a key when emplacing into an unordered map in C++? (It compiles and runs as expected but I want to know what is happening under the hood)
Will a copy of the const reference be created by emplace or I need to make sure that the memory referred to is valid till the map exists?
Where can I read more about this?
void func(
const std::vector<std::string>& itemList) {
int i = 0;
std::unordered_map<std::string, int>itemMap;
for (const auto& item : itemList){
itemMap.emplace(item, i);
}
}
Actually,
for (const auto& item : itemList){
has the same effect of following
for (const std::string& item : itemList){
And emplace
just use the const std::string&
to create another string at the place.
The reason why we prefer emplace
than insert
is that the first one will only create the object one time while that last one will create the pair then move it to the place.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.