Quantcast
Channel: 連想配列タグが付けられた新着記事 - Qiita
Viewing all articles
Browse latest Browse all 129

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

$
0
0

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

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


Viewing all articles
Browse latest Browse all 129

Trending Articles