al_the_coug
al_the_coug

Reputation: 21

Overloading << operator to insert into a vector

I have found many solutions that overload the output stream operator to print out a vector. I need to do the opposite. Something like,

vector<string> v;
  v << "String1" << "String2" << "String3" << "String4" << "String5";

I have this code, which only adds the first string. I understand why that is, but I can't figure out how to add the other strings.

template<typename T, typename T2>
vector<T> operator<<(vector<T>& v1, T2 s) {
    v1.push_back(s);
    return v1;
}

Upvotes: 1

Views: 238

Answers (1)

R Sahu
R Sahu

Reputation: 206567

In your function, you are returning a copy of the input vector. I am surprised your compiler didn't warn you about using a temporary object as an argument where a reference is expected.

Change the return type to a reference.

template<typename T, typename T2>
vector<T>& operator<<(vector<T>& v1, T2 s) {
//      ^^^
    v1.push_back(s);
    return v1;
}

Upvotes: 7

Related Questions