[英]map a float value to key which is a pair
我正在嘗試創建一個映射並將浮點值映射到類型為pair的鍵。 我無法使用顯示功能顯示地圖。
#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;
}
您正在嘗試輸出std::pair
,這是您的密鑰(即映射的第一個模板參數),但是沒有為它定義流運算符。 用這個:
std::cout << setw(10) << it->first.first
<< setw(5) << it->first.second
<< setw(5) << it->second
<< std::endl;
您可以嘗試以下方式:
for (it = m.begin(); it != m.end(); ++it)
cout << '(' << setw(10) << it->first.first << ", " << setw(10) << it->first.second << ") -> " << setw(5) << it->second << endl;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.