Handling Items in a List Template - C++ STL

C++ examples for STL:list

Description

Handling Items in a List Template

Demo Code

#include <iostream>
#include <list>
#include <string>
using namespace std;

class Duck/*from w w  w  .j  a v  a 2s  .  com*/
{
public:
    string name;
    int weight;
    int length;
};

ostream& operator << (ostream &out, const Duck &duck)
{
    cout << "(" << duck.name;
    cout << "," << duck.weight;
    cout << "," << duck.length;
    cout << ")";
    return out;
}

void DumpDucks(list<Duck> *mylist)
{
    list<Duck>::iterator iter = mylist->begin();

    while (iter != mylist->end())
    {
        cout << *iter << endl;
        iter++;
    }
}

list<Duck>::iterator MoveToPosition(list<Duck> *mylist, int pos)
{
    list<Duck>::iterator res = mylist->begin();

    for (int loop = 1; loop <= pos; loop++)
    {
        res++;
    }

    return res;
}

int main()
{
    list<Duck> Inarow;

    // Push some at the beginning
    Duck d1 = {"J", 20, 15}; // Braces notation!
    Inarow.push_front(d1);

    Duck d2 = {"S", 15, 12};
    Inarow.push_front(d2);

    // Push some at the end
    Duck d3 = {"S", 18, 25};
    Inarow.push_front(d3);

    Duck d4 = {"T", 19, 26};
    Inarow.push_front(d4);

    Duck d5 = {"S", 12, 13};
    Inarow.push_front(d5);

    // Display the ducks
    DumpDucks(&Inarow);

    // Reverse
    Inarow.reverse();
    DumpDucks(&Inarow);

    // Splice
    // Need another list for this
    list<Duck> extras;

    Duck d6 = {"G", 8, 8};
    extras.push_back(d6);

    Duck d7 = {"S", 8, 8};
    extras.push_back(d7);

    Duck d8 = {"O", 8, 8};
    extras.push_back(d8);

    Duck d9 = {"G", 8, 8};
    extras.push_back(d9);

    DumpDucks(&extras);

    list<Duck>::iterator first = MoveToPosition(&extras, 1);

    list<Duck>::iterator last = MoveToPosition(&extras, 3);

    list<Duck>::iterator into = MoveToPosition(&Inarow, 2);

    Inarow.splice(into, extras, first, last);

    DumpDucks(&extras);

    DumpDucks(&Inarow);

    return 0;
}

Result


Related Tutorials