gpt4 book ai didi

c++ - C++ 中的 vector::清除

转载 作者:IT老高 更新时间:2023-10-28 22:18:04 27 4
gpt4 key购买 nike

当应用于 vector 时,我在理解 C++ clear 函数的行为时遇到了一些困难。

我尝试编译并运行以下函数:

#include <iostream>
#include <vector>
using namespace std;

int main ()
{
unsigned int i;
vector<int> myvector;
myvector.push_back (1);
myvector.push_back (2);
myvector.push_back (3);

cout << "myvector contains:";
for (i=0; i<myvector.size(); i++) cout << " " << myvector[i];

myvector.clear();
myvector.push_back (11);
myvector.push_back (12);

cout << "\nmyvector contains:";
for (i=0; i<myvector.size(); i++) cout << " " << myvector[i];
cout << endl;

cout << " entry3 = " << myvector[2]<<endl;

return 0;
}

这是输出:

myvector contains: 1 2 3
myvector contains: 11 12
entry3 = 3

怎么可能在清除vector的时候,vector的第三个entry的信息还没有被删除?

最佳答案

来自文档:

All the elements of the vector are dropped: their destructors are called, and then they are removed from the vector container, leaving the container with a size of 0.

基本上,您是在 myvector[2] 上调用 undefined behavior,因为该项目不再存在。在调用 clear() 之后,您只在 vector 中推送了 2 个元素,因此只能访问索引 01

你很不幸它没有崩溃,因为看起来工作可以隐藏错误。无法保证该值会被删除。

尝试使用 .at(2) 访问元素会导致抛出异常(operator[]() 不做任何边界检查,而 at() 确实)。

关于c++ - C++ 中的 vector::清除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12840711/

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