如何使用 C++ 中的键从地图中获取对

Onu*_*bek 0 c++ stl stdmap std-pair

我有以下地图:

std::map<char, std::pair<int, int> > robots;
Run Code Online (Sandbox Code Playgroud)

如果输入满足某些条件,我将使用此函数来填充地图:

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;
}
Run Code Online (Sandbox Code Playgroud)

每个机器人名称(只是一个字符)都与其位置(行/列坐标)一起保存。在以下函数中,我希望能够检索给定机器人名称的位置对:

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

    std::pair<int, int> location = robots.find(robot_name);
    return location;
}
Run Code Online (Sandbox Code Playgroud)

但名称location已红线,并显示以下错误消息:

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>'
Run Code Online (Sandbox Code Playgroud)

我哪里出错了?如何仅从机器人名称返回坐标对?

Mar*_*low 5

映射的迭代器“指向” a std::pair<const KEY, VALUE>

对于你的地图,KEYcharVALUEstd::pair<int, int>

所以在你的代码中,而不是:

std::pair<int, int> location = robots.find(robot_name);
Run Code Online (Sandbox Code Playgroud)

你需要:

std::pair<int, int> location = robots.find(robot_name)->second;
Run Code Online (Sandbox Code Playgroud)

另外,您需要检查 find 调用是否未能找到您想要的密钥。在这种情况下,迭代器将等于robots.end,您必须处理该问题:

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