【发布时间】:2019-04-01 04:04:30
【问题描述】:
我正在开发一个聊天室程序,我正在尝试将用户添加到聊天室地图。我的聊天室地图存储在我的 Server 类中,如下所示:map<Chatroom*,int> chatrooms 其中 int 是聊天室中的用户数。同样在我的Server 类中是当前服务器中所有用户的向量:
vector<User*> current_users。 server.getUsers() 返回 current_users 和 server.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;
}
【问题讨论】:
-
认为您需要 auto& stackoverflow.com/a/29860056/360211 或者您正在修改地图条目的本地副本,而不是地图条目。
标签: c++ dictionary