如何访问C++映射内部值

发布于 2025-01-29 16:03:54 字数 372 浏览 1 评论 0原文

这是我的地图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

also this is what ProductInfo looks like during debug

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

血之狂魔 2025-02-05 16:03:54

假设您有一个地图:

std::map<KeyT, ValueT> m;

迭代器指向的值定义为:

using value_type = std::pair<KeyT const, ValueT>;

因此,您使用pair :: second用于映射值:

auto it = m.find("some key");
if (it != m.end()) {
  std::cout << "name: " << it->second.name << '\n';
}

Assuming you have a map:

std::map<KeyT, ValueT> m;

The value your iterators are pointing to are defined as:

using value_type = std::pair<KeyT const, ValueT>;

Thus, you use pair::second for the mapped value:

auto it = m.find("some key");
if (it != m.end()) {
  std::cout << "name: " << it->second.name << '\n';
}
陌路黄昏 2025-02-05 16:03:54

要在容器上循环循环,请不要使用迭代器(或索引)(如果不是明确的必要),而是使用基于循环的范围( https://en.cppreference.com/w/cpp/language/range-for )。基于范围的更可读性,并防止偶然的访问。

对于代码可读性,您可以使用结构化绑定( https://en.cppreference.com/cppreference.com/ww /cpp/language/structistion_binding )这样:

#include <iostream>
#include <map> // or unordered_map for faster access
#include <string>

struct ProductInfo
{
    std::size_t id;
};

int main()
{
    // initialize map with 3 entries
    std::map<std::string, ProductInfo> m_products
    {
        {"one",{1}},
        {"two",{2}},
        {"three",{3}}
    };

    // range based for loop with structured bindings
    for (const auto& [key, product_info] : m_products)
    {
        std::cout << "key = " << key << ", value = " << product_info.id << "\n";
    }

    return 0;
}

也不要按照上述建议使用[]索引运算符。但请使用: 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 :

#include <iostream>
#include <map> // or unordered_map for faster access
#include <string>

struct ProductInfo
{
    std::size_t id;
};

int main()
{
    // initialize map with 3 entries
    std::map<std::string, ProductInfo> m_products
    {
        {"one",{1}},
        {"two",{2}},
        {"three",{3}}
    };

    // range based for loop with structured bindings
    for (const auto& [key, product_info] : m_products)
    {
        std::cout << "key = " << key << ", value = " << product_info.id << "\n";
    }

    return 0;
}

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

若能看破又如何 2025-02-05 16:03:54

访问std :: Map使用operator []给我们映射类型,与ProductInfo < /代码>在您的示例中。这意味着您可以使用成员访问操作员访问数据成员name如下所示:

//-----------------------------vvvv---->use member access operator
std::cout << mymap["some key"].name; 

如果您为productInfo提供了Geters,则可以使用该Getter,如下所示

std::cout << mymap["some key"].get_name();

:请注意,如果密钥尚未在地图内部,则使用operator []时,将创建并插入一个新的键值对,因此请不要忘记初始化每个数据成员内部productInfo

Accessing a key of a std::map using the operator[] gives us the mapped type which is the same as ProductInfo in your example. This means that you can access the data member name using the member access operator as shown below:

//-----------------------------vvvv---->use member access operator
std::cout << mymap["some key"].name; 

If you provided getters for ProductInfo then you can use that getter as shown below:

std::cout << mymap["some key"].get_name();

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 inside ProductInfo.

書生途 2025-02-05 16:03:54

您需要访问productInfo对象的属性名称。您需要做的是your_map [“键”] - &gt; get_name()其中get_name()name> name in productInfo

You want to access the property name of the ProductInfo object inside a map. What you need to do is your_map["the key"]->get_name() where get_name() is a getter for name in ProductInfo.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文