从另一个 cpp 文件更改结构内、映射键内的变量

Changing a variable inside a struct, inside a map-key, from another cpp file

本文关键字:映射 变量 结构 cpp 另一个 文件      更新时间:2023-10-16

我是C++新手,所以我不确定我是否以正确的方式去做,但我的问题是:

如何从另一个.cpp文件访问和更改在结构内定义的变量(位于映射内(?

我的 .h 文件的一部分:

struct Borough {
std::string name = "";
int num_players = 0;
Borough(std::string n) : name(n) {}
friend inline bool operator< (const Borough& lhs, const Borough& rhs){ return (lhs.name < rhs.name); }
friend inline bool operator==(const Borough& lhs, const Borough& rhs){ return (lhs.name == rhs.name); }
};
class Graph {
public:
typedef std::map<Borough, Vertex *> vmap;
vmap walk;
};

和(部分(播放器.cpp文件:

#include <iostream>
#include <stack>
#include "player.h"
void Player::move() {
std::string current_loc = get_location();
std::cout << "nWhere do you want to move to?" << std::endl;
display_branches(current_loc);
std::string selected_location;
std::getline(std::cin, selected_location);
// verification and placement of player:
if (verify_location(current_loc, selected_location)) {
set_location(selected_location);
// HERE IS WHERE I WANT TO MAKE Borough::num_players++;
std::cout << m_graph.walk.find(selected_location)->first.num_players << " <-- That's the number of players.n";
}
}

我知道我可以显示数字,但我想在玩家成功"移动"时通过递增 +1 来更改它。

std::map的key_type总是const的,因为修改键的方式可能会改变它在地图(树(中的正确位置是一个错误。

但唯一重要的部分是影响地图中位置的部分。std::map无法知道这一点,但在您的情况下,自治市镇的比较仅涉及其name,而不涉及num_players

解决此问题的最简单方法是将num_players标记为mutable

mutable int num_players = 0;

然后,即使在const Borough中,您也可以修改此值。 它不会伤害任何东西,只要你的自治市比较器不依赖于num_players.