C++ 如何遍历/迭代 STL 映射?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4207346/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I traverse/iterate an STL map?
提问by atoMerz
I want to traverse an STL map. I don't want to use its key. I don't care about the ordering, I just look for a way to access all elements it contains. How can I do this?
我想遍历 STL 映射。我不想使用它的钥匙。我不在乎顺序,我只是在寻找一种方法来访问它包含的所有元素。我怎样才能做到这一点?
回答by John Dibling
Yes, you can traverse a Standard Library map
. This is the basic method used to traverse a map
, and serves as guidance to traverse any Standard Library collection:
是的,您可以遍历标准库map
。这是用于遍历 a 的基本方法map
,并作为遍历任何标准库集合的指南:
C++03/C++11:
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;
}
}
If you need to modify the elements:
如果需要修改元素:
- Use
iterator
rather thanconst_iterator
. Instead of copying the values out of the iterator, get a reference and modify the values through that.
for( MyMap::iterator it = my_map.begin(); it != my_map.end(); ++it ) { int key = it->first; string& value = it->second; if( value == "foo" ) value = "bar"; }
- 使用
iterator
而不是const_iterator
. 不是从迭代器中复制值,而是获取引用并通过它修改值。
for( MyMap::iterator it = my_map.begin(); it != my_map.end(); ++it ) { int key = it->first; 字符串&值=它->秒;if( value == "foo" ) value = "bar"; }
This is how you typically traverse Standard Library containers by hand. The big difference is that for a map
the type of *it
is a pair
rather than the element itself
这就是您通常手动遍历标准库容器的方式。最大的区别在于,对于 amap
的类型*it
是 apair
而不是元素本身
C++11
C++11
If you have the benefit of a C++11 compiler (for example, latest GCC with --std=c++11
or MSVC), then you have other options as well.
如果您受益于 C++11 编译器(例如,最新的 GCC--std=c++11
或 MSVC),那么您还有其他选择。
First you can make use of the auto
keyword to get rid of all that nasty verbosity:
首先,您可以使用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;
}
}
Second, you can also employ lambdas. In conjunction with decltype
, this might result in cleaner code (though with tradeoffs):
其次,您还可以使用 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 also instroduces the concept of a range-bases for
loop, which you may recognize as similar to other languages. However, some compilers do not fully support this yet -- notably, MSVC.
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;
}
}
回答by fredoverflow
As with any STL container, the begin()
and end()
methods return iterators that you can use to iterate over the map. Dereferencing a map iterator yields a std::pair<const Key, Value>
.
与任何 STL 容器一样,begin()
和end()
方法返回可用于迭代映射的迭代器。取消引用映射迭代器会产生一个std::pair<const Key, Value>
.
回答by vitaut
回答by honk
C++17
C++17
Since C++17you can use range-based for loopstogether with structured bindingsfor iterating over a map. The resulting code, e.g. for printing all elements of a map, is short and well readable:
从C++17 开始,您可以使用基于范围的 for 循环和结构化绑定来迭代映射。生成的代码(例如用于打印地图的所有元素)简短且易读:
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;
Output:
输出:
m[3] = a
m[5] = b
m[9] = c
m[3] = a
m[5] = b
m[9] = c
回答by rashedcs
You can iterate map by using auto iterator.
您可以使用自动迭代器迭代地图。
Code Snippet:
代码片段:
#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;
}
回答by Harsh Sharma
Using for
with auto
for C++11 and above usage
使用for
with auto
for C++11 及以上用法
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
}
The newer format of for
using auto
was introduced in C++11
在 C++11 中引入了新的for
using格式auto
To give it functionality like some higher level languages like python
赋予它像 Python 等高级语言一样的功能
Where there was already an implementation of such type of iteration
已经实现了这种类型的迭代的地方
P.S. : map variable keeps values sorted, so when iterating you will get keys in sorted order
PS:映射变量保持值排序,因此在迭代时,您将按排序顺序获得键