4

次のコードを検討してください。

std::map <string,string> myMap;
myMap.insert(std::make_pair("first_key" , "no_value" ));
myMap.insert(std::make_pair("first_key" , "first_value" ));
myMap.insert(std::make_pair("second_key" , "second_value" ));

typedef map<string, string>::const_iterator MapIterator;
for (MapIterator iter = myMap.begin(); iter != myMap.end(); iter++)
{
    cout << "Key: " << iter->first << endl << "Values:" << iter->second << endl;
}

出力は次のとおりです。

Key: first_key
Values:no_value
Key: second_key
Values:second_value

つまり、2番目の割り当ては次のとおりです。

myMap.insert(std::make_pair("first_key" , "first_value" ));

行われなかった。

キーがまだリストされていない場合、およびリストされている場合にのみ、ペアを作成するにはどうすればよいですか?その値を変更しますか?

std :: mapの一般的な方法はありますか?

4

4 に答える 4

5

を使用するか、キーが見つかった場合は値をoperator []使用して変更します。findそのようなキーがない場合はマップにペアを挿入し、キーが存在する場合は値を更新します。

myMap["first_key"] = "first_value";

またはこれ:

auto pos = myMap.find("first_key");
if (pos != myMap.end())
{
   pos->second = "first_value";
}
else
{
   // insert here.
}
于 2012-12-25T11:26:46.367 に答える
4

挿入する前に条件を追加します

if (myMap.find("first_key") == myMap.end()) {
  myMap.insert(std::make_pair("first_key" , "first_value" ));
}
else {
  myMap["first_key"] = "first_value";
}
于 2012-12-25T11:26:37.533 に答える
4

値が存在するときにマップを再度検索することを避ける方が効率的です。

const iterator i = myMap.find("first_key");
if (i == myMap.end()) {
    myMap.insert(std::make_pair("first_key" , "first_value"));
} else {
    i->second = "first_value";
}
于 2015-10-23T21:23:51.640 に答える
0
    #include <map>
//use of make_pair using map container

std::map< std::string, std::map<std::string, float> > student;
        std::map<std::string, float> data;
           data.insert(make_pair("rollno", 11));
        data.insert(make_pair("Physics", 55));
        data.insert(make_pair("Chemistry", 80));
        data.insert(make_pair("Math", 65));
        student.insert(make_pair("Milind Morey", data));
       
        data.insert(make_pair("rollno", 12));
        data.insert(make_pair("Physics", 40));
        data.insert(make_pair("Chemistry", 90));
        data.insert(make_pair("Math", 77));
        student.insert(make_pair("pankaj B", data));
       
        data.insert(make_pair("rollno", 12));
        data.insert(make_pair("Physics", 84));
        data.insert(make_pair("Chemistry", 59));
        data.insert(make_pair("Math", 76));
        student.insert(make_pair("Sachin D", data));
       
        for (auto s : student)
        {
            std::map<std::string, float> rmrk = s.second;
            cout <<endl<< s.first<<"   ";
            for (auto stddetails : s.second)
            {
                cout <<"   "<< stddetails.first << "   " << stddetails.second;
            }
        }
于 2021-09-07T07:55:15.920 に答える