3 ms·
In all honesty in my experience both of these approaches are wrong. Rather, it's using the good ol' typedef, which you should already be using pretty liberally
by mehrdadn 8y ago
In all honesty in my experience both of these approaches are wrong. Rather, it's using the good ol' typedef, which you should already be using pretty liberally anyway:
typedef std::map<std::string, int> Numbers;
Numbers numbers {
{ "one", 1 }, {"two", 2 }, { "three", 3 }
};
// each time entry is copied from pair<const string, int>!
std::for_each(std::begin(numbers), std::end(numbers),
[](const Numbers::value_type& entry) {
std::cout << entry.first << " = " << entry.second << '\n';
}
);
Or if you're feeling particularly pedantically correct, you can replace const Numbers::value_type& with Numbers::const_reference, but I don't go that far generally.
IMHO one of the mistakes of (many, even very experienced) C++ programmers is that they don't realize typedefs are such a powerful tool to be used liberally throughout a code base, and they instead overuse auto and decltype. Typedefs prevent you from repeating yourself, prevent accidents like these, make changing the underlying types a breeze, are self-documenting, and (when needed on occasion) let you use a different type for a variable than the expression used to initialize it, which isn't possible with auto.