我有以下用例:
-
containerTypeX
我在前面插入许多元素的对象 - 在
containerTypeX
之后对象已插入所有内容,containerXType
对象需要转换为std::vector
对于containerTypeX
我选择std::deque
超过std::vector
,因为据我所知,在 std::vector
的开头插入效率不高。
但现在我必须转换 std::deque
到 std::vector
并且不想像这样将队列中的每个元素单独移动到 vector
v.emplace_back(std::move(q.front()));
1)有没有办法直接将我的队列转换为我缺少的 vector ?
2) 我应该使用像 std::stack
这样的 LIFO 容器吗?而不是std::deque
因为我只插入一侧?但这会给我带来一个问题,即当转换为 std::vector
时,元素顺序需要颠倒。 ...
最佳答案
I chose
std::deque
overstd::vector
, because as far as I know inserting at the begin of astd::vector
is not efficient
正确。
1) Is there a way to directly convert my queue to a vector that I am missing?
将元素从旧容器移动到新容器怎么样 std::vector
使用std::vector
接受开始/结束几个迭代器和 std::make_move_iterator
的构造函数适配器?
我是说
std::vector<containedType> v(std::make_move_iterator(q.begin()),
std::make_move_iterator(q.end()));
哪里q
是std::deque
?
2) Should I use a LIFO container like
std::stack
instead ofstd::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 thestd::vector
...
您可以使用反向迭代器进行相同的操作
std::vector<containedType> v(std::make_move_iterator(s.rbegin()),
std::make_move_iterator(s.rend()));
哪里s
是一个 LIFO 容器。
但是,正如评论中所建议的,您确定需要这种转换吗?如果您使用std::vector
作为 LIFO 容器(因此在末尾添加元素),通过反向运算符反向使用它怎么样?
关于c++ - 将 deque 或 LIFO 容器转换为 std::vector,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48824781/