简体   繁体   中英

C++ | Get the last value in list

I have list of items (Item class) and I would like to get the last value of list, and it's show me stupid error when I run the program (The error is in runtime and no compiler error)

this is the code:

int id = 1;
if(items.size() > 0)
    id = items.end()->getID() + 1;

items is the list variable and getID() is a function of Item class and its' which return int

the error is "list iterator not dereferencable"

Thanks for help guys ;)

items.end() , and other end-of-container iterators (eg items.rend() ) point to one past the end of the list. Try items.back()->getID() + 1; .

std::list::end returns an iterator to the element following the last element of the container, This element acts as a placeholder; attempting to access it results in undefined behavior .

You could use std::list::back or reverse iterator std::list::rbegin

try:

items.back()->getID() +1;
(*items.rbegin())->getID() +1;

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