[英]How do I make a map using a struct in C++?
what I am trying to do is use C++ struct to make a simple map.我想做的是使用 C++ 结构来制作一个简单的 map。
for example,例如,
if I have如果我有
struct Map { char name; int age };
Map MapObj[] = { {'charles', 10}, {'kate', 20}, {'nate', 10} }
how can I access to kate's age using the map?如何使用 map 了解凯特的年龄? I tried MapjObj['kate'] but it does not work.我试过 MapjObj['kate'] 但它不起作用。 How can I access the age using the name?如何使用名称访问年龄?
You can use the <algorithm>
facilities C++ offers, and specifically - std::find
;您可以使用 C++ 提供的<algorithm>
工具,特别是 - std::find
; something like:就像是:
auto pos = std::find(
std::begin(MapOjb),
std::end(MapObj),
[](const Map& m) { return m == "kate"}
);
But note that:但请注意:
name
must be an std::string
or a char *
(in the latter case, you would use strcmp()
, not plain string comparison). name
必须是std::string
或char *
(在后一种情况下,您将使用strcmp()
,而不是纯字符串比较)。Map
and MapObj
are incredibly poor choices for names here... Map
和MapObj
在这里的名字是非常糟糕的选择......Pass it the beginning and the end of the array you created, as well as a lambda function.将您创建的数组的开头和结尾以及 lambda function 传递给它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.