如何在 C++ 中遍历静态映射
How do I iterate through a static map in C++
我似乎无法遍历静态地图,似乎也找不到对此的问题。也许我做错了,地图是否是静态的并不重要,但就在这里。
我有静态图=static std::map<std::string, Texture>* s_textureMap;
(纹理只是我自定义的class)
我尝试了两种不同的循环:
for (auto it = s_textureMap.begin(); it != s_textureMap.end(); it++)
{
std::cout << it->first // string (key)
}
或
for (auto const& str : m_programMap)
{
std::cout << it->first // string (key)
}
对于第一个循环,我收到错误消息说 "initialize map at the very start of the app" 和 "expression must have class type"
对于第二个循环,我收到错误消息说 "initialize map at the very start of the app" 和 "this ranged based 'for' statement requires a suitable "begin" 函数,并且找到了 none。
我试图查找此错误,但似乎无济于事。
提前致谢!
您拥有的不是静态地图,而是指向地图的静态指针。因此,您需要使用 ->
取消引用运算符而不是 .
.
for (auto it = s_textureMap->begin(); it != s_textureMap->end(); it++)
{
std::cout << it->first; // string (key)
}
或者,您也可以通过使用 *
取消引用 m_programMap
来使用后一个循环。 (假设 m_programMap
也是一个指向地图的指针,从你展示的内容来看还不清楚。)
for (auto const& str : *m_programMap)
{
std::cout << it->first; // string (key)
}
我不知道那是不是你想要做的,但你的静态地图被声明为一个指针,我尝试使用类似静态 std::map<std::string, TextureMap> s_textureMap;
的东西,它工作得很好。
或者你也可以做 s_textureMap->begin()
而不是 s_textureMap.begin()
,再次假设你真的想使用静态指针。
我似乎无法遍历静态地图,似乎也找不到对此的问题。也许我做错了,地图是否是静态的并不重要,但就在这里。
我有静态图=static std::map<std::string, Texture>* s_textureMap;
(纹理只是我自定义的class)
我尝试了两种不同的循环:
for (auto it = s_textureMap.begin(); it != s_textureMap.end(); it++)
{
std::cout << it->first // string (key)
}
或
for (auto const& str : m_programMap)
{
std::cout << it->first // string (key)
}
对于第一个循环,我收到错误消息说 "initialize map at the very start of the app" 和 "expression must have class type"
对于第二个循环,我收到错误消息说 "initialize map at the very start of the app" 和 "this ranged based 'for' statement requires a suitable "begin" 函数,并且找到了 none。
我试图查找此错误,但似乎无济于事。
提前致谢!
您拥有的不是静态地图,而是指向地图的静态指针。因此,您需要使用 ->
取消引用运算符而不是 .
.
for (auto it = s_textureMap->begin(); it != s_textureMap->end(); it++)
{
std::cout << it->first; // string (key)
}
或者,您也可以通过使用 *
取消引用 m_programMap
来使用后一个循环。 (假设 m_programMap
也是一个指向地图的指针,从你展示的内容来看还不清楚。)
for (auto const& str : *m_programMap)
{
std::cout << it->first; // string (key)
}
我不知道那是不是你想要做的,但你的静态地图被声明为一个指针,我尝试使用类似静态 std::map<std::string, TextureMap> s_textureMap;
的东西,它工作得很好。
或者你也可以做 s_textureMap->begin()
而不是 s_textureMap.begin()
,再次假设你真的想使用静态指针。