1

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;
3
  • 4
    cout << "s: " << v << endl; Typo in the last line. Commented Feb 26, 2015 at 6:07
  • Stupid me. I was only concentrating on copping part, and trying pointers, references, auto, and others. :-) Commented Feb 26, 2015 at 6:11
  • 1
    That's ok... It happens for everyone of us. Commented Feb 26, 2015 at 6:27

3 Answers 3

4

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.

Sign up to request clarification or add additional context in comments.

3 Comments

why does the vector need to be const ? In the original code it's non-const. Making it const makes it looks like it has to be constant.
@Jagannath: To save work, add const whereever possible. I.e. it's the default choice. One doesn't need a reason to use const, one needs a reason to not use const. Making it non-const makes it look like it has to change. Does it?
I agree with the default const choice. But sometimes these "almost always..." type of thumb-rules confuse the newbies ( not saying OP is a newbie ). So, I believe we should add a bit of explanation as well if we say this is "proper" way to do.
2

At this line,

 cout << "s: " <<  tv << endl;

tv is vector<int> not int. Modify your code like this:

cout << "s: " << v << endl;

You can accept it now, Thanks.

Comments

0

Operator << is not overloaded for std::vector. You are supposed to print each element of vector like this:

#include <iostream>
#include <vector>

int main() {
    int t[] = {1, 2, 3, 4, 5};
    std::vector<int> tv;

    // Copy values from the array to the vector
    for (int i = 0; i < 5; i++) {
        tv.push_back(t[i]);
    }

    // Print each element of the vector
    for (int v : tv) {
        std::cout << "s: " << v << std::endl;
    }

    return 0;
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.