c++ - 修改 BOOST_FOREACH 中 vector 的内容

标签 c++ boost vector foreach

这是一个关于 BOOST_FOREACH 如何检查它的循环终止的问题

cout << "Testing BOOST_FOREACH" << endl;
vector<int> numbers; numbers.reserve(8);
numbers.push_back(1); numbers.push_back(2); numbers.push_back(3);
cout << "capacity = " << numbers.capacity() << endl;
BOOST_FOREACH(int elem, numbers)
{
    cout << elem << endl;
    if (elem == 2) numbers.push_back(4); 
}
cout << "capacity = " << numbers.capacity() << endl;

给出输出

Testing BOOST_FOREACH
capacity = 8
1
2
3
capacity = 8

但是在循环中途插入的数字 4 呢?如果我将类型更改为列表,新插入的数字将被迭代。如果需要重新分配, vector push_back 操作将使任何指针无效,但是在本示例中不会发生这种情况。所以我想的问题是,为什么 end() 迭代器在使用 vector 时似乎只被评估一次(在循环之前),但在使用列表时具有更动态的评估?

最佳答案

Under the covers, BOOST_FOREACH uses iterators to traverse the element sequence. Before the loop is executed, the end iterator is cached in a local variable. This is called hoisting, and it is an important optimization. It assumes, however, that the end iterator of the sequence is stable. It usually is, but if we modify the sequence by adding or removing elements while we are iterating over it, we may end up hoisting ourselves on our own petard.

http://www.boost.org/doc/libs/1_40_0/doc/html/foreach/pitfalls.html

如果您不希望 end() 迭代器更改,请对 vector 使用 resize 而不是保留。

http://www.cplusplus.com/reference/stl/vector/resize/

请注意,您不想 push_back 而是使用 operator[]。但要小心不要越界。

关于c++ - 修改 BOOST_FOREACH 中 vector 的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1801251/

相关文章:

c++ - 在 C++ 中使用 vector vector (二维 vector )的邻接表表示

javascript - p5.j​​s 中向量数组的问题

c++ - 是否可以在 POSIX 系统上部分释放动态分配的内存?

c++ - 派生类中virtual operator==的重新定义

c++ - boost 累加器滚动计数非零

c++ - Boost.Log 与 Boost.Log v2

c++ - 添加多个相同类型的 boost::error_infos 到一个 boost::exception

c++ - 此代码中调试断言的原因

c++ - 在基于 Visual Studio MFC 的应用程序中禁用事件处理程序

c++ - const vector<string> 还是 const string[]?