gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 15:10:48 25 4
gpt4 key购买 nike

这是一个关于 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com