Is there a container in C++ I could use to add elements in both ends, not just back or just front, but would like to add in either end. And similarly remove elements from any end, not from just one. Maybe in STLs or Boost?
Asked
Active
Viewed 245 times
1
-
2what about `std::list`? – JFMR Dec 13 '17 at 16:28
-
That would work perfectly! Thanks! – quickdraw Dec 13 '17 at 16:29
-
4`std::deque`? If you need random access (say `at()` and/or `operator[]`) I suggest `std::deque`; otherwise I suppose `std::list` is a good choice. – max66 Dec 13 '17 at 16:35
-
Sure there are a few that support this. Have a look at the STL flowchart in the answer to this question https://stackoverflow.com/questions/471432/in-which-scenario-do-i-use-a-particular-stl-container – Justin Randall Dec 13 '17 at 16:48
-
@JustinRandall - nice flowchart; do you know something similar that support also C++11 containers (arrays, forward lists and unordered*)? – max66 Dec 13 '17 at 16:57
-
1@max66 yes scroll further down past the accepted answer and you will see an updated flowchart for C++11. – Justin Randall Dec 13 '17 at 17:06
-
1@JustinRandall - Never stop at the first answer :( ! Thanks. – max66 Dec 13 '17 at 17:14
1 Answers
0
You can portably add an element x
to the front of a sequence container (vector
/deque
/list
) via v.insert(v.begin(), x)
. However, for vector
this is an O(n) operation (this is why vector
does not have a convenient push_front
operation) and it relocates all the existing elements. If you don't want existing elements to be relocated, deque
or list
may be a better fit.

Nevin
- 4,595
- 18
- 24
-
1Please don't idly suggest `list`; `list` is a very special purpose container who is almost always a bad idea. – Yakk - Adam Nevraumont Dec 13 '17 at 19:03