haosmark
haosmark

Reputation: 1127

C++ How do I get a reference to a nested map, to remove an element?

How do I get a reference to the second map here? I want to be able to delete elements by using items.erase(). In the example below, the number of elements in the main map doesn't change, it only changes the copy. C++ 98 only please.

#include <iostream>
#include <map>
#include <string>

using namespace std;

int main()
{
    map<int, map<int, string> > acks;
    acks[10].insert(make_pair(1, "a"));
    acks[10].insert(make_pair(2, "b"));
    acks[10].insert(make_pair(3, "c"));

    acks[20].insert(make_pair(11, "b"));
    acks[20].insert(make_pair(12, "c"));
    
    map<int, map<int, string> >::const_iterator it = acks.find(10);
    if (it != acks.end())
    {
        map<int, string> items = it->second;
        map<int, string>::const_iterator it2 = items.find(3);
        cout << "size before: " << acks[10].size() << endl;
        items.erase(it2);
        cout << "size after: " << acks[10].size() << endl;
    }
}

Upvotes: 0

Views: 283

Answers (1)

john
john

Reputation: 88017

The copy happens here

 map<int, string> items = it->second;

so just change that to a reference

 map<int, string>& items = it->second;

I think you will also need to change

map<int, map<int, string> >::const_iterator it = acks.find(10);

to

map<int, map<int, string> >::iterator it = acks.find(10);

Upvotes: 1

Related Questions