C++ has changed a lot since I was first learned about it in college, so I’m going to do a series of posts outlining some of those changes as they come up for me. First off: range-based for-loops using auto type-inference. Here’s the TL;DR:
- Use
auto iwhen you want to work with copies of the array items - Use
auto &iwhen you want to work with the original items and maybe modify them place - Use
auto const &iwhen you want to work with the original items and not modify them
#include <iostream>
using namespace std;
int main()
{
// basic 10-element integer array
int arr[10] = {0,1,2,3,4,5,6,7,8,9};
// range based for loop to iterate over the array
// access of arr by value declared as a specific type
for (int i: arr)
{
cout << i << " ";
}
cout << endl;
// access of arr by value using type-inference
for (auto i: arr)
{
cout << i << " ";
}
cout << endl;
// type-inference and access by reference
// used when modifying arr in-place
for (auto &i: arr)
{
cout << i << " ";
}
cout << endl;
// type-inference and access by reference
// used when not modifying in-place
for (auto const &i: arr)
{
cout << i << " ";
}
cout << endl;
}
Compile as:
$ g++ --std=c++14 -o range-based-for-loop range-based-for-loop.cpp