This language bar is your friend. Select your favorite languages!
Select your favorite languages :
- Or search :
- C++
- C++
- C#
- D
- Dart
- Go
- Go
- Go
- Groovy
- Haskell
- JS
- Java
- Java
- Java
- Java
- Java
- Java
- Lua
- PHP
- Perl
- Prolog
- Python
- Python
- Python
- Ruby
- Rust
- Scala
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.
auto print(auto&... args) {
// c++17 fold expression
(std::cout << ... << args) << std::endl;
}
auto print_map_contents(auto mymap) {
// c++17 structured binding
for (auto [k, x] : mymap) {
print("mymap[", k, "] = ", x);
}
}
auto main() -> int {
// map is ordered map, iteration is ascending by key value
auto map = std::map<std::string, int> {
{"first entry", 12},
{"second entry", 42},
{"third entry", 3},
};
print_map_contents(map);
}
keys := make([]string, 0, len(mymap))
for k := range mymap {
keys = append(keys, k)
}
sort.Strings(keys)
for _, k := range keys {
x := mymap[k]
fmt.Println("Key =", k, ", Value =", x)
}
First extract the keys, then sort them, then iterate.
Adapt for key types other than string.
Adapt for key types other than string.
mymap.sort { it.key }.each { println it}
Keys in mymap are automatically turned into string values in Groovy
[...mymap.entries()].sort().map(([_, x]) => console.log(x))
mymap has type Map.
We have to spread mymap.entries() because it returns an iterator instead of a list.
We have to spread mymap.entries() because it returns an iterator instead of a list.
SortedMap<K, V> mymap = new TreeMap<>();
...
for(Map.Entry<K, V> e: mymap.entrySet())
System.out.println("Key=" + e.getKey() + ", Value=" + e.getValue());
When mymap implements SortedMap, sorted iteration is straightforward.
dict_pairs(D, _, Ps),
forall(member(K-V, Ps),
format("~w:~w~n", [K, V]))
Map a dict to an ordered list of pairs, and print them to standard output using forall