【问题标题】:How to insert 3 elements or another odd number of elements in an unordered_map?如何在 unordered_map 中插入 3 个元素或其他奇数个元素?
【发布时间】:2023-03-25 22:24:02
【问题描述】:

我正在开发某种交通应用程序,我有车站,我将它们之间的连接放在 unordered_map 中。一个连接是:department_station_id,arrival_station_id,travel_time。

如您所见,共有三个元素。 这是我已经尝试过的。

uint64_t fr=strtoul(from.c_str(),NULL,10);
uint64_t t=strtoul(to.c_str(),NULL,10);
uint64_t tf_time=strtoul(tfr.c_str(),NULL,10);
connections_hashmap.insert({{fr,t},tf_time});

我得到了这个:

 error: no matching function for call to ‘std::unordered_map<long unsigned int, std::unordered_map<long unsigned int, long unsigned int> >::insert(<brace-enclosed initializer list>)’                                                                     connections_hashmap.insert({{fr,t},tf_time});    

我也尝试形成一个 {tf_time,NULL} 对,但我没有工作。

【问题讨论】:

  • 地图与字典几乎相同。在字典中,你给它一个单词,它给你一个定义。同样,对于一张地图,你给它一个key,它给你一个value。因此,如果您要在这里使用地图,您必须确定合适的键是什么:您希望能够查找什么。您必须为该值提供单一类型,通常是 struct(或 class),其中包含属于该值的各个部分。
  • 请提供minimal reproducible example;至少,connections_hashmap 的定义。

标签: c++ c++11 unordered-map


【解决方案1】:

您应该将连接定义为结构,然后将其插入到某个有意义的 ID 下:

struct connection {
  string departure_station_id;
  string arrival_station_id;
  string travel_time;
};

auto connections_hashmap = new unordered_map<string, connection>();
connections_hashmap.insert("connectionID", {"Powell", "Embarcadero", "3"});

这将让您稍后通过 connectionID 检索结构。

【讨论】:

  • 这是一个有趣的想法。谢谢。我期待会有某种标准的方式来做到这一点。
  • 这是相对标准的,因为您会在许多/大多数包含相同问题的代码库中看到它。我不知道有一个现成的解决方案可以让您存储多个键:值对。这是因为根据定义,unordered_map/hashtables/dictionaries 在内部将 Value 存储在由 Key 的函数确定的某个索引处。我希望任何具有第三个键的解决方案都非常适合。
猜你喜欢
  • 2020-07-09
  • 1970-01-01
  • 2015-12-20
  • 2022-12-22
  • 2021-06-27
  • 1970-01-01
  • 1970-01-01
  • 2017-04-30
  • 2012-06-20
相关资源
最近更新 更多