Copy from vector to vector in C+

2020-07-13 10:32发布

I create a vector A and want to copy to a vector B in another class by using below method, is it a correct way? The vector A may be destroyed! I searched in google, but not found the good solution and meaningful explanation. Thanks everyone

void  StateInit(vector<CButton*> listBtn) 
{ 
   _m_pListBtn = listBtn; 
 };

标签: c++ stdvector
2条回答
爱情/是我丢掉的垃圾
2楼-- · 2020-07-13 11:05

Yes and no, you are passing the vector by value:

void  StateInit(vector<CButton*> listBtn) 
{ 
   _m_pListBtn = listBtn; 
 };

Wich means that listBtn is a copy of vector A (asuming we are calling vector A the one passed as parameter of StateInit), if you delete vector A, vector B will still have the collection of pointers and they will be valid since the destruction of a vector of pointers doesnt delete the pointed objects because it cant possible now how (should it call, delete, delete[], free?).

Do keep in mind that if you modify/delete one of the elements from vector A (using the pointers on the vector), that element will be modified in vector B (since its a pointer to the same element).

Im not sure what is your intend with this, but if you want to copy the whole vector, you should implement a clone mechanism for the objects and then copy them using transform:

class cloneFunctor {
public:
    T* operator() (T* a) {
        return a->clone();
    }
}

Then just:

void  StateInit(vector<CButton*> listBtn) 
{ 
   transform(listBtn.begin(), listBtn.end(), back_inserter(_m_pListBtn), cloneFunctor()); 
 };

IF your intention is not to clone it but to share the pointers you should pass the vector as pointer or reference:

void StateInit(const vector<CButton*>& listBtn) 
{ 
   _m_pListBtn = listBtn; 
};
查看更多
仙女界的扛把子
3楼-- · 2020-07-13 11:13

A better way is to iterate on the new vector and push_back the elements to your vector.

See example code: std::vector::begin

查看更多
登录 后发表回答