2008년 1월 3일 목요일

list::insert, list::erase

STL가 제공하는 list에 insert, erase는 각각 iterator를 반환한다. (형태에 따라 반환하지 않는 것도 있으니 주의)
  • iterator insert(iterator pos, const T& x) : pos 앞쪽에 x를 넣고, x에 대한 iterator를 반환한다.
  • iterator erase(iterator pos) : pos에 해당하는 아이템을 삭제하고, pos 다음 iterator를 반환한다.
예)
#include <iostream>
#include <list>
#include <set>
#include <algorithm>
using namespace std;

typedef list<int> list_int;
typedef list_int::iterator list_itr;

class print
{
public:
    ostream& m_os;
    print(ostream& os) : m_os(os) {}
    void operator() (int v) { m_os << v << ' '; }
};

template<typename _T>
ostream&
dump(ostream& os, const _T& cont)
{
    for_each(cont.begin(), cont.end(), print(os));
    os << endl;
    return os;
}

list_int&
init(list_int& cont)
{
    cont.clear();
    for ( int i(0); i < 10; i++ )
    {
        cont.push_back(i);
    }
    return cont;
}

template<typename _IteratorType>
void
testInsert(_IteratorType ib, _IteratorType ie, list_int& cont)
{
    _IteratorType itr, itr2;
    cout << "TYPE: " << typeid(_IteratorType).name() << endl;
    cout << "OPER: " << "ERASE" << endl;
    cout << "LIST: "; dump(cout,cont);
    itr = find(ib,ie,5);
    cout << "SLCT: " << *itr << endl;
    itr2 = cont.insert(itr,100);
    cout << "RSLT: " << *itr2 << endl;
    cout << "RLST: "; dump(cout,cont);
}

template<typename _IteratorType>
void
testErase(_IteratorType ib, _IteratorType ie, list_int& cont)
{
    _IteratorType itr, itr2;
    cout << "TYPE: " << typeid(_IteratorType).name() << endl;
    cout << "OPER: " << "INSERT" << endl;
    cout << "LIST: "; dump(cout,cont);
    itr = find(ib,ie,5);
    cout << "SLCT: " << *itr << endl;
    itr2 = cont.erase(itr);
    cout << "RSLT: " << *itr2 << endl;
    cout << "RLST: "; dump(cout,cont);
}

int
main(int argc, char* argv[])
{
    list_int cont;
    init(cont);
    testInsert(cont.begin(),cont.end(),cont);
    init(cont);
    testErase(cont.begin(),cont.end(),cont);

    return 0;
}


결과)
TYPE: St14_List_iteratorIiE
OPER: ERASE
LIST: 0 1 2 3 4 5 6 7 8 9
SLCT: 5
RSLT: 100
RLST: 0 1 2 3 4 100 5 6 7 8 9
TYPE: St14_List_iteratorIiE
OPER: INSERT
LIST: 0 1 2 3 4 5 6 7 8 9
SLCT: 5
RSLT: 6
RLST: 0 1 2 3 4 6 7 8 9


Powered by ScribeFire.