c++listiteratorlistiterator

C++ iterator to last element of a linked list?


I'd like to get the ::iterator to the last element of the list.

My understanding is that you can get the iterator to the .front() of the list with .begin(), but what about the .back()? As the list boundaries are not inclusive of the final element, .end() would be the iterator past the back() element of the list.

I've tried using .rbegin(), as logically that appears to be just what I want, but it appears to return a reverse_iterator type, which results in a mismatched type for my code.


Solution

  • The algorithm is the same for any bidirectional container:

    #include <list>
    #include <stdexcept>
    #include <iostream>
    #include <vector>
    #include <set>
    
    
    template<typename Container>
    auto iter_to_last(Container&& cont)
    {
        auto last = std::end(cont);
        if (last == std::begin(cont))
        {
            throw std::invalid_argument("container is empty");
        }
        return std::prev(last);
    }
    
    int main()
    {
        auto l = std::list<int> { 1, 2, 3 };
        std::cout << *iter_to_last(l) << std::endl;
        std::cout << *iter_to_last(std::set<int> { 1, 2, 3 }) << std::endl;
        std::cout << *iter_to_last(std::vector<int> { 1, 2, 3 }) << std::endl;
    }
    

    expected output:

    3
    3
    3