61

C++ でマップの (キーではなく) マップされた値を検索し、キーを返す方法はありますか? 通常someMap.find(someKey)->secondは値を取得するために行いますが、ここでは逆にキーを取得します (値とキーはすべて一意です)。

4

6 に答える 6

67

がどのようにmap設計されているかにより、順序付けられていないデータに対する検索と同等の操作を行う必要があります。

for (auto it = someMap.begin(); it != someMap.end(); ++it)
    if (it->second == someValue)
        return it->first;
于 2010-11-24T05:08:35.237 に答える
16

大きなマップでこの種の検索を頻繁に行う場合は、キーと値の両方にインデックスを付ける Bimap を調べると面白いかもしれません。Boost で利用可能な Bimap の実装があります: https://www.boost.org/doc/libs/1_77_0/libs/bimap/doc/html/index.html

于 2010-11-24T05:09:40.213 に答える
1
struct test_type
{
    CString str;
    int n;
};


bool Pred( std::pair< int, test_type > tt )
{
    if( tt.second.n == 10 )
        return true;

    return false;
}


std::map< int, test_type > temp_map;

for( int i = 0; i < 25; i++ )

{
    test_type tt;
    tt.str.Format( _T( "no : %d" ), i );
    tt.n = i;

    temp_map[ i ] = tt;
}

auto iter = std::find_if( temp_map.begin(), temp_map.end(), Pred );
于 2017-01-06T07:47:02.530 に答える