是的,您可以遍历标准库map
。这是用于遍历的基本方法map
,并作为遍历任何标准库集合的指导:
C++03/C++11:
#include <cstdlib>
#include <map>
#include <string>
using namespace std;
int main()
{
typedef map<int,string> MyMap;
MyMap my_map;
// ... magic
for( MyMap::const_iterator it = my_map.begin(); it != my_map.end(); ++it )
{
int key = it->first;
string value = it->second;
}
}
如果需要修改元素:
这就是您通常手动遍历标准库容器的方式。最大的区别是对于map
的类型*it
is a pair
而不是元素本身
C++11
如果您受益于 C++11 编译器(例如,最新的 GCC--std=c++11
或 MSVC),那么您还有其他选择。
首先,您可以使用auto
关键字来摆脱所有令人讨厌的冗长内容:
#include <cstdlib>
#include <map>
#include <string>
using namespace std;
int main()
{
map<int,string> my_map;
// ... magic
for( auto it = my_map.begin(); it != my_map.end(); ++it )
{
int key = it->first;
string& value = it->second;
}
}
其次,您还可以使用 lambda。和这个结合decltype
,这可能会导致更清晰的代码(尽管需要权衡):
#include <cstdlib>
#include <map>
#include <string>
#include <algorithm>
using namespace std;
int main()
{
map<int,string> my_map;
// ... magic
for_each(my_map.begin(), my_map.end(), [](decltype(*my_map.begin()) val)
{
string& value = val.second;
int key = val.first;
});
}
C++11 还引入了范围基数的概念for
循环,您可能会认为它与其他语言类似。然而,一些编译器尚未完全支持这一点——尤其是 MSVC。
#include <cstdlib>
#include <map>
#include <string>
#include <algorithm>
using namespace std;
int main()
{
map<int,string> my_map;
// ... magic
for(auto val : my_map )
{
string& value = val.second;
int key = val.first;
}
}