Modern C++ › C++11
auto, nullptr and Range-based for
Let the compiler deduce types, use a real null pointer, and iterate containers without iterator boilerplate.
Since C++11 beginner #auto#nullptr#range-for#type-deduction
Explanation
autodeduces a variable’s type from its initializer.nullptrhas its own type (std::nullptr_t) and converts to any pointer type, unlike0orNULL.- Range-based
foriterates any type withbegin()/end().
Example
#include <iostream>
#include <map>
#include <string>
#include <vector>
int main() {
std::vector<int> v = {1, 2, 3}; // also C++11: initializer lists
for (int x : v) std::cout << x << ' '; // copy
for (auto& x : v) x *= 2; // modify in place
std::cout << '\n';
std::map<std::string, int> ages = {{"Ann", 30}, {"Bob", 25}};
for (const auto& kv : ages) // no verbose iterator type
std::cout << kv.first << " = " << kv.second << '\n';
int* p = nullptr; // not 0 / NULL
std::cout << (p == nullptr) << '\n';
}
Pitfalls
autodrops references and top-levelconst: writeauto&orconst auto&when you mean it.for (auto x : bigObjects)copies each element. Preferconst auto&.- Modifying the container’s size inside a range-for invalidates iterators.
Legacy vs modern
// C++98
for (std::map<std::string,int>::const_iterator it = ages.begin(); it != ages.end(); ++it)
std::cout << it->first << '\n';
// C++11
for (const auto& kv : ages) std::cout << kv.first << '\n';
Exercises
1. What type does auto x = 3.0f * 2; deduce?
float: the int is converted to float in the multiplication.