一、题意
输入若干行字符串。表示键盘输入的字符序列。
其中'['表示光标移至开头,']'表示把光标移至末尾。
要求输出最终的字符串。
二、解析
需要插入操作,因此考虑用list。移动光标通过维护list的一个迭代器即可,用来表示插入的位置。
三、代码
#include <iostream> #include <string> #include <list> using namespace std; int main() { string str; while(cin >> str) { list<char> lst; auto pos = lst.end(); for(char ch : str) { if(ch == '[') pos = lst.begin(); else if(ch == ']') pos = lst.end(); else pos = lst.insert(pos, ch), pos ++; } for(char ch : lst) cout << ch; cout << endl; } }
四、归纳
- 这题主要是复习一下list的使用,当需要频繁操作时就用list
- pos = lst.insert(pos, x)表示将x插入到lst的pos迭代器位置,返回值pos表示的是新插入字符的迭代器位置。lst.insert(lst.begin(), x)是在开头插入;lst.insert(lst.end(), x)是在末尾插入。