【问题标题】:Changing a variable inside a struct, inside a map-key, from another cpp file从另一个 cpp 文件更改结构内、映射键内的变量
【发布时间】:2018-10-13 02:50:15
【问题描述】:

我是 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;
};

和(部分) player.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 来改变它。

【问题讨论】:

    标签: c++ dictionary struct


    【解决方案1】:

    std::map 的 key_type 始终为 const,因为修改密钥以使其可能更改其在地图(树)中的正确位置是错误的。

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

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

    mutable int num_players = 0;
    

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

    【讨论】:

      猜你喜欢
      • 2012-02-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多