C++ STL/list methods

From Software Engineers Wiki
Jump to: navigation, search

std::list is a doubly linked list. Its iterator is BidirectionalIterator.

#include <iostream>
#include <algorithm>
#include <initializer_list>
#include <list>

template <typename T> class CIntDList : public std::list<T> {
public:
        CIntDList() {}
        CIntDList(const std::initializer_list<T> &il) : std::list<T>(il) {}

        typename std::list<T>::iterator begin(void) { return std::list<T>::begin(); }
        typename std::list<T>::iterator end(void) { return std::list<T>::end(); }
        typename std::list<T>::reverse_iterator rbegin(void) { return std::list<T>::rbegin(); }
        typename std::list<T>::reverse_iterator rend(void) { return std::list<T>::rend(); }

        void print(void) {
                for_each(begin(), end(), [](T ir){ std::cout << ir << " "; });
                std::cout << std::endl;
        }
        void print_reverse(void) {
                for_each(rbegin(), rend(), [](T ir){ std::cout << ir << " "; });
                std::cout << std::endl;
        }
};

int main(void)
{
        CIntDList<int> idlist { { 7, 3, 0, 6, 2, 7, 11, 27, 36, 45, 56, 61, 78 } };

        idlist.print();
        idlist.print_reverse();
}

For traversing the list, following allows user defined callback function using functional.

template <typename T> class CIntDList : public std::list<T> {
        void traverse(std::function<void (T)> fn) {
                typename std::list<T>::iterator ir;

                for (ir = begin(); ir != end(); ++ir) 
                        fn(*ir);
        }
        void traverse_reverse(std::function<void (T)> fn) {
                for_each(rbegin(), rend(), fn);
        }
}

int main(void)
{
        int order = 0;
        idlist.traverse([&order](int irv){ if (irv == 7) std::cout << "Found 7 at order " << order << std::endl; ++order; });

        order = 0;
        idlist.traverse_reverse([&order](int irv){ if (irv == 7) std::cout << "Found 7 at reverse order " << order << std::endl; ++order; });
}

It allows adding elements to both ends.

        idlist.emplace_front(-1);
        idlist.emplace_back(99);
        idlist.print();

It also can be sorted.

        idlist.sort();
        idlist.print();

Also elements can be removed from both ends.

        idlist.pop_front();
        idlist.pop_back();
        idlist.print();

pop_front() is same as erase(begin());

        idlist.erase(idlist.begin());
        auto ir_end = idlist.end();
        --ir_end;
        idlist.erase(ir_end);
        idlist.print();
Personal tools
Namespaces

Variants
Actions
Navigation
Toolbox