想要遍历STL地图。我不想用它的钥匙。我不关心排序,我只想找到一种方法来访问它包含的所有元素。我怎样才能做到这一点?
是的,您可以遍历标准库map
。这是用于遍历map
的基本方法,并作为遍历任何标准库集合的指导:
#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;
}
}
如果您需要修改元素:
iterator
而不是const_iterator
。这就是您通常手动遍历标准库容器的方式。最大的区别是,对于map
,*it
的类型是pair
而不是元素本身
如果您拥有C ++ 11编译器的好处(例如,使用--std=c++11
或MSVC的最新GCC),那么您还有其他选项。
首先,您可以使用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;
}
}
其次,你也可以雇用lambdas。与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还引入了基于范围的qazxsw poi循环的概念,您可能会认为它与其他语言类似。但是,一些编译器还没有完全支持这一点 - 特别是MSVC。
for
与任何STL容器一样,#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;
}
}
和begin()
方法返回可用于迭代地图的迭代器。取消引用地图迭代器会产生end()
。
您可以使用与任何其他STL容器相同的方式遍历std::pair<const Key, Value>
:使用迭代器,例如
STL map
从for (std::map<key, value>::const_iterator
i = myMap.begin(), end = myMap.end(); i != end; ++i)
{
// *i is a key-value pair
}
开始,你可以使用C++17和range-based for loops迭代地图。结果代码,例如用于打印地图的所有元素,简短且易读:
structured bindings
输出:
m [3] = a m [5] = b m [9] = c
std::map<int, std::string> m{ {3, "a"}, {5, "b"}, {9, "c"} };
for (const auto &[k, v] : m)
std::cout << "m[" << k << "] = " << v << std::endl;
使用#include<bits/stdc++.h>
using namespace std;
int main()
{
ios::sync_with_stdio(false);
map<string, int> mp;
mp["a"]=500;
mp["b"]=200;
mp["d"]=300;
mp["c"]=400;
for(auto it=mp.begin(); it != mp.end(); it++)
{
cout<<it->first <<" : "<<it->second<<endl;
}
return 0;
}
和for
进行C ++ 11及以上版本的使用
auto
使用map<int,int> map_variable; //you can use any data type for keys, as well as value
for(auto &x:map_variable)
{
cout<<x.first ;// gives the key
cout<<x.second; //gives the value
}
的更新格式的for
在C ++ 11中引入
为它提供像python这样的更高级语言的功能
哪里已经有这种迭代的实现
附: :map变量使值保持排序,因此在迭代时,您将按排序顺序获取键