In need to know how to traverse an stl map. I don't want to use its key. I don't care about the ordering, just a way to access all elements it contains. Is there a way to do this?
相关问题
- Sorting 3 numbers without branching [closed]
- How to compile C++ code in GDB?
- Why does const allow implicit conversion of refere
- thread_local variables initialization
- What uses more memory in c++? An 2 ints or 2 funct
相关文章
- Class layout in C++: Why are members sometimes ord
- How to mock methods return object with deleted cop
- Which is the best way to multiply a large and spar
- C++ default constructor does not initialize pointe
- Selecting only the first few characters in a strin
- What exactly do pointers store? (C++)
- Converting glm::lookat matrix to quaternion and ba
- What is the correct way to declare and use a FILE
As with any STL container, the
begin()
andend()
methods return iterators that you can use to iterate over the map. Dereferencing a map iterator yields astd::pair<const Key, Value>
.Yes, you can traverse a Standard Library
map
. This is the basic method used to traverse amap
, and serves as guidance to traverse any Standard Library collection:C++03/C++11:
If you need to modify the elements:
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"; }
This is how you typically traverse Standard Library containers by hand. The big difference is that for a
map
the type of*it
is apair
rather than the element itselfC++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.First you can make use of the
auto
keyword to get rid of all that nasty verbosity:Second, you can also employ lambdas. In conjunction with
decltype
, this might result in cleaner code (though with tradeoffs):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.You can iterate map by using auto iterator.
Code Snippet:
You can traverse STL map in the same way as any other STL container: using iterators, e.g.
Using
for
withauto
for C++11 and above usageThe newer format of
for
usingauto
was introduced in C++11To give it functionality like some higher level languages like 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