简体   繁体   English

pop_back function 在自定义向量 class

[英]pop_back function in custom vector class

So I've been looking at code from this website: https://www.geeksforgeeks.org/program-to-create-custom-vector-class-in-c/ .所以我一直在看这个网站的代码: https://www.geeksforgeeks.org/program-to-create-custom-vector-class-in-c/ But I'm having a problem understanding this part:但是我在理解这部分时遇到了问题:

template <typename DT>
DT GenericMyVector<DT>::pop_back()
{
    return arr[length-- - 1];
}

I understand that this lowers int length by one, and when you call function size it will be smaller by one.我知道这会将int length降低一,当您调用 function 大小时,它会小一。 But here are my questions: What does - 1 do?但这是我的问题: - 1做什么? Since arrays are fixed in size how does this lower the amount of memory taken up by the vector?由于 arrays 的大小是固定的,这如何降低向量占用的 memory 的数量? And how exactly does the last element get popped back?最后一个元素究竟是如何弹出回来的?

length-- evaluates to the value of length (decrementing after evaluation). length--计算长度的值(计算后递减)。 So the item you're accessing is arr[length - 1] .因此,您正在访问的项目是arr[length - 1] You need the -1 because array indexes start at zero.您需要 -1 因为数组索引从零开始。

It's easier to think of the code as:更容易将代码视为:

template <typename DT>
DT GenericMyVector<DT>::pop_back()
{
    DT value = arr[length - 1];
    length--;
    return value;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM