Tiger
Tiger

Reputation: 43

Moving (not copying) part of a vector to another vector using C++98

In C++11 we can do the following:

std::vector<int> A(n);
std::vector<int> B; 
// I want to move part of A (from A[start] to A[end]) to B
std::move(A.begin()+start,A.begin()+end,std::back_inserter(B));
// in C++98 there is no move operator, so use copy (assign)
B.assign(A.begin()+start, A.begin()+end);

Is there any way in C++98 to do something similar to C++11 implementation. The goal is to save time and use move instead of copying the vector, do you have any idea?

In the real code, I am not using int, It is vector of object.

Upvotes: 2

Views: 149

Answers (2)

UKMonkey
UKMonkey

Reputation: 6983

While move semantics didn't exist in C++98, you can always write something that does the equivalent yourself for this situation.

A quick and easy way to do it would be to just introduce a "moveTo" function on your class that you plan to work with, and then just call that with the reference/pointer of where you want to move it to.

It's worth highlighting that I have said "on your class"; because as Arnav Borborah said, your example is too trivial to make a difference; but I highlight this option in case it's a poor example.

Upvotes: 1

Arnav Borborah
Arnav Borborah

Reputation: 11789

Unfortunately, move semantics are not available in C++98, (Since they were introduced in C++11), but for the example given, moving the integers is not much different from copying them, so the actual performance difference should be negligible, if there is any.

Upvotes: 1

Related Questions