how to iterate through map in c++ code example
Example 1: how to iterate through a map in c++
for(map<string,int>::iterator it=m.begin(); it!=m.end(); ++it)
if(it->second)cout<<it->first<<" ";
for(auto &x:m)
if(x.second)cout<<x.first<<" ";
Example 2: through map c++
for (auto& [key, value]: myMap) {
cout << key << " has value " << value << endl;
}
for (auto& kv : myMap) {
cout << kv.first << " has value " << kv.second << endl;
}
Example 3: c++ map iterator
#include <iostream>
#include <map>
int main() {
std::map<int, float> num_map;
for (auto it = num_map.begin(); it != num_map.end(); ++it) {
std::cout << it->first << ", " << it->second << '\n';
}
}
Example 4: cpp map iterate over keys
#include <iostream>
#include <map>
int main()
{
std::map<std::string, int> myMap;
myMap["one"] = 1;
myMap["two"] = 2;
myMap["three"] = 3;
for ( const auto &myPair : myMap ) {
std::cout << myPair.first << "\n";
}
}