5 ms·
Some of them are complex, some are less complex than they used to be. For example look at the first article in this series that discusses the very common mistak
by shereadsthenews 8y ago
Some of them are complex, some are less complex than they used to be. For example look at the first article in this series that discusses the very common mistake of incorrect parameter types leading to unwanted copies, which is solved by generic lambdas where the compiler is permitted to deduce the type.
std::map<std::string, int> 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 std::pair<std::string, int>& entry) {
std::cout << entry.first << " = " << entry.second << '\n';
}
);
This has an error, which is harder to commit in c++14 and forward, with a more compact expression:
std::for_each(std::begin(numbers), std::end(numbers),
[](const auto& entry) {
std::cout << entry.first << " = " << entry.second << '\n';
}
);
- deleted 8y ago[deleted]
- mehrdadn 8y agoIn 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.