2017-08-19 8 views
1

ベクトルのポインタをAオブジェクトのベクトルに移動したい(this)。私は私のヘルプベクトル(mergesort用)を使用しているので、元のベクトルのヘルプベクトルの値が必要なので、これを行いたいと思います。しかし、私は1つの操作だけを使用したい(したがって、それは移動で実行され、要素のコピーは行われません)。C++でベクトルの派生クラスへのポインタを移動しますか?

これは私が使用するコードです:

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のオブジェクトにキャストする必要があることだと思うけど私はそれをどうすればいいのか分かりません。私を助けることができる人?

答えて

1

、それを使用したい場合は、O(1)でそれを行います移動assigment演算子を、実装するオペレータの割り当てをオーバーロードする必要があります。

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; 
    } 
}; 
それは、そのまま helpベクトルを維持しますので、あなたがこの演算子 privateを作成し、クラスのパブリック用移動assigment演算子を実装する可能性があります、だけでなくしかし、あなたのクラスに法線ベクトルを割り当てることができます

。このコードで

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

また、あなたにも移動のコンストラクタを実装する必要があります。

+0

ありがとう、それは私が必要としていたものです! –

0

あなたがそのように

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

Working example here.

+0

しかし、これは、ベクトルのすべての要素を移動することを意味します。私の目標は、ベクトル自体のポインタを移動し、ベクトル内のすべてのポインタを移動しないことです。 O(n)の操作が必要です.O(1)操作のみが必要です。これは可能ですか? –

+0

私は知っているが、私はO(1)とそれを解決するcouldntのeveruthingを試みた。 –

関連する問題