Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overloading operator= for struct members of class std::vector<>

Tags:

c++

struct

vector

Say I have the following struct:

struct Parameter {
  double value;
  double error;
};

So that I'm usually working with vectors of that struct (ie. std::vector<Parameter>), and ocasionally I want to set a vector of values (but not errors) in that vector of parameters by using the operator= with a standard std::vector, for convenience.

std::vector<Parameter> vector_of_parameters;
std::vector<double> vector_of values;
....
vector_of_parameters = vector_of_values;

To do so, I'm trying to overload operator= for this struct as follows:

std::vector<Parameter> operator=(const std::vector<double>& v) {
  this->clear();
  for (const auto& i:v) {
    Parameter p;
    p.value = i;
    this->push_back(p);
  }
  return *this;
}

But this will return an error saying that std::vector operator=(const std::vector& v) must be a non-static member. So if I understand it correctly, I have to define this as a member function of the operator as:

std::vector<Parameter>::operator=(const std::vector<double>& v) {
  this->clear();
  for (const auto& i:v) {
    Parameter p;
    p.value = i;
    this->push_back(p);
  }
  return *this;
}

The error now says that a syntaxis with template<>, but I dont really see it, or understand it, and don't know what more can I do.

like image 949
elcortegano Avatar asked Feb 12 '26 06:02

elcortegano


1 Answers

You cannot overload the assignment operator of std::vector. operator = must be a member function and you just can't add a member function to std::vector.

What you can do is make a convenience function like create_parameters that takes a std::vector<double> and returns a std::vector<Parameter>. That would look like

std::vector<Parameter> create_parameters(std::vector<double> const& params)
{
    std::vector<Parameter> ret(params.size());
    std::transform(params.begin(), params.end(), ret.begin(),
                   [](auto value) { return Parameter{value, 0}; });
    return ret;
}

and then

vector_of_parameters = vector_of_values;

would become

vector_of_parameters = create_parameters(vector_of_values);
like image 80
NathanOliver Avatar answered Feb 15 '26 11:02

NathanOliver



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!