How to get reference to inserted object from std::map::emplace()
?
Official doc for emplace.
I have added auto inserted = m.emplace("d", "ddd");
Can you please demonstrate how to get reference to just inserted "ddd"
?
I receive some ridiculous type struct std::_Rb_tree_iterator
and cannot find any documentation or example how to work with it.
#include <iostream>
#include <utility>
#include <string>
#include <map>
int main()
{
std::map<std::string, std::string> m;
// uses pair's template constructor
auto inserted = m.emplace("d", "ddd");
for (const auto &p : m) {
std::cout << p.first << " => " << p.second << '\n';
}
}
map.emplace
return a pair containing an iterator to object and a boolean (http://www.cplusplus.com/reference/map/map/emplace/)
and the iterator for map is a kind of pointer to a pair of key and value. So, you can do :
auto inserted = m.emplace("d", "ddd");
if (inserted.second == true)
{
auto &ref_to_ddd = inserted.first->second;
}
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