我在c++中有一个类似的include:
struct my_struct
{
time_t time;
double a, b, c, d;
}
typedef std::map<std::string, std::vector<my_struct> Data;
在我的代码中(为了调试问题(,我想打印特定键的Data中的一些值。我不记得语法了,而且总是出错。
以下是我尝试过但没有成功的语法:
for (const auto& [key, value] : inputData)
{
if (key=="mytest")
{
std::cout << '[' << key << "] = " << value.a << endl;
}
}
我也试过:
for(const auto& elem : inputData)
{
if (elem.first=="mytest")
{
cout<<elem.second.a>>endl;
}
}
感谢您的帮助
正确查看以下行:
typedef std::map<std::string, std::vector<my_struct> Data;
正如您所看到的,std::map
的第二个元素是my_struct
的列表。现在这里:
for (const auto& [key, value] : inputData)
{
if (key == "mytest")
{
std::cout << '[' << key << "] = " << value.a << std::endl;
}
}
value.a
没有意义,因为std::vector<my_struct>::a
不是一个东西。
因此,将value.a
替换为:
value[0].a; // Replace 0 with the index of element you want to access
或者打印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;
}
}
您可以根据自己的选择使用这两个选项中的任何一个。
查看地图元素的类型:
typedef std::map<std::string, std::vector<my_struct> Data; ^^^^^^^^^^^^^^^^^^^^^^
映射包含向量。
for (const auto& [key, value] : inputData)
这里,value
是映射中元素的值。它是一个矢量。
value.a
Vector没有名为a
的成员。您应该会收到解释这一点的错误消息。
有许多方法可以访问向量中的元素。这里有一个例子:
std::cout << value.at(0).a;