C++ Loop through Map
You can achieve this like following :
map<string, int>::iterator it;
for (it = symbolTable.begin(); it != symbolTable.end(); it++)
{
std::cout << it->first // string (key)
<< ':'
<< it->second // string's value
<< std::endl;
}
With C++11 ( and onwards ),
for (auto const& x : symbolTable)
{
std::cout << x.first // string (key)
<< ':'
<< x.second // string's value
<< std::endl;
}
With C++17 ( and onwards ),
for (auto const& [key, val] : symbolTable)
{
std::cout << key // string (key)
<< ':'
<< val // string's value
<< std::endl;
}
Iterating through map keys in C++ 17
Two options:
A ranged-for version of @πάνταῥεῖ 's answer:
for (auto const& pair : myMap) {
auto key = pair.first;
// etc. etc.
}Use the ranges-v3 library (or
std::ranges
in C++20) to adapt the rangemyMap.begin()
andmyMap.end()
by projecting it onto its first coordinate. Then you'd write something like:for (auto key : keys_of(myMap) ) {
// etc. etc.
}you can do this without ranges if
keys_of()
materializes all of the keys, but that could be expensive for a larger map.(If you have weird, heavy keys, then
const auto& key
instead ofauto key
.)
How to iterate over a C++ STL map data structure using the 'auto' keyword?
This code uses 2 new features from C++11 standard the auto keyword, for type inference, and the range based for loop.
Using just auto
this can be written as (thanks Ben)
for (auto it=mymap.begin(); it!=mymap.end(); ++it)
Using just range for this can be written as
for (std::pair<const char,int>& x: mymap) {
std::cout << x.first << " => " << x.second << '\n';
}
Both of these do the exact same task as your two versions.
How can I loop through a C++ map of maps?
Old question but the remaining answers are outdated as of C++11 - you can use a ranged based for loop and simply do:
std::map<std::string, std::map<std::string, std::string>> mymap;
for(auto const &ent1 : mymap) {
// ent1.first is the first key
for(auto const &ent2 : ent1.second) {
// ent2.first is the second key
// ent2.second is the data
}
}
this should be much cleaner than the earlier versions, and avoids unnecessary copies.
Some favour replacing the comments with explicit definitions of reference variables (which get optimised away if unused):
for(auto const &ent1 : mymap) {
auto const &outer_key = ent1.first;
auto const &inner_map = ent1.second;
for(auto const &ent2 : inner_map) {
auto const &inner_key = ent2.first;
auto const &inner_value = ent2.second;
}
}
How to iterate map containing set in c++?
for (std::map<int, std::set<int> >::const_iterator i = haha.begin(); i != haha.end(); ++i) {
int key = i->first;
const std::set<int>& values = i->second;
}
Create a template to iterate map in C++11 like C++17's structured bindings
You cannot initialize variables inside the range-based loop until C++20, so the best option, that I can see to use such macro:
#define STRUCTURED_BINDING(a, b, map_item) \
const auto &a = map_item.first; \
const auto &b = map_item.second;
So then in your code, you can write something like that:
for(const auto& item: a)
{
STRUCTURED_BINDING(fst, snd, item);
std::cout << fst << " " << snd << std::endl;
}
You can improve this macro to be used with tuple (get<0>
, get<1>
, ...), rewriting macro to use variadic arguments.
Iterate keys in a C++ map
If you really need to hide the value that the "real" iterator returns (for example because you want to use your key-iterator with standard algorithms, so that they operate on the keys instead of the pairs), then take a look at Boost's transform_iterator.
[Tip: when looking at Boost documentation for a new class, read the "examples" at the end first. You then have a sporting chance of figuring out what on earth the rest of it is talking about :-)]
C++ loop through map while erasing
http://en.cppreference.com/w/cpp/container/map/erase :
References and iterators to the erased elements are invalidated. Other
references and iterators are not affected.
(So make sure you increment and save a "next" iterator before you erase.
Edit: In fact since C++11
, erase
returns the next iterator anyway, so you may use that.)
How do you iterate through a C++ map?
for( auto const& pair : family )
{
cout << pair.first << " represented by object at " << (void*)pair.second << "\n";
}
Instead of using a loop to delete objects, consider storing the objects directly instead of pointers to dynamically allocated objects.
Here's one way to delete all Person
objects and remove their map entries:
while( not family.empty() )
{
auto const it = family.begin();
delete it->first;
family.erase( it );
}
If instead you store Person
objects (not pointers to dynamically allocated objects) this reduces to
family.clear();
Related Topics
Static Constexpr Member of Same Type as Class Being Defined
Why Does the Library Linker Flag Sometimes Have to Go at the End Using Gcc
Why Do We Need to Use Boost::Asio::Io_Service::Work
How to Cout a Float Number with N Decimal Places
Compare Two Float Variables in C++
When Should I Use C++14 Automatic Return Type Deduction
How Does the Standard Library Implement Std::Swap
Fast Cross-Platform C/C++ Image Processing Libraries
Order of Execution in Constructor Initialization List
Is Std::Pair<Int, Std::String> Ordering Well-Defined
How to Combine Several C/C++ Libraries into One
How Can an Incomplete Type Be Used as a Template Parameter to Vector Here
How to Access a Local Variable in Outer Scope in C++
C++ Uninitialized Local Variable
How to Hook Windows Functions in C/C++