C++ STL 中使用 std::map 存储 string 键和结构体值并查找示例
"C++ STL 中使用 std::map 存储 string 键和结构体值并查找示例" \n本文介绍如何在 C++ STL 中使用 std::map 来存储 string 作为键,结构体作为值,并使用 find 方法查找指定键的值。示例代码展示了如何添加数据、查找数据以及如何处理找不到数据的情况。\n\ncpp\n#include <iostream>\n#include <map>\n#include <string>\n\nstruct Person {\n std::string name;\n int age;\n};\n\nint main() {\n std::map<std::string, Person> people;\n\n // 添加一些数据到map中\n people["John"] = {\"John Doe\", 25};\n people["Jane"] = {\"Jane Smith\", 30};\n people["Mike"] = {\"Mike Johnson\", 35};\n\n // 查找指定键的值\n std::string key = \"Jane\";\n auto it = people.find(key);\n if (it != people.end()) {\n std::cout << \"Key: \" << it->first << \", Value: \" << it->second.name << \", \" << it->second.age << std::endl;\n } else {\n std::cout << \"Key not found!\" << std::endl;\n }\n\n return 0;\n}\n\n\n在上面的示例中,我们首先定义了一个名为Person的结构体,该结构体包含一个名字和年龄字段。然后,我们创建了一个std::map对象,其中键的类型为std::string,值的类型为Person结构体。接下来,我们向people map中添加了一些数据。\n\n在查找数据时,我们使用find方法来查找指定键的值。如果找到了指定的键,则find方法返回一个指向该键值对的迭代器,我们可以通过它来访问键和值。如果找不到指定的键,则find方法返回end迭代器。\n\n在上面的示例中,我们查找了键为"Jane"的值,并输出了找到的结果。如果找到了指定的键,则输出对应的姓名和年龄;如果找不到指定的键,则输出"Key not found!"。\n\n请注意,当使用find方法时,如果指定的键不存在,它将返回end迭代器,因此在使用迭代器之前,我们需要检查是否找到了指定的键。
原文地址: https://www.cveoy.top/t/topic/p8hq 著作权归作者所有。请勿转载和采集!