简体   繁体   中英

convert deque or LIFO container to std::vector

I have the following use case:

  • containerTypeX object to which I insert many elements at the front
  • After the containerTypeX object has everything inserted, the containerXType object needs to be converted to a std::vector

For containerTypeX I chose std::deque over std::vector , because as far as I know inserting at the begin of a std::vector is not efficient. But now I have to convert the std::deque to a std::vector and do not want to move every single element from the queue to the vector separately like

v.emplace_back(std::move(q.front()));

1) Is there a way to directly convert my queue to a vector that I am missing?

2) Should I use a LIFO container like std::stack instead of std::deque as I am only inserting one one side? But this will leave me the problem that in addition the element ordering needs to be reversed when converted to the std::vector ...

Related Question: How to convert std::queue to std::vector

I chose std::deque over std::vector , because as far as I know inserting at the begin of a std::vector is not efficient

Correct.

1) Is there a way to directly convert my queue to a vector that I am missing?

What about moving element from old container to new std::vector using the std::vector constructor that accept a begin/end couple of iterators and the std::make_move_iterator adapter?

I mean

std::vector<containedType> v(std::make_move_iterator(q.begin()),
                             std::make_move_iterator(q.end()));

where q is the std::deque ?

2) Should I use a LIFO container like std::stack instead of std::deque as I am only inserting one one side? But this will leave me the problem that in addition the element ordering needs to be reversed when converted to the std::vector ...

You can make the same using reverse iterators

std::vector<containedType> v(std::make_move_iterator(s.rbegin()),
                             std::make_move_iterator(s.rend()));

where s is a LIFO container.

But, as suggested in comments, are you sure you need this conversion? If you use a std::vector as LIFO container (so adding element at the end), what about using it reversed with reverse operators?

v.reserve(q.size());
std::move(std::begin(q), std::end(q), std::back_inserter(v));
q.clear();
q.shrink_to_fit();

However, as noted in comments, inserting at the end of v directly and reversing the order of elements (if it is really required) by

std::reverse(std::begin(v), std::end(v));

would be likely more efficient.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM