C ++:在std :: vector中进行迭代的push_back [英] C++: push_back in std::vector while iterating it

查看:89
本文介绍了C ++:在std :: vector中进行迭代的push_back的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码段提供了非常奇怪的输出.我期待一个溢出(Python给出了MemoryError)

Following code snippet provides a very weird output. I was expecting an overflow( Python gives a MemoryError)

#include <iostream>
#include <vector>

int main()
{
    std::vector<int> a{1,2,3};

    for( auto const & item : a)
        a.push_back(item);


    for( auto const & item : a)
        std::cout<<item<<',';

    return 0;
}

输出:1,2,3,1,0,3,

我怎么解释这个结果?

如果您在Python中做类似的事情,则会出现内存错误.

If you do a similar thing in Python, it gives a memory error.

>>> a = range(0,20)
>>> for i in a:
    a.append(i)



Traceback (most recent call last):
  File "<pyshell#3>", line 2, in <module>
    a.append(i)
MemoryError

>>> 

我想到了这个问题,因为以上编写代码的方式被认为是绑定安全的.对于绑定的安全容器,在 foreach类型迭代中不应增长/收缩.因此,这是一个泄漏的抽象.

This question came to my mind, because above way of writing code is considered to be bound-safe. And for bound safety container should not grow/shrink during foreach type iteration. So, this is a leaky abstraction.

有没有一种方法可以包装此 foreach 循环,以便在循环体中不允许执行任何导致尺寸修改/重新分配的操作.

Is there a way one can wrap this foreach loop so that any operation causing size-modification/reallocation is not allowed in the loop body.

推荐答案

在C ++中,向向量中添加元素可能会导致所包含数据的重新分配,这将使所有迭代器无效.这意味着在插入新元素的同时,不能使用迭代器遍历向量(这是基于范围的for循环所做的事情).

In C++ adding elements to a vector may cause reallocation of the contained data, which will invalidate all iterators. That means you can't loop over the vector using iterators (which is what the range-based for loop does) while also inserting new elements.

可以使用索引进行迭代,并使用向量大小作为条件,因为索引将始终相同.

You can however iterate using indexes and use the vector size as condition, since indexes will always be the same.

这篇关于C ++:在std :: vector中进行迭代的push_back的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆