蒼い夏の空のライブラリー

ブログ名は適当に考えました  このブログの記事のすべてはCC0、パブリックドメインです

std::string を空白で分割する

std::sregex_token_iterator を使う

例として、

双方向連結リスト | アルゴリズムとデータ構造 | Aizu Online Judge

をやった

#include <iostream>
#include <list>
#include <string>
#include <regex>
#include <algorithm>

class my_list : public std::list<int>
{
    std::regex m_separator{" "}; // 分割用のセパレータ
public:
    using std::list<int>::list; // std::listのコンストラクタ群のmy_listでの暗黙定義
    void accept_command(const std::string & line)
    {
        // セパレータで入力を分割し、イテレータ it で参照できるようにしています
        auto && it = std::sregex_token_iterator(std::begin(line), std::end(line), m_separator, -1);

        // コマンドを command に入れています
        const std::string & command = *it;

        if (command == "insert")
        {
            // コマンドの数字を num に入れています
            auto && num = std::stoi(*std::next(it));
            emplace_back(num);
        }

        else if (command == "delete")
        {
            auto && num = std::stoi(*std::next(it));
            erase(std::find_if(begin(), end(),
                [&num](auto && tmp) {return tmp == num; }));
        }

        else if (command == "deleteFirst") pop_front();

        else if (command == "deleteLast") pop_back();

        else std::cout << "コマンド名をチェックしてください";
    }
};

template<typename T>
void show(T && tmp)
{
    for (auto && i = tmp.rbegin(); i != tmp.rend(); ++i)
    {
        std::cout << *i;
        if (i != std::prev(tmp.rend())) std::cout << " ";
    }
}

int main()
{
    std::string s;
    std::getline(std::cin, s);

    const int & line_num = stoi(s);

    my_list m;
    for (auto i = 0; i < line_num; ++i) 
    {
        std::getline(std::cin, s);
        m.accept_command(s);
    }

    show(m);
}