Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!
  • C#

Idiom #112 Iterate over map entries, ordered by keys

Print each key k with its value x from an associative array mymap, in ascending order of k.

using System.Collections.Generic;
SortedDictionary<string, string> myMap;
foreach (var item in myMap)
{
  Console.WriteLine($"{item.Key}={item.Value}");
}
	
#include <iostream>
#include <map>
std::map< K, V > _mymap;
for (const auto& pair : _mymap) {
    std::cout << pair.first << ": " << pair.second << "\n";
}

std::map is a sorted collection that uses std::less by default.

New implementation...