Vito Corleone
Vito Corleone

Reputation: 37

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;

}

Upvotes: 3

Views: 897

Answers (2)

Denis Ermolin
Denis Ermolin

Reputation: 5546

You are trying to output a std::pair, which is your key (i.e. 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;

Upvotes: 6

R&#233;mi
R&#233;mi

Reputation: 3745

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;

Upvotes: 1

Related Questions