C++ Loop Through Map

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:

  1. A ranged-for version of @πάνταῥεῖ 's answer:

    for (auto const& pair : myMap) {
    auto key = pair.first;
    // etc. etc.
    }
  2. Use the ranges-v3 library (or std::ranges in C++20) to adapt the range myMap.begin() and myMap.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 of auto 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



Leave a reply



Submit