【问题标题】:Can you create a string based dictionary in C++?你能在 C++ 中创建一个基于字符串的字典吗?
【发布时间】:2021-08-15 13:25:58
【问题描述】:

我正在尝试在 C++ 中创建一个类似 python 的字典,并且多次建议使用,但在我的情况下,我想用单词而不是“1、2、3、4 ...”来标记我的列表,这可能吗?

示例字典: “饼干”:“糖”、“巧克力”、“面粉” “派”:“牛奶”、“苹果”、“面粉”

等等等等

【问题讨论】:

  • 喜欢std::map<std::string>, std::vector<std::string>>?
  • 好吧,我已经尝试过std::map<std::string, std::string>,但问题是,然后在我的“cookie:”列表中,我只能包含一个值(例如:“sugar”),我目前正在尝试制作它可以与std::map<std::string, std::vector<std::string>> 一起使用,因为它可以在一个列表中存储多个值
  • 这能回答你的问题吗? Simple dictionary in C++
  • 我已经给出了一个使用它的例子,但我使用unordered_map 以获得更好的性能,因为索引的顺序并不重要。

标签: c++


【解决方案1】:

使用@Retired Ninja 提出的数据结构,您可以做一些非常漂亮的事情。您可以使用 unordered_map 而不是 map 以获得更好的性能,因为索引的顺序无关紧要:

#include <iostream>
#include <unordered_map>
#include <vector>


using namespace std;

int main()
{
    unordered_map<string, vector<string>> dict = {
        {"Cookies", {"sugar", "chocolate", "flour"}},
        {"Pies", {"milk", "apples", "flour"}},
        {"Drinks", {"Refrigerant", "Beer", "Juice"}},
        //And so on... You can add values later
    };
    
    for(const auto& object : dict){

        cout<<object.first<<": {";

        for(const auto& value : object.second){
            cout<<value<<", ";
        }

        cout<<object.first<<'}';
        cout<<endl;
    }

    return 0;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-09-13
    • 1970-01-01
    • 1970-01-01
    • 2010-11-17
    • 2020-12-03
    • 1970-01-01
    • 2019-11-17
    相关资源
    最近更新 更多