简体   繁体   中英

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/ . 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. But here are my questions: What does - 1 do? Since arrays are fixed in size how does this lower the amount of memory taken up by the vector? And how exactly does the last element get popped back?

length-- evaluates to the value of length (decrementing after evaluation). So the item you're accessing is arr[length - 1] . You need the -1 because array indexes start at zero.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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