c++ - 使用 vector 时,pop_back 是否会连同元素一起删除值?

标签 c++ vector

为什么这样说:

cout << values[0] << " " << values[1] << " " << values[2] << endl;

显示

1 2 3

尽管使用了 pop back 从 vector 中删除最后一个元素。这些值不应该也被删除吗?还是即使删除了元素, vector 也会调整大小?

示例代码如下:

// This program demonstrates the vector pop_back member function.
#include <iostream>
#include <vector>
using namespace std;

int main()
{
    vector<int> values;

    // Store values in the vector.
    values.push_back(1); // Last element in values is 1
    values.push_back(2); // Now elements in values are 1,2
    values.push_back(3); // Now elements in values are 1,2,3

    cout << "The size of values is " << values.size() << endl; // values has 3 elements

    // Remove a value from the vector.
    cout << "Popping a value from the vector...\n";
    values.pop_back();
    cout << "The size of values is now " << values.size() << endl; // 1 is Removed thus size is 2
    cout << values[0] << " " << values[1] << " " << values[2] << endl;

    // Now remove another value from the vector.
    cout << "Popping a value from the vector...\n";
    values.pop_back();
    cout << "The size of values is now " << values.size() << endl;
    cout << values[0] << " " << values[1] << " " << values[2] << endl;


    // Remove the last value from the vector.
    cout << "Popping a value from the vector...\n";
    values.pop_back();
    cout << "The size of values is now " << values.size() << endl;
    cout << values[0] << " " << values[1] << " " << values[2] << endl;

    return 0;

}

最佳答案

“值”和“元素”是一回事。 pop_back() 如果 vector 不为空,则从 vector 中删除最后一个值。

vector 的设计使得程序员有责任不越界访问 vector。如果一个 vector 有 2 个元素并且您尝试通过 at() 以外的任何方法访问第三个元素,您会导致 undefined behaviour .

要进行边界检查,请使用 values.at(0) 而不是 values[0] 等,并包含一个 try ...catch block 以捕获生成的异常。

关于c++ - 使用 vector 时,pop_back 是否会连同元素一起删除值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32577576/

相关文章:

c++ - 不正确的浮点行为

c++ - 在 std::map 中查找结构作为值

c++ - 如何将一个 vector 传递给另一个 vector 推回? (无需创建额外的变量来传递)

c++ - 在 C++ 中将对象作为参数传递给函数时修改的对象

vector - 如何在 Rust 中将值推送到 2D Vec?

c++ - 默认值输入错误的构造函数不会引发 GCC 7 错误

C++: *((SomeType*) 0 )?

C++对许多项目使用数组或 vector

c++ - 将大量二进制数据加载到 RAM 中

c++ - 如何获得调用带有特定参数的函数的信号?