在C++中实现Python中的字典(Dict)

2022-01-23  本文已影响0人  LabVIEW_Python

在Python中,字典是一个很好用且很常用的数据结构,用于存放“键-值”对。而C++语言中,没有提供直接开箱可用的字典数据结构,而是通过C++标准模板库(STL)中的map关系式容器来实现。

map操作的范例程序如下:

#include<map>  //map C++ STL库
#include<string> //C++ string 类库
#include<iostream> //输入输出的iostream类库

using namespace std;

int main()
{
    /* 创建字典key-value pair */
    typedef map<string, string> StudentInfo;
    StudentInfo s_info;
    s_info["Jack"] = "boy";
    s_info.insert(StudentInfo::value_type("Lucy", "girl"));
    s_info.insert(pair<string, string>("Tom", "boy"));
    s_info["Peter"] = "boy";

    /* 获取字典长度 */
    cout << "The Size of s_info: " << s_info.size() << endl;

    /* 查找字典元素 */
    cout << "The Gender of Tom is: " << s_info.find("Tom")->second << endl;

    /* 遍历字典元素 */
    StudentInfo::iterator it; //定义StudentInfo的迭代器
    for (it = s_info.begin(); it!=s_info.end(); it++)
    {
        cout << "key: " << it->first << "; value: " << it->second << endl;
    }

    return 0;
}
运行结果: 范例运行结果

C++ map的基本操作函数:

上一篇 下一篇

猜你喜欢

热点阅读