karthik
karthik

Reputation: 17842

How to use copy function in Vector?

I want to copy collection of structures from one vector to another vector in mfc.

My Vector Structure is

     typedef  vector<CLog *> CLogData;

     typedef vector<CLog * > tLogData;

how to copy the TYPE CLog* from CLogData to tLogData?

Regards,

Karthik

Upvotes: 0

Views: 432

Answers (3)

MacGucky
MacGucky

Reputation: 2504

To copy one vector to another you can use std::copy in two ways:

1) resize target-vector and copy by iterator:

tlogData.clear();
tlogData.resize(CLogData.size());
std::copy(CLogData.begin(), CLogData.end(), tLogData.begin());

2) use an back_inserter:

std::copy(CLogData.begin(), CLogData.end(), std::back_inserter(tLogData));

But that copys only the pointers from one vector to another - the pointers direct to the same objects in both vectors!


If you want to really copy the objects, you have to create new ones:

size_t n = CLogData.size();
for (size_t i = 0; i < n; ++i) {
   tLogData.push_back(new CLog(*CLogData[i]));
}

This works only if CLog has an copy-constructor.

Upvotes: 1

Xeo
Xeo

Reputation: 131837

If you want a shallow copy of the CLog* pointers, use the answer MacGucky gave. If you need a deep copy of the actual data the CLog* pointers point to, you need to do it manually in a loop:

CLogData cl;
tLogData tl;
// fill cl
for(size_t i = 0; i < cl.size(); ++i){
  // invokes the copy ctor of CLog
  CLog* plog = new CLog(*cl[i]);
  tl.push_back(plog);
}

Upvotes: 1

Oswald
Oswald

Reputation: 31685

Both types are the same. So you can just do

CLogData cl;
tLogData tl;
// todo: fill cl

tl = cl;

Upvotes: 1

Related Questions