int main () {
vector<int> myvector;
vector<int>::iterator it;
// set some values:
for (int i=1; i<=5; i++)
myvector.push_back(i*10); // myvector: 10 20 30 40 50
myvector.resize(myvector.size()+3); // allocate space for 3 more elements
copy_backward ( myvector.begin(), myvector.begin()+5, myvector.end() );
开发者_运维百科 cout << "myvector contains:";
for (it=myvector.begin(); it!=myvector.end(); ++it)
cout << " " << *it;
cout << endl;
return 0;
}
Why the output is "myvector contains: 10 20 30 10 20 30 40 50"
why not "30 40 50 10 20 30 40 50"
The implementation of copy_backward is here:
template<class BidirectionalIterator1, class BidirectionalIterator2>
BidirectionalIterator2 copy_backward ( BidirectionalIterator1 first,
BidirectionalIterator1 last,
BidirectionalIterator2 result )
{
while (last!=first) *(--result) = *(--last);
return result;
}
So confused. thank you for all your help.
That output looks right to me according to the way the code is written. You are copying from and into the same vector. You are copying from [begin, begin +5] (10 20 30 40 50) and you are copying to [end, end-5]. So 10 20 30 [10 20 30 40 50] is the right output for that code. The first 3 elements are untouched.
If you want to copy something backwards, use reverse-iterators: rbegin()
and rend()
. Then just use the regular std::copy
.
精彩评论