【问题标题】:Why is my map's second value not modifying?为什么我的地图的第二个值没有修改?
【发布时间】:2019-04-01 04:04:30
【问题描述】:

我正在开发一个聊天室程序,我正在尝试将用户添加到聊天室地图。我的聊天室地图存储在我的 Server 类中,如下所示:map<Chatroom*,int> chatrooms 其中 int 是聊天室中的用户数。同样在我的Server 类中是当前服务器中所有用户的向量:

vector<User*> current_usersserver.getUsers() 返回 current_usersserver.get_chatrooms() 返回映射 chatrooms。我的函数正确地将用户添加到聊天室,但是,它不会增加聊天室中的用户数量。我在问题所在写了一条评论。

这里是函数。

void Controller::add_user_to_chatroom(){
    string username, chatroom_name;
    User* user;
    bool foundChat = false;
    bool foundUser = false;

    view.username_prompt();
    cin >> username;

    //this loops checks to see if user is on the server 
    for(auto x : server.get_users()){
        if(x->getUsername() == username){
            user = x;
            foundUser = true;
            break;
        }
    }

    if(!foundUser){
        cout << "No user found.\n" << endl;
    }
    else{
        view.chatroom_name_prompt();
        cin >> chatroom_name;

        //adds user to chatroom, but doesn't increment the number
        for(auto x : server.get_chatrooms()){
            if(x.first->get_name() == chatroom_name){
                x.first->add_user(user);

                //line below doesn't work, tried x.second++;
                server.get_chatrooms().at(x.first) += 1;
                foundChat = true;
                break;
            }
        }

        if(!foundChat){
            cout << "Chatroom not found.\n" << endl;
        }
    }
}

我打印聊天室时的输出如下所示: Chatroom Name: Sports, Users: joey1212, , Num Users: 0

但是,它应该如下所示: Chatroom Name: Sports, Users: joey1212, , Num Users: 1 因为聊天室里只有一个用户。

为什么x.second 没有更新?我已将多个用户添加到同一个聊天室,并且 num 个用户从不更新。以防万一,这里是从 add_user_to_chatroom() 调用的其他函数

这里是Server::get_users()

vector<User*> Server::get_users(){
    return users;
}

这里是Server::get_chatrooms()

 map<Chatroom*, int> Server::get_chatrooms(){
    return chatrooms;
 }

【问题讨论】:

标签: c++ dictionary


【解决方案1】:

get_chatrooms 返回地图的副本。当您尝试更改房间中的用户数量时,您更改的是副本中的值,而不是 server.chatrooms 中的值。

更改get_chatrooms 以返回引用:

map<Chatroom*, int> &Server::get_chatrooms()

【讨论】:

  • 现在我想起来了……如果它只获取用户的副本而不是参考,为什么它对 get_users() 有效?对于不同的行为,get_users() 和 get_chatrooms() 有什么区别?
  • @rbb091020 由于get_users 返回vector&lt;User *&gt;,因此使用副本或对原始文件的引用都没有关系——您将获得相同的用户指针。 get_chatrooms 返回一个映射,当您通过迭代得到相同的 x.first(因为两个指针具有相同的值),但 x.second 指的是不同的整数。
猜你喜欢
  • 2022-01-15
  • 1970-01-01
  • 2020-07-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-16
  • 2020-10-30
相关资源
最近更新 更多