【问题标题】:Cannot iterate Hashmap C++无法迭代 Hashmap C++
【发布时间】: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&lt;float&gt; 没有意义。请发布真实代码。或者至少在问题中包含错误消息,目前尚不清楚您要修复什么问题
  • x.secondlist。你知道如何打印 list 的每个元素吗?是这个问题吗?

标签: c++ hashmap iteration


【解决方案1】:

std::list 没有输出运算符 (operator&lt;&lt;),就像 std::map 没有输出运算符一样。以与迭代地图相同的方式,您可以迭代列表:

for (const auto& x: measurements) {
    std::cout << x.first << "\n";
    for (const auto& y : x.second) {
        std::cout << y << "\n";
    }
}

我将auto 替换为const auto&amp;,因为仅在auto 的情况下,类型被推断为值类型,然后x 是映射中元素的副本。这个副本可以通过使用const auto&amp; 来避免,然后x 是对地图中元素的(常量)引用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-10-31
    • 2010-10-24
    • 1970-01-01
    • 2018-02-13
    • 2015-09-19
    • 2011-03-21
    • 2021-11-25
    • 2010-12-02
    相关资源
    最近更新 更多