简体   繁体   中英

How to overload std::vector::operator=()

I need to have assignment of type std::vector = arma::vec, ie to assign vector from armadillo math library to a std::vector.

template <typename T>
std::vector<T>& std::vector<T>::operator=(arma::vec right) {
  std::size_t s(right.size());
  this->resize(s);
  for (std::size_t i = 0; i < s; i++)
    *this[i] = right(i);
  return *this;
}

I tried this way, but the compiler is not agree: error: invalid use of incomplete type 'class std::vector<_RealType>'

Is it possible to overload the assignment operator for std::vector class?

No, it isn't possible to do so. It's even undefined behavior if you extend the std namespace unless explicitly permitted by the standard for those symbols. That said, I don't see a compiler put in resources to track that. It however could conflict with symbols already in use.

In the implementations of the STL that I know, a lot of the functions are implemented in base classes with unspecified names.

There does consist something like a casting operator: operator std::vector<int>() const This needs to be added to the type that needs to be converted. However, as that's also part of a library, I don't think you have valid options.

Points to consider:

  1. operator= can be overloaded only as a member function.
  2. Defining the operator function the way you have is not possible unless the function is declared as member function of the class.
  3. There are easy work arounds to assign a arma::vec . Use them instead of trying to define an oprator= overload.

Example code that demonstrates how you can assign different kinds of containers to a std::vector .

#include <iostream>
#include <vector>
#include <set>

int main()
{
   std::vector<int> a;
   int b[] = {1, 2, 3, 4, 5};
   std::set<int> c{10, 20, 30, 40, 50};

   a = {std::begin(b), std::end(b)};

   for ( int el : a )
   {
      std::cout << el << " ";
   }

   std::cout << std::endl;

   a.assign(std::begin(c), std::end(c));

   for ( int el : a )
   {
      std::cout << el << " ";
   }

   std::cout << std::endl;
}

In your case, you can use either of the following:

std::vector<YourType> v;
v = {std::begin(right), std::end(right)};
v.assign(std::begin(right), std::end(right));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM