标签:
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 ----------------
标签:
原文地址:http://www.cnblogs.com/davidgu/p/4891990.html