C++ STL/forward list methods

From Software Engineers Wiki
Jump to: navigation, search

Since forward_list is a singly linked list, its iterator is ForwardIterator and doesn't provide reverse iterator. It has special iterator before_begin() so insert_after() can insert an element to the head.

Construct a singly linked list of integer and print the contents:

void print_int_list(std::forward_list<int> &ilist)
{
        for_each(ilist.begin(), ilist.end(), [](int val){ std::cout << val << " "; });
        std::cout << std::endl;
}

int main(void)
{
        std::forward_list<int> ilist({ 1, 2, 3, 4, 5 });
        print_int_list(ilist);
}

Insert a value to the front.

        ilist.push_front(0);
        print_int_list(ilist);
        ilist.insert_after(ilist.before_begin(), -1);
        print_int_list(ilist);

Retrieve the first element and remove it.

        std::cout << ilist.front() << std::endl;
        ilist.pop_front();
        print_int_list(ilist);

Since this is a singly linked list, and the data structure has a pointer to the head, it doesn't support adding an element to the end of the list.

To remove elements with specific value.

void remove_n_from_int_list(std::forward_list<int> &ilist, int to_remove)
{
        ilist.remove_if([=](int value){ return value == to_remove; });
}

        ilist.remove(1);
        remove_n_from_int_list(ilist, 4);
        print_int_list(ilist);

To erase specific node, it is required to have an iterator to point to the node in front. To erase the element with value '3' which is after '2'.

        auto ir = std::find(ilist.begin(), ilist.end(), 2);
        ilist.erase_after(ir);
        print_int_list(ilist);
Personal tools
Namespaces

Variants
Actions
Navigation
Toolbox