当地图在向量中时,有谁知道如何访问地图键/值?
struct ControlPointSet
{
std::map<uint32_t,uint32_t> control_points;
}
当矢量看起来像这样:
void someMethod(const std::vector<ControlPointSet>& controlpoint_sets)
{
//run through the map vector
for(auto it = controlpoint_sets.begin(); it != controlpoint_sets.end(); it++)
{
for(int i = 0; i < it->control_points.size(); i ++)
{
std::cout << it->control_points.at(i) << std::endl;
}
}
不知怎的,这不起作用
答案 0 :(得分:2)
您无法按索引访问std::map
个元素。它的at()
方法取而代之的是输入密钥。
您可以使用iterator
:
void someMethod(const std::vector<ControlPointSet>& controlpoint_sets)
{
//run through the elements of the vector
for(auto it = controlpoint_sets.begin(); it != controlpoint_sets.end(); ++it)
{
//run through the elements of a map
for(auto cp = it->control_points.begin(); cp != it->control_points.end(); ++cp)
{
std::cout << cp->first << " " << cp->second << std::endl;
}
}
}
void someMethod(const std::vector<ControlPointSet>& controlpoint_sets)
{
//run through the elements of the vector
for(const auto &cps : controlpoint_sets)
{
//run through the elements of a map
for(const auto &cp : cps.control_points)
{
std::cout << cp.first << " " << cp.second << std::endl;
}
}
}