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
CodePudding user response:
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;
CodePudding user response:
Look at the following line properly:
typedef std::map<std::string, std::vector<my_struct> Data;
As you can see the second element of the std::map
is a list of my_struct
. Now here:
for (const auto& [key, value] : inputData)
{
if (key == "mytest")
{
std::cout << '[' << key << "] = " << value.a << std::endl;
}
}
..value.a
makes no sense because std::vector<my_struct>::a
is not a thing.
So replace value.a
with:
value[0].a; // Replace 0 with the index of element you want to access
Or print every element in value
:
for (const auto& [key, value] : inputData)
{
if (key == "mytest")
{
std::cout << '[' << key << "] = ";
for (auto& i : value)
{
std::cout << i.a << " : ";
}
std::cout << std::endl;
}
}
You can use any one of the 2 options as per your choice.