Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/152.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 为什么我的地图是';第二个值不修改吗?_C++_Dictionary - Fatal编程技术网

C++ 为什么我的地图是';第二个值不修改吗?

C++ 为什么我的地图是';第二个值不修改吗?,c++,dictionary,C++,Dictionary,我正在开发一个聊天室程序,我正在尝试向聊天室地图添加一个用户。我的聊天室地图存储在我的服务器类中,它如下所示:地图聊天室其中int是聊天室中的用户数。在我的Server类中,还有一个当前服务器中所有用户的向量: 矢量当前用户server.getUsers()返回当前用户和服务器。get\u聊天室()返回地图聊天室。我的函数正确地将用户添加到聊天室,但是,它不会增加聊天室中的用户数。我在问题所在的地方写了一条评论 下面是函数 void Controller::add_user_to_chatroo

我正在开发一个聊天室程序,我正在尝试向聊天室地图添加一个用户。我的聊天室地图存储在我的
服务器
类中,它如下所示:
地图聊天室
其中int是聊天室中的用户数。在我的
Server
类中,还有一个当前服务器中所有用户的向量:

矢量当前用户
server.getUsers()
返回
当前用户
服务器。get\u聊天室()
返回地图
聊天室
。我的函数正确地将用户添加到聊天室,但是,它不会增加聊天室中的用户数。我在问题所在的地方写了一条评论

下面是函数

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;
        }
    }
}
这里是服务器::获取聊天室()

map服务器::获取聊天室(){
返回聊天室;
}

获取聊天室
返回地图副本。当您试图更改聊天室中的用户数时,您正在更改副本中的值,而不是
server.chattrooms
中的值

更改
get_chattrooms
以返回引用:

map<Chatroom*, int> &Server::get_chatrooms()
map&Server::get\u聊天室()

认为您需要自动&或者您正在修改地图条目的本地副本,而不是地图条目。现在我考虑一下。。。如果只获取用户的副本而不获取引用,那么为什么它对get_users()有效?对于不同的行为,get_users()和get_chatrooms()之间有什么区别?@rbb091020因为
get_users
返回一个
向量
,所以无论您是使用原始的副本还是引用,您都会得到相同的用户指针
get\u chatrooms
返回一个映射,当您迭代时,会得到相同的
x.first
(因为两个指针的值相同),但
x.second
表示不同的整数。
 map<Chatroom*, int> Server::get_chatrooms(){
    return chatrooms;
 }
map<Chatroom*, int> &Server::get_chatrooms()