Search code examples
c++stlstdmapstd-pair

How to get pair from a map using key in C++


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?


Solution

  • 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:

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

    you need to:

    std::pair<int, int> location = robots.find(robot_name)->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:

    const auto it = robots.find(robot_name);
    if (it != robots.end()) {
        return it->second;
    } else {
        // Not found, do something else
    }