如何访问C++映射内部值
这是我的地图std :: map< std :: String,productInfo> mymap
,这些是productInfo
的值:
bool isActive = false;
char name[80];
我已经能够访问特定的键 - value对(std :: string
- productinfo < /code>)使用
:: iterator
,但我实际上需要的是name
属性productinfo
This is my map std::map<std::string,ProductInfo> mymap
and these are the values inside ProductInfo
:
bool isActive = false;
char name[80];
I am already able to access a specific key - value pair (std::string
- ProductInfo
) using ::iterator
but what I actually need is the name
property inside ProductInfo
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
假设您有一个地图:
迭代器指向的值定义为:
因此,您使用
pair :: second
用于映射值:Assuming you have a map:
The value your iterators are pointing to are defined as:
Thus, you use
pair::second
for the mapped value:要在容器上循环循环,请不要使用迭代器(或索引)(如果不是明确的必要),而是使用基于循环的范围( https://en.cppreference.com/w/cpp/language/range-for )。基于范围的更可读性,并防止偶然的访问。
对于代码可读性,您可以使用结构化绑定( https://en.cppreference.com/cppreference.com/ww /cpp/language/structistion_binding )这样:
也不要按照上述建议使用[]索引运算符。但请使用: https://en.cppreference.com/w/w/cpp/容器/地图/AT 。如果找不到数据,则[]运算符将插入数据,这通常会导致错误。 AT功能仅在地图内真正存在时返回数据
To loop over containers then do not use iterators (or indices) if not explicitly necessary, but use range based for loops (https://en.cppreference.com/w/cpp/language/range-for). Range based are more readable and prevent accidental out of bound access.
For code readability you can use structured bindings (https://en.cppreference.com/w/cpp/language/structured_binding) like this :
Also do not use the [] index operator as advised above. But use at : https://en.cppreference.com/w/cpp/container/map/at. The [] operator will insert data if data is not found and this often leads to bugs. The at function will only return data if it really exists inside the map
访问
std :: Map
使用operator []
给我们映射类型,与ProductInfo <
/代码>在您的示例中。这意味着您可以使用成员访问操作员访问数据成员name
如下所示:如果您为
productInfo
提供了Geters,则可以使用该Getter,如下所示:请注意,如果密钥尚未在地图内部,则使用
operator []
时,将创建并插入一个新的键值对,因此请不要忘记初始化每个数据成员内部productInfo
。Accessing a key of a
std::map
using theoperator[]
gives us the mapped type which is the same asProductInfo
in your example. This means that you can access the data membername
using the member access operator as shown below:If you provided getters for
ProductInfo
then you can use that getter as shown below:Also note that if the key is not already inside the map, a new key-value pair will be created and inserted inside the map when using
operator[]
so don't forget to initialize each of the data members insideProductInfo
.您需要访问
productInfo
对象的属性名称
。您需要做的是your_map [“键”] - &gt; get_name()
其中get_name()
是name> name
inproductInfo
。You want to access the property
name
of theProductInfo
object inside a map. What you need to do isyour_map["the key"]->get_name()
whereget_name()
is a getter forname
inProductInfo
.