list
Theory and problem statement
Machine translation, not yet reviewed by a native speaker.
std::list is a doubly linked list: each item stores pointers to its neighbours. Inserting or removing an item
anywhere is O(1) if you have an iterator to that place; there's no l[i] access.
#include <list>
std::list<std::string> q = {"a", "b", "c"};
q.push_front("z"); // to the front
auto it = std::next(q.begin(), 2); // an iterator to the 3rd item
q.insert(it, "x"); // insert before it
q.remove("b"); // remove all "b"s
q.reverse(); q.sort(); // its own versions of the algorithms
In practice vector is almost always faster because of the processor cache (the items are next to each other in memory). list is needed
when there are many insertions and removals in the middle at a position you've already found, and the iterators must keep working.
Task. A single-line text editor with a cursor. The starting text is the first word, and the cursor is at its end. Then come commands:
L (cursor left), R (right), D (delete the character to the left of the cursor), I c (insert the character c before the cursor).
Print the final text. Use a std::list<char> and an iterator as the cursor.
Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.