gpt4 book ai didi

c++ - 有人可以解释他们的意思是 list.pushback 文档(不会使迭代器无效)

转载 作者:行者123 更新时间:2023-11-30 02:03:33 25 4
gpt4 key购买 nike

在 list.pushback 文档中说

Due to the nature of a %list this operation can be done in constant time, and does not invalidate iterators and references.

add怎么不能改变迭代器?不使引用无效是什么意思?

谢谢

最佳答案

这意味着在调用 push_back 之前获得的所有迭代器和引用仍然可以在之后使用:

std::list<int> numbers { 2, 3, 5, 7};
auto it = numbers.begin();
int& r = numbers.front();
numbers.push_back(11);
std::cout << *it << '\n'; // guaranteed to print 2
std::cout << r << '\n'; // guaranteed to print 2

其他数据结构不一定提供此类保证。如果您使用 vector 而不是列表,则每次调用 push_back 都可能会使调用之前获得的所有迭代器和引用无效,因为容量可能会耗尽,在这种情况下,数据必须被移动到一个更大的数组中。使用无效的迭代器或引用会导致未定义的行为(阅读:任何事情都可能发生)。

关于c++ - 有人可以解释他们的意思是 list.pushback 文档(不会使迭代器无效),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11735278/

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