使用向量时,pop_back是否会删除元素值?

Dan*_*son 1 c++ vector

为什么这个声明:

cout << values[0] << " " << values[1] << " " << values[2] << endl;
Run Code Online (Sandbox Code Playgroud)

显示

1 2 3

即使使用pop back来移除向量中的最后一个元素.不应该删除这些值吗?或者即使元素被删除,矢量也会调整大小?

以下是示例代码:

// 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;

}
Run Code Online (Sandbox Code Playgroud)

M.M*_*M.M 5

"价值"和"元素"是一回事.pop_back()如果向量不为空,则从向量中移除最后一个值.

vector被设计为程序员有责任不访问向量的界限.如果向量有2个元素,并且您尝试通过除以外的任何方法访问第三个元素at(),则会导致未定义的行为.

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