Loops and auto

suggest change

This example shows how auto can shorten the type written in a for loop. A std::map<int, std::string> element is std::pair<const int, std::string>, not std::pair<int, std::string>.

std::map<int, std::string> Map;
for (auto pair : Map) {}                 // pair is std::pair<const int, std::string>
for (const auto pair : Map) {}           // pair is const std::pair<const int, std::string>
for (const auto& pair : Map) {}          // pair is const std::pair<const int, std::string>&
for (auto i = 0; i < 1000; ++i) {}       // i is int
for (auto i = 0; i < Map.size(); ++i) {} // i is int; Map.size() is std::size_t
for (auto i = Map.size(); i > 0; --i) {} // i is std::size_t

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents