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
CodePudding user response:
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';
}
CodePudding user response:
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
CodePudding user response:
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
.
CodePudding user response:
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
.