我正在尝试创建一个映射并将浮点值映射到类型为对的键。我无法使用显示功能显示 map 。
#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;
关于c++ - 将浮点值映射到一对键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13499844/