0
template <typename T>
void DisplayVector(const vector<T>& inVec)
{
    for (const auto& element : inVec)
        cout << element << ' ';
    cout << endl;
}

and

template <typename T>
void DisplayVector(const vector<T>& inVec)
{
    for (auto element : inVec)
        cout << element << ' ';
    cout << endl;
}

How much information (like const and &) can the compiler infer from the type of inVec? What is the type difference of the two elements in the above code?

  • The second copies each element. The first uses the value directly from the vector using a const reference – drescherjm Apr 18 '22 at 02:25
  • `auto const&` is a `const` reference (an *alias*) to the member in the vector *in situ*. `auto&&` is a reference to the member in the vector *in situ*, which will be `const` if needed. `auto` will be a *copy* of the member. `auto&` will be a reference that will fail if it needs to be `const`. – Eljay Apr 18 '22 at 12:39

0 Answers0