STL forward_list容器成员函数

2020-05-10  本文已影响0人  coolTigers

通过示例学习单向链表的几个函数

#include "monotonicallyStack.h"
#include<iostream>
#include <vector>
#include <forward_list>
using namespace std;

int main()
{
    forward_list<std::string> my_words{ "three","six","eight" };
    auto count = std::distance(std::begin(my_words), std::end(my_words));
    cout << count << endl; // 3
    cout << "====================" << endl;

    std::forward_list<int> data{ 10,21,43,87,175,351 };
    auto iter = std::begin(data);
    size_t n{ 3 };
    std::advance(iter, n);
    cout << "The " << n + 1 << "th element is " << *iter << endl; // 87
    cout << "====================" << endl;

    forward_list<string> your_words{"seven", "four", "nine"};
    my_words.splice_after(my_words.before_begin(), your_words);
    cout << "your_words: " << endl;
    for (auto iter : your_words)
    {
        cout << iter << endl;
    }
    cout << "my_words: " << endl;
    for (auto iter : my_words)
    {
        cout << iter << endl;
    }
    cout << "====================" << endl;

    forward_list<int> iflst= { 1,2,3,4,5,6 };

    auto pre = iflst.before_begin();
    auto curr = iflst.begin();

    while (curr != iflst.end()) {
        if (*curr & 1) {
            curr = iflst.erase_after(pre);
        } else {
            pre = curr;
            ++curr;
        }
    }

    for (auto iter : iflst) {
        cout << iter << endl;
    }
    return 0;
}

打印结果如下:


image.png
上一篇 下一篇

猜你喜欢

热点阅读