Question

I encountered a problem here. I'm using C++ multiset. This is the test file.

Score: 3-1 
Ben
Steven
Score: 1-0 
Ben
Score: 0-0
Score: 1-1 
Cole
Score: 1-2
Ben

I'm using while loop and ifstream (fin1) to read in from the test file above.

multiset<string, less<string> > myset;

while(!fin1.eof())
{

fin1 >> scoreName;

if(scoreName == "Score:")                                               
{
    //calculates number of matches played
}
else
{
    goalCheck = scoreName.substr(1,1);
    if(goalCheck == "-")
    {
        string lGoal, rGoal;
        lGoal = scoreName.substr(0,1);
        rGoal = scoreName.substr(2,1);

        int leftGoal, rightGoal;
        leftGoal = atoi(lGoal.c_str());
        rightGoal = atoi(rGoal.c_str());

        if(leftGoal > rightGoal)   //if team wins
        {
            //some computations
        }
        else if(leftGoal < rightGoal)   //if team loses
        {
            //computations
        }
        else if(leftGoal == rightGoal)   //if team draws
        {
            //computations
        }
        else
        {
            myset.insert(myset.begin(), scoreName);
        }
    }
}

I'm inserting all names into myset (regardless of wins/loses/draws) in my last else statement. But I only require the names of those matches who won/draw.

Those names whose matches lost will not be included in myset. In the test file above, there's only one match that lost (1-2) and I wanted to remove "Ben". How can I do that?

I tried to use myset.erase(), but I'm not sure how to get it point to Ben and remove it from myset.

Any help is much appreciated. Thanks.

Was it helpful?

Solution

If I understand what you're trying to do, I think it would be easier to remember whether the team had won, drawn or lost when you read the "Score" line and only insert the following lines (ie. "Ben") if the team hasn't lost. Inserting everyone and then erasing ones you didn't want seems overcomplicated to me :)

For reference: If you do need to erase, you would use the find() member to locate an entry matching a given key, and then erase() on the returned iterator to delete it (after checking that find() didn't return an iterator equal to end(), which means the item wasn't found).

Also, you shouldn't pass begin() to insert(). The iterator is a hint as to where the map might insert the item; in practice that's rarely useful. There is an overload of that function which takes only one argument, the item to insert.

OTHER TIPS

Create a Score class. Add it a non-member operator>>() so you can parse it easily. Then it will be easy for you decide whether to insert a Score object into the set or not:

if( scr.gained - scr.lost >= 0 )
    myset.insert(myset.begin(), scr);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top