代码之家  ›  专栏  ›  技术社区  ›  Pekov

如何重载std::vector::operator=()

  •  -1
  • Pekov  · 技术社区  · 7 年前

    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;
    }
    

    我试过这种方法,但编译器不同意: error: invalid use of incomplete type ‘class std::vector<_RealType>’

    是否可以重载std::vector类的赋值运算符?

    2 回复  |  直到 7 年前
        1
  •  1
  •   JVApen    7 年前

    不,不可能这样做。如果扩展 std 命名空间,除非标准明确允许使用这些符号。也就是说,我没有看到编译器投入资源来跟踪它。然而,它可能与已经使用的符号冲突。

    确实有一些类似于铸造操作员的东西: operator std::vector<int>() const 这需要添加到需要转换的类型中。但是,由于这也是库的一部分,我认为您没有有效的选项。

        2
  •  1
  •   R Sahu    7 年前

    1. operator=
    2. 除非函数被声明为类的成员函数,否则无法按现有方式定义运算符函数。
    3. 有一些简单的变通方法可以指定 arma::vec oprator= 超载。

    演示如何将不同类型的容器分配给 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;
    }
    

    在您的情况下,您可以使用以下任一选项:

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