简体   繁体   English

在不使用高级数据结构的情况下,C++ 中是否有 Python 字典的替代品?

[英]Is there any alternative of Python Dictionary in C++ without using high level Data Structures?

I was actually working a projects of OOP in C++ and stuck in a problem to store keys and their associative values.我实际上是在 C++ 中处理 OOP 的项目,并且遇到了存储键及其关联值的问题。 Both keys and values are string type.键和值都是字符串类型。 Here's the code I'm trying to write but still it's showing error.这是我正在尝试编写的代码,但仍然显示错误。

#include <map>
#include <iostream>
std::map<std::string,std::string> dest;
using namespace std;
dest["M"]  = "001";
dest["D"]  = "010";
dest["MD"] = "011";
dest["A"]  = "100";
dest["AM"] = "101";
dest["AD"] = "110";
dest["AMD"]= "001";

Hi @ALI and welcome to stackoverflow.嗨@ALI,欢迎来到stackoverflow。

C++ is not like Python, you have to show the compiler where to enter the file by implementing an int main() function. C++ 与 Python 不同,您必须通过实现int main() function 向编译器显示输入文件的位置。

I attach this link for you to have a look over我附上此链接供您查看

Solution解决方案

#include <map>
#include <iostream>
std::map<std::string,std::string> dest;
using namespace std;

int main(){
   dest["M"]  = "001";
   dest["D"]  = "010";
   dest["MD"] = "011";
   dest["A"]  = "100";
   dest["AM"] = "101";
   dest["AD"] = "110";
   dest["AMD"]= "001";
}

You might use initialization at global scope:您可以在全局 scope 处使用初始化:

/* const */ std::map<std::string, std::string> dest = {
    {"M", "001"},
    {"D", "010"},
    {"MD", "011"},
    {"A", "100"},
    {"AM", "101"},
    {"AD", "110"},
    {"AMD", "001"}
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM