c++c++11

How to properly copy values from array to vector?


I have code that copies values from array to vector. But it does not work. In the last line, I get this error:

 error: cannot bind 'std::basic_ostream<char>' lvalue to 'std::basic_ostream<char>&&'
         cout << "s: " <<  tv << endl;
              ^
int t[] = {1,2,3,4,5};
vector<int> tv;
    
for (int i=0;i<5;i++)
    tv.push_back(i);
    
for (int v: tv)
    cout << "s: " <<  tv << endl;

Solution

  • For more "proper" way, replace this code:

    int t[] = {1,2,3,4,5};
    vector<int> tv;
    
    for (int i=0;i<5;i++)
        tv.push_back(i);
    

    with this:

    const int t[] = {1,2,3,4,5};
    const vector<int> tv( begin( t ), end( t ) );
    

    where begin and end are std::begin and std::end from the <iterator> header.


    Oh, the compilation error: simple typo, writing tv instead of t.