0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

c++のmapメモ:insertの更新方法

Posted at

insertは初めてのkeyの時のみ追加して更新はしない。

更新をしたいときはmp[1] = 10のようにする。

ポインタの時は、*pmp[1] = 10としてしまうとエラーがでる。

(*pmp)[1] = 10とすれば更新もできる。

# include <iostream>
# include <map>
using namespace std;
typedef unsigned int UInt;
 
int main() {
 map<int, int> mp;
 map<int, int>* pmp = &mp;
 // mp.insert(map<int, int>)
 mp[1] = 10;
 mp[2] = 20;
 mp[1] = 100;
 
 
 for(auto itr = mp.begin(); itr != mp.end(); ++itr) {
  std::cout << "key = " << itr->first           // キーを表示
    << ", val = " << itr->second << "\n";    // 値を表示
 }
 
 pmp->insert(map<int,int>::value_type(1,10));
 (*pmp)[1] = 10;
 // pmp->insert(map<int,int>::value_type(2,20));
 // pmp->insert(map<int,int>::value_type(1,100));

 std::cout << endl;
 
 for(auto itr = pmp->begin(); itr != pmp->end(); ++itr) {
  std::cout << "key = " << itr->first           // キーを表示
   << ", val = " << itr->second << "\n";    // 値を表示
 }
 
 return 0;
}
0
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?