1
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.

David Degea
  • 1,378
  • 2
  • 12
  • 18

2 Answers2

2

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.

Skrymsli
  • 5,173
  • 7
  • 34
  • 36
1

If you want to copy something backwards, use reverse-iterators: rbegin() and rend(). Then just use the regular std::copy.

Nicol Bolas
  • 449,505
  • 63
  • 781
  • 982
  • I'm not sure how this helps. To be fair, I'm not sure exactly what the OP wants. Where would the data for the 'new' first three elements come from? – Michael Burr Aug 02 '11 at 22:09