【发布时间】:2019-06-04 18:07:00
【问题描述】:
我正在尝试编写一个非常简单且平庸的程序,其中提示用户输入三种动物的名称和三个维度(身高、体重和年龄)。我想将其存储为 {"animal":{height, weight, age}} 类型的 Hashmap。
当我尝试迭代键值(动物名称)时,它可以工作,但问题在于迭代键时。这个问题让我发疯了,因为我不理解迭代器重载等概念,我在其他帖子中看到这是我必须修改代码的一种方式,以便它可以迭代每个键的第二个值我的哈希图。
这是我的代码:
#include <iostream>
#include <string>
#include <map>
#include <list>
using namespace std;
int main(){
map <string, list<float>> measurements;
for(int i=1; i<=3; i++){
string name;
float height, weight, age;
cout << "Please enter the animals' name: " << i << endl;
cin >> name;
cout << "Enter the height, weight, age" << endl;
cin >> height >> weight >> age;
measurements[name] = {height, weight, age};
}
for (auto x: measurements) {
cout << x.first << endl;
cout << x.second << endl;
}
return 0;
}
【问题讨论】:
-
你永远不会在
measurements中插入任何东西,或者有任何列表可以让迭代器插入其中(假设你修复它以使用正确的类型)。也不涉及哈希表... -
没有声明
grades,这是在修改代码以将其发布到此处时的拼写错误吗?请确保您描述的代码和行为是同步的。我无法编译代码(我对错误有点困惑)wandbox.org/permlink/NYKUxWX02ocEUtxF -
错误是因为
list::iterator<float>没有意义。请发布真实代码。或者至少在问题中包含错误消息,目前尚不清楚您要修复什么问题 -
x.second是list。你知道如何打印list的每个元素吗?是这个问题吗?