简体   繁体   English

迭代器无法访问完整向量

[英]Iterator does not access full vector

int main()
{
    vector<int> vi;

    vi.reserve(10);
   // back_insert_iterator<vector<int> > iter(vi);

    vector<int>::iterator iter = vi.begin();

    *iter = 1;
    ++iter;
    *iter = 2;
    ++iter;
    *iter = 3;

    back_insert_iterator<std::__1::vector<int> > iterb(vi);
    back_inserter(vi) = 4;
    back_inserter(vi) = 5;

    vi.reserve(vi.size() * 2);
    copy(vi.begin(), vi.end(), vi.end());

    ostream_iterator<int> os(cout, " ");
    copy(vi.begin(), vi.end(), os);
}

Question 1, why does cout print 4 5 , when I expected it will print 1 2 3 4 5 1 2 3 4 5 ? 问题1,为什么cout打印4 5 ,而我预期会打印1 2 3 4 5 1 2 3 4 5 Question 2, when I replace it with copy(vi.begin(), vi.end(), back_insert(vi)) , it will print 4 5 4 5 , why? 问题2,当我用copy(vi.begin(), vi.end(), back_insert(vi))替换它时,它将打印4 5 4 5 ,为什么?

Your code has undefined behavior, because you assign to iterators which are at or beyond the end. 您的代码具有未定义的行为,因为您将分配给末尾或末尾的迭代器。 The reserve() function does not update the size, only the capacity. reserve()函数不会更新大小,只会更新容量。 You might try resize() instead. 您可以尝试使用resize()代替。

copy(vi.begin(),vi.end(),vi.end()) doesn't work because std::copy writes to the destination iterator, and you can't write to the end iterator. copy(vi.begin(),vi.end(),vi.end())不起作用,因为std::copy写入目标迭代器,而您无法写入结束迭代器。

copy(vi.begin(),vi.end(),back_insert(vi)) doesn't work because the back_insert_iterator is changing the vector as it inserts, which invalidates the source iterators. copy(vi.begin(),vi.end(),back_insert(vi))不起作用,因为back_insert_iterator会在插入矢量时对其进行更改,这会使源迭代器无效。

You might try this instead: 您可以尝试以下方法:

 size_t vi_size = vi.size();
 vi.resize(vi_size*2);
 copy(vi.begin(),vi.begin()+vi_size,vi.begin()+vi_size);

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

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