'I need to print element of a struct that is itself in a map in c++
I have in c++ an include like that:
struct my_struct
{
time_t time;
double a, b, c, d;
}
typedef std::map<std::string, std::vector<my_struct> Data;
In my code (for debugging issue) I want to print some of the values in Data for specific key. I don't remember the syntax and keep having errors.
Here the kind of syntax I tried without success:
for (const auto& [key, value] : inputData)
{
if (key=="mytest")
{
std::cout << '[' << key << "] = " << value.a << endl;
}
}
I also tried:
for(const auto& elem : inputData)
{
if (elem.first=="mytest")
{
cout<<elem.second.a>>endl;
}
}
Thanks for your help
Solution 1:[1]
Look at the type of the element of the map:
typedef std::map<std::string, std::vector<my_struct> Data; ^^^^^^^^^^^^^^^^^^^^^^
The map contains vectors.
for (const auto& [key, value] : inputData)
Here, value is a value of an element in the map. It is a vector.
value.a
Vector doesn't have a member named a. You should be getting error messages that explain this.
There are many ways of accessing elements within vectors. Here is an example:
std::cout << value.at(0).a;
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | eerorika |
