Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get reference to inserted object from std::map::emplace()?

Tags:

c++

c++11

stdmap

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';
    }
}
like image 316
Cron Merdek Avatar asked Mar 03 '16 15:03

Cron Merdek


1 Answers

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;
}
like image 173
Garf365 Avatar answered Nov 03 '22 00:11

Garf365