c++ - 将 deque 或 LIFO 容器转换为 std::vector

标签 c++ c++11 stl

我有以下用例:

  • containerTypeX我在前面插入许多元素的对象
  • containerTypeX之后对象已插入所有内容,containerXType对象需要转换为 std::vector

对于containerTypeX我选择std::deque超过std::vector ,因为据我所知,在 std::vector 的开头插入效率不高。 但现在我必须转换 std::dequestd::vector并且不想像这样将队列中的每个元素单独移动到 vector

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

1)有没有办法直接将我的队列转换为我缺少的 vector ?

2) 我应该使用像 std::stack 这样的 LIFO 容器吗?而不是std::deque因为我只插入一侧?但这会给我带来一个问题,即当转换为 std::vector 时,元素顺序需要颠倒。 ...

相关问题: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

正确。

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()));

哪里qstd::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...

您可以使用反向迭代器进行相同的操作

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/

相关文章:

c++ - STL 列表实现

c++ - cin.get() 后的回车; C++

c++ - 双向链接的线程安全分离

c++ - Q : Template class that takes either a normal type or a template template argument

c++ - stable_partition 如何成为一种自适应算法?

c++ - 是否有一些 STL 函数可以获取两个 C++ vector 的笛卡尔积?

c++ - 游戏网络代码-客户端预测和修正

c++ - 我必须设置 rdbuf 吗

c++ - 检查模板参数是否在同质参数包中出现两次以上

c++ - 是否可以让 std::once_flag 成为成员(非静态成员)