我正在尝试编写一个非常简单和平庸的程序,其中提示用户输入三种动物的名称和三个维度(身高,体重和年龄(。我想将其存储为{"动物":{身高,体重,年龄}}的哈希图。
当我尝试迭代键值(动物名称(时,它可以工作,但问题是在迭代键时。这个问题让我发疯,因为我不理解迭代器重载等概念,我在另一篇文章中看到过,这是我必须修改代码的一种方式,以便它可以迭代我的哈希映射中每个键的第二个值。
这是我的代码:
#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;
}
对于std::list
没有输出运算符(operator<<
(,就像std::map
没有输出运算符一样。与迭代映射的方式相同,您可以迭代列表:
for (const auto& x: measurements) {
std::cout << x.first << "n";
for (const auto& y : x.second) {
std::cout << y << "n";
}
}
我用const auto&
替换了auto
,因为仅在auto
的情况下,类型被推断为值类型,然后x
是映射中元素的副本。可以使用 const auto&
来避免此复制,则x
是对映射中元素的(const(引用。