在while循环中向std :: map添加条目会覆盖最后输入的对

时间:2016-02-12 19:19:26

标签: c++ stdmap

问题: 我在while循环中向一个地图添加条目,每次它从同一个点开始,i。即之前输入的条目被驳回/覆盖。

代码:

#include <iostream>
#include <map>

int main(){
    char* key=new char;
    char *name, *address;
    name=new char[80];
    address=new char[80];
    std::map<char*, char*> addressBook;
    while(true){
        std::cout<<"Please select action: \n";
        std::cout<<"e - exit\n";
        std::cout<<"a - add new address\n";
        std::cout<<"p - print address book\n";
        std::cin>>key;
        switch(key[0]){
            case 'a':
                std::cin>>name>>address;
                std::cin.clear();
                std::cin.ignore(500,'\n');
                addressBook[name]=address;
                std::cout<<addressBook.size()<<"\n";
                break;
            case 'p':
                for(std::map<char*,char*>::iterator it = addressBook.begin();it!=addressBook.end(); ++it)
                    std::cout<<it->first<<" "<<it->second<<"\n";
                break;
            default:
                return 0;
        }
    }
}

设置: Code ::具有MinGW / gcc 4.7.1的块

2 个答案:

答案 0 :(得分:3)

You're only storing the char * in the map (the pointer), not the value of the pointer. The same pointer keeps getting stored over and over again, and the user input is just changing what is pointed to.

You really want to be having a std::map<std::string, std::string>, instead, and to read into std::strings, not char *s. A rule of thumb is, in modern C++, you should almost never have to use new.

答案 1 :(得分:0)

Use the insert method found Here. As stated the way you are doing it just overwrites the last key.