James Bradley
James Bradley

Reputation:

Really confused about map::erase()

//test


#include <map>
#include <iostream>


using namespace std;

int main()
{
    map<int, string> Inventory;

    Inventory[1] = "Sword";
    Inventory[2] = "Armor";
    Inventory[3] = "Shield";

    map<int, string>::iterator iter;

    for (iter = Inventory.begin(); iter != Inventory.end(); ++iter)
        cout << (*iter).first << " - " << (*iter).second << "\n";

    iter == Inventory.find(2);

    Inventory.erase(iter);

    cout << "\n" << Inventory.count(2) << "\n";

    iter == Inventory.find(2);
    cout << "\n" << (*iter).first << " - " << (*iter).second.size() << "\n\n";


    if (Inventory.find(2) == Inventory.end())
        cout << "\nNot found.\n";

    for (iter = Inventory.begin(); iter != Inventory.end(); ++iter)
        cout << (*iter).first << " - " << (*iter).second << "\n";

    cout << "\n" << Inventory.size() << "\n";

    system("PAUSE");
    return EXIT_SUCCESS;

}

This is what I get when I run the program:

1 - Sword

2 - Armor

3 - Shield

1

2 - 1968772512

1 - Sword

3 - Shield

2

So I'm a little confused why the key '2' isn't being completely deleted.

Inventory.count(2) is returning 1 which would mean that key '2' is still lingering around in Inventory somewhere?

Apparently, after erasing key '2', find() still returns a iterator to that key value?

How exactly does erase() work?

Upvotes: 0

Views: 80

Answers (1)

marsh
marsh

Reputation: 2730

iter == Inventory.find(2);

is not an assignment, I am guessing you meant to do:

iter = Inventory.find(2);

Upvotes: 4

Related Questions