4
5

More than 5 years have passed since last update.

C++のmap, unordered_mapの使い方: 連想配列が扱える

Last updated at Posted at 2019-08-15

C++ での連想配列の使い方

C++ で連想配列を使うために mapコンテナを使います
使い方は簡単で下記ように宣言するだけで, 連想配列が扱えるようになります

map<string, int> mp;

では下記の2個のプログラムを参考に説明していきます

通常の連想配列同様 mp[key] に値の入力を行い, 出力することができます.
また, mp["fish"] のように初期化されていないものは 0 が出力されます.

exsample.cpp
#include<bits/stdc++.h>
using namespace std;

int main(){
    map<string, int> mp;
    mp["dog"] = 3;
    mp["cat"] = 1;
    mp["python"] = 4;

    cout << mp["dog"] << endl; //3
    cout << mp["cat"] << endl; // 1
    cout << mp["python"] << endl; // 4
    cout << mp["fish"] << endl; //0
}

ループ使用方法及び, キー, 値の取得方法は下記のようにできます.

exsample2.cpp
#include<bits/stdc++.h>
using namespace std;

int main(){
    map<string, int> mp;
    mp["dog"] = 3;
    mp["cat"] = 1;
    mp["python"] = 4;

    for(auto itr=mp.begin(); itr!=mp.end(); itr++) {
        cout << "key = " << itr->first;      // キーを表示      
        cout << ", val = " << itr->second << endl;    // 値を表示
    }
}

exsample2.cpp の実行結果が下記のoutput.txtです.

output.txt
key = cat, val = 1
key = dog, val = 3
key = python, val = 4

おまけ

競技プログラマーの人は下記の問題で連想配列を使ってみてね!
ABC008-b 投票

unordered_map が高速だと聞いたので速度比較してみた

"map.cpp" と "unordered_map.cpp"の実行時間を time で測ってみた!

g++ -O0 map.cpp
time ./a.out 
g++ -O0 unordered_map.cpp
time ./a.out 
map.cpp
#include<bits/stdc++.h>
using namespace std;

int main(){
    map<string, int> mp;

    for(int i=0; i<1e7; i++){
        string s = to_string(i);
        mp[s]= i;
    }

    for(auto itr=mp.begin(); itr!=mp.end(); itr++) {
        string a = itr->first;      // キーを表示
        int b = itr->second;
    }
}

unordered_map.cpp
#include<bits/stdc++.h>
using namespace std;

int main(){
    unordered_map<string, int> mp2;
    for(int i=0; i<1e7; i++){
        string s = to_string(i);
        mp2[s]= i;
    }

    for(auto itr=mp2.begin(); itr!=mp2.end(); itr++) {
        string a = itr->first;
        int b = itr->second;
    }
}

実行結果

実行結果は下記のようになった.
map.cpp: 19.24s
unordered_map.cpp: 15.49s

大きな差ではないが, 有意な差は見られた

4
5
3

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
4
5