揮発性のメモ2

組込みLinux開発を通じて得た知識と通じずに得た知識をメモ書きしておく

multimapで特定のキーのイテレータを取得する

http://www.geocities.jp/ky_webid/cpp/library/020.html
equal_range()を使って、ソート済み配列の先頭と末尾のイテレータを貰う。 書くことが多くて面倒くさい。

#include <iostream>
#include <map>
#include <string>
using namespace std;

int main(){
    typedef multimap<string,int> M;
    typedef M::iterator MIT;
    
    M list;
    list.insert( M::value_type( "hoge", 1 ) );
    list.insert( M::value_type( "piyo", 2 ) );
    list.insert( M::value_type( "fuga", 3 ) );
    list.insert( M::value_type( "hoge", 4 ) );
    list.insert( M::value_type( "piyo", 5 ) );
    list.insert( M::value_type( "hoge", 6 ) );
    
    cout << "■全部表示" << endl;
    for( MIT it=list.begin(); it!=list.end(); ++it ){
        cout << it->first << ':' << it->second << endl;
    }
    
    cout << "■hogeだけ表示" << endl;
    pair<MIT, MIT> range = list.equal_range("hoge"); // ★
    for( MIT it=range.first; it!=range.second; ++it ){
        cout << it->first << ':' << it->second << endl;
    }
    
    cout << "■range.secondを表示" << endl;
    cout << range.second->first << ':' << range.second->second << endl;
        
    return 0;
}
$ ./a.out
■全部表示
fuga:3
hoge:1
hoge:4
hoge:6
piyo:2
piyo:5
■hogeだけ表示
hoge:1
hoge:4
hoge:6
■range.secondを表示
piyo:2

equal_range()で返ってくるのは 最初に見つけた要素 と 最後に見つけた次の要素 なので、
http://www.cppll.jp/cppreference/cppmultimap_details.html
↑ここの説明は間違い