繁体   English   中英

将浮点值映射到键是一对

[英]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.

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