【问题标题】:Python-style dictionary in C++?C ++中的Python风格字典?
【发布时间】:2016-03-27 01:17:59
【问题描述】:

这里是 C++ 初学者。想知道是否有类似于 Python 中的字典的函数。我希望创建一个具有分配值的键列表,这些键可以通过如下数字指针轻松引用:myDict ['插入键位置']。哦,插入的数据将是字符串。提前致谢。

我想用他们手中的硬币(恶搞)数量制作一个名称字典作为键。这将全部用 cin 输入。

【问题讨论】:

  • “哦,插入的数据将是字符串。” 不与 “名称字典作为带有硬币数量的键” : 映射到的数据是strings 还是数字?

标签: python c++ arrays list dictionary


【解决方案1】:

这通常是这样的

std::map<std::string, std::string>

std::unordered_map<std::string, std::string>

但一定要仔细研究界面。例如,元素访问和检查键是否存在的语法可能不是您所期望的,并且看似熟悉的语法可能会做一些意想不到的事情。

【讨论】:

  • 感谢您的回复。我已经尝试过了,但根据我目前的知识,如果不专门输入整个字符串,我很难引用密钥。
  • @Jonathan358:有点难以理解你的意思,但是说你有一个std::string,你已经读过,你可以在地图中创建一个元素的引用(它使用如果尚未插入以下代码,则将插入值为 0)std::map&lt;std::string, int&gt; my_map; while (getline(std::cin, my_string) { int&amp; number_of_coins = my_map[my_string]; number_of_coins += 3; }。正如 Kerrek 所说,研究界面 (here)。
  • std::unordered_map 更类似于 python dict 而不是 std::map,因为 std::unordered_mapdict 是哈希表,而 std::map 是树。
【解决方案2】:

std::mapstd::unordered_map 在很多情况下表现非常相似。但是,它们是不同的数据结构,std::map 使用树实现,std::unordered_map 使用哈希表。由于pythondict是作为哈希表实现的,所以std::unordered_map比较相似;它具有相同的渐近性质。

使用std::unordered_map的非常基本的例子:

#include <iostream>
#include <string>
#include <unordered_map>

int main()
{
  // declare and initialize the "dictionary"
  std::unordered_map<std::string, std::string> my_dict = {{"cat", "dog"}, {"apple", "book"}};

  // insert values
  my_dict.insert(std::make_pair("horse", "tree"));
  my_dict["pig"] = "sky";

  for (auto it=my_dict.begin(); it != my_dict.end(); it++)
  {
    std::cout << "key : " << it->first << " value " << it->second << std::endl;
  }

  // .count() to check if elements exists in unordered_map
  std::cout << my_dict.count("cat") << std::endl;
  std::cout << my_dict.count("wolf") << std::endl;

return 0;
}

【讨论】:

    猜你喜欢
    • 2016-08-29
    • 1970-01-01
    • 2023-03-18
    • 2011-05-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-20
    • 2020-08-28
    相关资源
    最近更新 更多