【问题标题】:Moving vector pointer to derived class of vector in C++?将向量指针移动到C++中的向量派生类?
【发布时间】:2018-01-27 21:55:38
【问题描述】:

我想将向量的指针移动到我的 A 对象 (this) 的向量。我想这样做是因为我使用我的帮助向量(用于合并排序)并且我想要原始向量中的帮助向量的值。然而,我只想使用 1 个操作(因此应该通过移动来完成,不要复制元素)。

这是我使用的代码:

template<class T>
class A:public vector<T> {
    public:
        void fillAndMove();

        vector<T> help;
}

template<class T>
void A<T>:fillAndMove() {
    // Fill a help array with random values
    help.resize(2);
    help[0] = 5;
    help[1] = 3;

    // This line doesn't work
    *this = move(help);
}

我收到以下错误:

no match for 'operator=' (operand types are 'A<int>' and 'std::remove_reference<std::vector<int, std::allocator<int> >&>::type {aka std::vector<int, std::allocator<int> >}')

我认为问题在于需要将帮助向量转换为 A 类对象,但我不知道该怎么做。谁能帮帮我?

【问题讨论】:

    标签: c++ class c++11 vector move


    【解决方案1】:

    你想实现移动赋值运算符,它将在 O(1) 中完成。

    template<class T>
    class A :public vector<T> {
    public:
        void fillAndMove();
    
        vector<T> help;
    
        A & operator=(std::vector<T> && rhs)
        {
            static_cast<vector<T>&>(*this) = move(rhs);
            return *this;
        }
    };
    

    它也允许将法线向量分配给您的 A 类,这将保持 help 向量不变,因此您可能希望将此运算符设为 private 并为 A 类实现移动分配运算符。

        test = std::vector<int>{ 5,6 }; // possible - should assigment operator be private?
    

    无法使用此代码:

    template<class T>
    class A :public vector<T> {
    public:
        void fillAndMove();
    
        vector<T> help;
    
        A & operator=(A && rhs)
        {
            // Move as you want it here, probably like this:
            help = std::move(rhs.help);
            static_cast<vector<T>&>(*this) = move(rhs);
            return *this;
        }
    
    private:
        A & operator=(std::vector<T> && rhs)
        {
            static_cast<vector<T>&>(*this) = move(rhs);
            return *this;
        }
    };
    

    此外,在执行此操作时,您还应该实现移动构造函数。

    【讨论】:

    • 非常感谢,这正是我所需要的!
    【解决方案2】:

    如果你想以这种方式使用它,你必须重载运算符分配

    A & operator=(const std::vector<T> & rhs)
    {
        for(auto it : help)
        {
            this->push_back(it);
        }
        return *this;
    }
    

    Working example here.

    【讨论】:

    • 但这意味着您移动向量的每个元素,我的目标是移动向量本身的指针,而不是移动向量内的每个指针。你在做什么需要 O(n) 操作,我只想要 O(1) 操作。这可能吗?
    • 我刚刚尝试了我所知道的一切,但我无法用 O(1) 解决它,抱歉。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-03-28
    • 2018-12-24
    • 1970-01-01
    • 2020-04-13
    • 2021-09-20
    • 2021-11-22
    • 1970-01-01
    相关资源
    最近更新 更多