2016-05-06 13 views

Antwort

0

Wenn Sie einen Iterator it auf ein Element eines std::map<X, Y> zeigt dann können Sie eine konstante Referenz auf den Schlüssel erhalten it->first und einen Verweis auf die abgebildeten Typs verwendet it->second verwenden, weil it Punkte auf einen std::map<X, Y>::value_type Wert, der vom Typ

std::pair<std::map<X, Y>::key_type const, 
      std::map<X, Y>::mapped_type> 

Zum Beispiel:

Y * setX(std::map<X, X> & dict, X const & value) { 
    std::map<X, Y>::iterator it = dict.find(value); 
    if (it != dict.end()) 
     return nullptr; 
    assert(it->first == value); 
    return &it->second; 
} 
0
#include <map> 
#include <iostream> 
#include <string> 
using namespace std; 


int main() 
{ 
    // for a simple struct you could use "pair" (especially if you don't want to name it). 
    // anyway: 
    map<int, pair<double, string>> mymap; 
    mymap[0] = pair<double, string>(4.56, "hello"); 
    mymap[1] = pair<double, string>(9.87, "hi"); 
    for(auto & item : mymap) 
    { 
     cout << "Key: " << item.first << ", Value: [" << item.second.first << ", " << item.second.second << "]" << endl; 
    } 
    return 0; 
} 

Ausgabe:

Key: 0, Wert: [4,56, hallo]

Key: 1, Wert: [9,87, hallo]