Home > Blockchain >  How to get pair from a map using key in C
How to get pair from a map using key in C

Time:06-06

I have the following map:

std::map<char, std::pair<int, int> > robots;

I am using this function to populate the map given the input meets certain conditions:

bool World::addRobot(int row, int col, char robot_name) {

    // This if block checks if the desired location is a valid 1 and keeps a track of all the robots already in the grid
    if (map_[row][col] == '1' && robots.find(robot_name) == robots.end()){
        map_[row][col] = robot_name;
        robots.insert(make_pair(robot_name, std::make_pair(row, col)));
    }
    else{std::cout << "Invalid input" << std::endl;}

  return true;
}

Each robot name, which is just a single char, is saved with a pair of its location, which are just row/col coordinates. In the following function, I want to be able to retrieve & ethe location pairs given the robot name:

std::pair<int, int> World::getRobot(char robot_name) {

    std::pair<int, int> location = robots.find(robot_name);
    return location;
}

But the name location is redlines with the following error message:

No viable conversion from 'std::map<char, std::pair<int, int>>::iterator' (aka '_Rb_tree_iterator<std::pair<const char, std::pair<int, int>>>') to 'std::pair<int, int>'

Where am I going wrong? How can I return the coordinate pairs from just the robot name?

CodePudding user response:

std::map::find returns a map iterator which is a "logical pointer" to a std::pair of key and value of the element in the map (not only the value).
The second member of this pair is the value that you seek to return from getRobot (which is by itself a pair of ints).

Fixed version:

std::pair<int, int> World::getRobot(char robot_name) 
{
    auto it = robots.find(robot_name);
    if (it == robots.end())
    {
        return std::pair<int, int>(0, 0);   // return some default value
    }
    return it->second;
}

2 additional notes:

  1. I used auto which is very convenient when using iterators (instead of specifying the long iterator type).
  2. I added a check whether the key is in the map. If not - return some default value. You can change the default value, or change the method prototype to return an error status in this case.

CodePudding user response:

An iterator for a map "points to" a std::pair<const KEY, VALUE>.

For your map, the KEY is char and the VALUE is std::pair<int, int>

So in your code, instead of:

    return location;

you need to:

    return location->second;

Also, you need to check and see if the call to find fails to find the key you want. In that case the iterator will be equal to robots.end, and you'll have to deal with that.

  • Related