Encontrar el valor mapeado del mapa


¿Hay alguna forma en C++ de buscar el valor asignado (en lugar de la clave) de un mapa y luego devolver la clave? Por lo general, hago someMap.find(someKey)->second para obtener el valor, pero aquí quiero hacer lo contrario y obtener la clave (los valores y las claves son todos únicos).

Author: CharlesB, 2010-11-24

5 answers

Debido a cómo está diseñado un map, tendrá que hacer el equivalente de una búsqueda en datos desordenados.

for (it = someMap.begin(); it != someMap.end(); ++it )
    if (it->second == someValue)
        return it->first;
 30
Author: Bill Lynch,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-11-24 15:36:34

Lo que estás buscando es un Bimap, y hay una implementación disponible en Boost: http://www.boost.org/doc/libs/1_36_0/libs/bimap/doc/html/index.html

 9
Author: Paul,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-11-24 05:09:40

Podemos crear un mapa inverso que asigna valores a claves.

Como,

map<key, value>::iterator it;
map<value, key> reverseMap;

for(it = originalMap.begin(); it != originalMap.end(); it++)
     reverseMap[it->second] = it->first;

Esto también es básicamente como una búsqueda lineal, pero será útil si tiene un número de consultas.

 3
Author: Karan Saxena,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-11-23 19:43:25
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 );
 1
Author: 이원용,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-01-06 07:47:02

Usando lambdas (C++11 y posterior)

//A MAP OBEJCT
std::map<int, int> mapObject;

//INSERT VALUES
mapObject.insert(make_pair(1, 10));
mapObject.insert(make_pair(2, 20));
mapObject.insert(make_pair(3, 30));
mapObject.insert(make_pair(4, 40));

//FIND KEY FOR BELOW VALUE
int val = 20;

auto result = std::find_if(
          mapObject.begin(),
          mapObject.end(),
          [val](const auto& mo) {return mo.second == val; });

//RETURN VARIABLE
int foundkey = result->first;
 1
Author: Naidu,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-09-21 16:44:07