Link to home
Start Free TrialLog in
Avatar of shadow66
shadow66

asked on

Deleting an entry from a multimap

Using Borland BCB4.0

I need two things:
1) Reason why the following program fails to find the entries made to the multimap "ITEM#1"
2) A way to delete a single entry (not a whole key) from the multimap "ITEM#2"

#include <condefs.h>
#include <conio>
#include <iostream>
#include <map>
#pragma hdrstop

class A
{
    public:
        A(int v = 0){val = v;}
        int getVal(){return val;}
    private:
        int val;
};

int main()
{
    A a1(1), a2(2), a3(3);
    std::multimap<const char*, A*> myMap;

    myMap.insert(std::make_pair("x", &a1) );
    myMap.insert(std::make_pair("x", &a2) );
    myMap.insert(std::make_pair("x", &a3) );

    typedef std::multimap<const char*, A*>::const_iterator mapIterator;
    std::pair<mapIterator,mapIterator> keyMatches;

    // Search for matches to key "x"; should find a1, a2 and a3
    keyMatches = myMap.equal_range("x");

    if ( keyMatches.first == myMap.end() )
        std::cout << "no matches found" << '\n';  // ITEM#1
    else
        for (mapIterator mi = keyMatches.first; mi != keyMatches.second; ++mi)
            std::cout << ( (mi->second)->getVal() ) << '\n';
            // Expected output:
            // 1
            // 2
            // 3


    // Erase map entry &a2 here (preserving entries &a1 and &a3
    // ?
    // ITEM#2
    // ?


    // Search for matches to key "x"; should find only a1 and a3

    keyMatches = myMap.equal_range("x");

    if ( keyMatches.first == myMap.end() )
        std::cout << "no matches found" << '\n';
    else
        for (mapIterator mi = keyMatches.first; mi != keyMatches.second; ++mi)
            std::cout << ( (mi->second)->getVal() ) << '\n';
            // Expected output:
            // 1
            // 3

    getch();
    return 0;
}
ASKER CERTIFIED SOLUTION
Avatar of jasonclarke
jasonclarke

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of proskig
proskig

You can also use std::string instead of char*
Avatar of shadow66

ASKER

Thanks for the quick answer, Jason. Stroustrop's book made it clear how to erase an entire key, but not how to erase a single entry (comparing pointers was my bonehead).

I decided to go with std::string all around, and it works great.