码迷,mamicode.com
首页 > 其他好文 > 详细

STL - 容器 - Forward List

时间:2015-10-19 17:03:21      阅读:178      评论:0      收藏:0      [点我收藏+]

标签:

forward list是一个行为受限的list, 不能走回头路。

它只提供前向迭代器, 而不提供双向迭代器。

eg:

rbegin(), rend(), crbegin(), crend()这些都不提供。

它不提供size()成员函数。

没有指向最末元素的anchor, 因此不提供back(), push_back(), pop_back()。

ForwardListTest.cpp:

#include <forward_list>
#include "../../Core/print.hpp"
#include "ForwardListTest.h"

using namespace std;

void ForwardListTest::findDemo()
{
    forward_list<int> list = { 1, 2, 3, 4, 5, 97, 98, 99 };

    // find the position before the first even element
    auto posBefore = list.before_begin();
    for (auto pos = list.begin(); pos != list.end(); ++pos, ++posBefore) 
    {
        if (*pos % 2 == 0) 
        {
            break;  // element found
        }
    }

    // and insert a new element in front of the first even element
    list.insert_after(posBefore, 42);
    PRINT_ELEMENTS(list);
}

void ForwardListTest::run()
{
    printStart("findDemo()");
    findDemo();
    printEnd("findDemo()");
}

运行结果:

---------------- findDemo(): Run Start ----------------
1 42 2 3 4 5 97 98 99
---------------- findDemo(): Run End ----------------

 

自定义find_before_if操作:

#include "../../Core/findbefore.hpp"

void ForwardListTest::findBeforeDemo()
{
    forward_list<int> list = { 1, 2, 3, 4, 5, 97, 98, 99 };

    // find the position before the first even element
    auto posBefore = find_before_if(list.before_begin(), list.end(), 
        [](int i) {
            return i % 2 == 0;
        });

    // and insert a new element in front of the first even element
    list.insert_after(posBefore, 42);
    PRINT_ELEMENTS(list);
}

void ForwardListTest::run()
{
    printStart("findBeforeDemo()");
    findBeforeDemo();
    printEnd("findBeforeDemo()");
}

运行结果:

---------------- findBeforeDemo(): Run Start ----------------
1 42 2 3 4 5 97 98 99
---------------- findBeforeDemo(): Run End ----------------

 

STL - 容器 - Forward List

标签:

原文地址:http://www.cnblogs.com/davidgu/p/4891990.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!