1

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?

quickdraw
  • 247
  • 1
  • 2
  • 12
  • 2
    what 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 Answers1

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