简体   繁体   English

C ++ STL copy_backward问题

[英]c++ STL copy_backward question

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" 为什么输出为“ myvector包含:10 20 30 10 20 30 40 50”

why not "30 40 50 10 20 30 40 50" 为什么不“ 30 40 50 10 20 30 40 50”

The implementation of copy_backward is here: copy_backward的实现在这里:

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]. 您正在从[begin,begin +5]开始复制(10 20 30 40 50),然后复制到[end,end-5]。 So 10 20 30 [10 20 30 40 50] is the right output for that code. 因此10 20 30 [10 20 30 40 50]是该代码的正确输出。 The first 3 elements are untouched. 前三个元素保持不变。

If you want to copy something backwards, use reverse-iterators: rbegin() and rend() . 如果要向后复制某些内容,请使用反向迭代器: rbegin()rend() Then just use the regular std::copy . 然后只需使用常规的std::copy

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM