简体   繁体   中英

map a float value to key which is a pair

I am trying to create a map and map a float value to key which is of type pair. I am not able display the map using the display function.

#include <iostream>
#include <utility>
#include <iomanip>
#include <map>

using namespace std;
typedef pair<int, int> Key; //pair

void display (map <Key,float> &m) // to print maps
{
    cout << "\tTotal size: " << m.size() << endl; 
    map <Key,float>::iterator it;
    for (it = m.begin(); it != m.end(); ++it)
       cout << setw(10) << it->first << setw(5) << it->second << endl;

    cout << endl; 
}

int main() {

map< Key , float> mapa; //create map

Key p1 (1, 45); //key values
Key p2 (2, 20);

mapa[p1]= 25.11; //map float to keys
mapa[p2]= 11.23;

display(mapa); //display map

return 0;

}

You are trying to output a std::pair , which is your key (ie the first template parameter of the map), but no stream operator has been defined for it. Use this:

std::cout << setw(10) << it->first.first
          << setw(5) << it->first.second
          << setw(5) << it->second
          << std::endl;

You can try something like:

for (it = m.begin(); it != m.end(); ++it)
   cout << '(' << setw(10) << it->first.first << ", " << setw(10) << it->first.second << ") -> " << setw(5) << it->second << endl;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM