如何使用std::forward_list 查找插入數據

//
//  Forward_list.hpp
//  練習
//
//  Created by hanzhiqiang on 2017/6/11.
//  Copyright © 2017年 hanzhiqiang. All rights reserved.
//

#ifndef Forward_list_hpp
#define Forward_list_hpp

#include <stdio.h>
#include <iostream>
#include <forward_list>

using namespace std;

int main()
{
    forward_list<string> mList;
    mList.emplace_front("aaa");
    mList.emplace_front("bbb");
    mList.emplace_front("ccc");
    
    for (auto it = mList.begin(); it != mList.end(); it++)
    {
        cout<<*it<<endl;
    }
    
//    for (auto it = mList.before_begin(); it != mList.end(); it++)
//    {
//        cout<<*it<<endl;
//    }
    
//    auto itList = find(mList.begin(), mList.end(), "fff");
//    if (itList != mList.end()) \
//    {
//        mList.emplace_after(itList, "111");
//    }
//    else
//    {
//        mList.insert_after(mList.end(),"222");//c++ primer p 313 向末尾插入數據結果未知  error
//    }
    
    auto prev = mList.before_begin();
    auto curr = mList.begin();
    bool isInsert = false;
    while (curr != mList.end())
    {
        if (*curr == "fff")
        {
            curr = mList.insert_after(curr, "111");
            isInsert = true;
        }
        prev = curr;
        curr++;
    }
    
    if(!isInsert)
    {
        curr = mList.insert_after(prev, "222");//向末尾插入數據成功
    }
    
    for (auto it = mList.begin(); it != mList.end(); it++)
    {
        cout<<"插入元素後"<<*it<<endl;
    }
    
    cout<<"fuck"<<endl;
    return 0;
}

#endif /* Forward_list_hpp */
相關文章
相關標籤/搜索