Hello!
I'm trying to overload the left stream operator so that it'll add elements to a vector. I'm really stumped as to why I'm getting an error.
Here's what I have:
#include "chai.h"
#include <vector>
#include <iostream>
#include <stdexcept>
using std::vector;
vector<int> operator<<(const vector<int>& v, int x){
v.push_back(x);
return v;
}
vector<int> operator+(const vector<int>& lhs, const vector<int>& rhs){ // return type is a vector of integers
if(lhs.size() != rhs.size()){ // Vectors must be the same size in order to add them!
throw std::runtime_error("Can't add two vectors of different sizes!");
}
vector<int> result; // Declaring the resulting vector, result
for(int i=0; i < lhs.size(); i++){ // adding each element of the result vector
result.push_back(lhs.at(i) + rhs.at(i)); // by adding each element of the two together
}
return result; // returning the vector "result"
}
The error I get is in chai.cpp:
In function 'std::vector<int> operator<<(const std::vector<int>&, int)':
error: passing 'const std::vector<int>' as 'this' argument of 'void std::vector<_Tp, _Alloc>::push_back(const value_type&> [with_Tp = int; _Alloc = std::allocator<int>; std::vector<_Tp, _Alloc>::value_type = int]' discards qualifiers [-fpermissive]
Also, would using std::cout<<"Some string" be changed because I overloaded the << operator?
vector<int> //returning a copy
operator<<(
const vector<int>& v, //we promise that we are not going to modify this vector
int x)
{
v.push_back(x); //we try to modify it
return v;
}
vector<int>& //for chaining
operator<<(
vector<int>& v, //we are going to modify
int x)
{
v.push_back(x);
return v; //the same object that we receive as parameter
}