[C++][list][双向链表]

2020-06-19  本文已影响0人  NO_OcaNE

双向链表list V.S. 链表forward_list

共性

都是便于插入、删除,但是查找需要O(n)的时间。比较适合在排序算法里

差别

list 双向链表,
forward_list 单向链表,更小,更高效

使用方式

construct 新建,空的,复制型的,从列表初始化型的

// constructing lists
#include <iostream>
#include <list>

int main()
{
    // constructors used in the same order as described above:
    std::list<int> first;                                // empty list of ints
    std::list<int> second(4, 100);                       // four ints with value 100
    std::list<int> third(second.begin(), second.end());  // iterating through second
    std::list<int> fourth(third);                       // a copy of third

    // the iterator constructor can also be used to construct from arrays:
    int myints[] = { 16,2,77,29 };
    std::list<int> fifth(myints, myints + sizeof(myints) / sizeof(int));

    std::cout << "The contents of fifth are: ";
    for (std::list<int>::iterator it = fifth.begin(); it != fifth.end(); it++)
        std::cout << *it << ' ';

    std::cout << '\n';

    return 0;
}

list<int> list_(3) 表示建立三个0 的list

.erase()的用法

.erase(list<int>::iterator it1) 一个参数时,是删除该指针现在指向的元素
.erase(list<int>::iterator it1,it2) 两个参数时,是删除之阵中中间段,左闭右开,[ it1, it2)
【注】advance(it2, 5) 指 指针 往前移5位 即 it2 += 5;

#include <iostream>
#include <list>

int main()
{
    std::list<int> mylist;
    std::list<int>::iterator it1, it2;
    // set some values:
    for (int i = 1; i < 10; ++i) mylist.push_back(i * 10);
                                // 10 20 30 40 50 60 70 80 90
    it1 = it2 = mylist.begin(); // ^^
    advance(it2, 6);            // ^                 ^
    ++it1;                      //    ^              ^

    it1 = mylist.erase(it1);   // 10 30 40 50 60 70 80 90
                                //    ^           ^

    it2 = mylist.erase(it2);   // 10 30 40 50 60 80 90
                                //    ^           ^

    ++it1;                      //       ^        ^
    --it2;                      //       ^     ^

    mylist.erase(it1, it2);     // 10 30 60 80 90
                                //        ^

    std::cout << "mylist contains:";
    for (it1 = mylist.begin(); it1 != mylist.end(); ++it1)
        std::cout << ' ' << *it1;
    std::cout << '\n';

    return 0;
}
上一篇 下一篇

猜你喜欢

热点阅读