vendredi 18 octobre 2019

How do I find value as pair in a map?

I am new to stl maps and what I am trying to do is to find if the paired values are exist in the map. I am going to implement a board game using map and the key is player ID and the value is a pair as the board coordinates. Both ID and coordinates are unique. I have done finding the player ID which is simply finding the map keys. However, I am stuck on finding the coordinates as paired values. When I run my code, it should check if the ID or coordinates are occupied. The ID check is successful but the coordinates check is not working properly. I just figured out the FindMatrix() function has some problems.

bool Board::Insertion(int id, int x, int y) //This function is going to take player ID and (x, y) as input and check if they are occupied, if either is occupied, then the insertion is failure. The FindID() function is working, but the below FindMatrix() function does not check the coordinate as the code still report insertion successful although it is not actually inserted.

How do I fix this?

    bool Board::FindMatrix(int x, int y)
    {
        for (auto it = matrix.find(make_pair(x, y)); it != matrix.cend(); it++)
    {

        if (x == it->second.first && y == it->second.second)
        {
            cout << "Matrix " << it->second.first << " " <<
                 it->second.second << " is found\n\n";
            return true;
        }
        else
        {
            cout << "Matrix " << it->second.first << " " <<
                 it->second.second << " is not found\n\n";
            return false;
        }
    }
}

    int main()
    {
    Board b;

    b.Insertion(7, 0, 0);
    b.Insertion(2, 4, 1);
    b.Insertion(2, 4, 1); //report failure, same ID
    b.Insertion(3, 0, 0); //NOT reporting failure
    b.PrintByID();


    }

Aucun commentaire:

Enregistrer un commentaire