簡體   English   中英

如何更新 C++ std::pair 中的值<int, int>

[英]How to update values in C++ std::pair<int, int>

我有這個函數可以返回機器人的位置(這只是矩陣中的一對 [row][col] 索引):

std::pair<int, int> World::getRobotLocation(char robot_name){
    auto const & location = robots.find(robot_name);
    if (location == robots.end()) {
        std::cout << "Robot " << robot_name << " does not exist." << std::endl;
    }
    return location->second;
}

下面,我正在嘗試實現move()函數,該函數接受機器人名稱、位置和移動方向,並相應地更新位置:

std::string move(char robot, char direction) {
    // Get robot and its location
    std::pair<int, int> robot_location = std::pair<int, int> World::getRobotLocation(robot);

    // Get direction to move from user
        // if L, map_[row+1][col]
        // if D, map_[row][col+1]
        // if R, map_[row-1][col]
        // if U, map_[row][col+1]
    // According to user input, update the robot's location

    if (direction == 'L') { 
        robot_location = robot_location[+1][]
    }
    else if (direction == 'D') { 
        robot_location = robot_location[][-1]
    }
    else if (direction == 'R') { 
        robot_location = robot_location[-1][]
    }
    else { 
        robot_location = robot_location[][+1]
    }

}

在我的變量robot_location中,我保存了該特定機器人的位置。 如何訪問此std::pair<int, int>的值以便能夠更新它們?

你的第一個函數有一個錯誤。 它會在找不到機器人時報告,但仍會取消引用結束迭代器,這會導致未定義的行為。 相反,您應該返回一個有條件為空的指針:

// Returns null if the robot is not found:
std::pair<int, int>*
World::getRobotLocation(char robot_name){
    auto const location = robots.find(robot_name);
    if (location == robots.end()) {
        return nullptr;
    }
    return &location->second;
}

在你的另一個函數中,你檢查看看,如果指針不為空,你更新值:

// Returns true if move happens, 
// false otherwise.
bool
move(char robot, char direction) {
    auto const robot_location = World::getRobotLocation(robot);

    if (!robot_location) return false;

    switch (direction) {
        case 'L': {
            ++robot_location->first;
        } break;
        case 'D': {
            --robot_location->second;
        } break;
        case 'R': {
            --robot_location->first;
        } break;
        default: {
            ++robot_location->second;
        } break;
    }
    return true;
}

我想你想要這樣的東西:

    if (direction == 'L') { 
        robot_location.first += 1;
    }
    else if (direction == 'D') {
        robot_location.second -= 1;
    }

    // ...etc (you get the idea)

firstsecondstd::pair中兩個元素的名稱(這也是robots.find(...)的返回值取消引用具有firstsecond的東西的原因 - 這是密鑰的std::pair和地圖的值類型)。

請記住,當前編寫的getRobotLocation將返回std::pair坐標的副本,而不是對地圖內原始坐標的引用。 因此,僅更新該std::pair本身是不夠的。 您需要將值保存回robots地圖,或更改getRobotLocation返回的內容(請參閱@Goswin 和@Ted 的評論)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM