简体   繁体   English

将std :: vector移动到C ++ 11中的std :: deque

[英]Move std::vector to std::deque in C++11

If I have std::deque and std::vector and want to combine them to std::deque , I can do it the following way: 如果我有std::dequestd::vector并希望将它们组合到std::deque ,我可以通过以下方式实现:

typedef int T; // type int will serve just for illustration
std::deque< T > deq(100); // just some random size here
std::vector< T > vec(50);
// ... doing some filling ...
// now moving vector to the end of queue:
deq.insert( 
    deq.end(), 
    std::make_move_iterator( vec.begin() ),
    std::make_move_iterator( vec.end() )
);
std::cout << deq.size() << std::endl;

We know the size of the vector but we can't reserve memory at the end of std::deque before using std::deque.insert(...) . 我们知道向量的大小但是在使用std::deque.insert(...)之前我们不能在std::deque的末尾保留内存。 So is it the fastest way to move all elements of std::vector to the end of std::deque ? 那么它是将std::vector所有元素移动到std::deque末尾的最快方法吗? Or did I miss something? 还是我错过了什么?

Thank you. 谢谢。

I would use resize method as follows, because than is deque reallocated only once: 我会使用如下resize方法,因为只有deque重新分配一次:

size_t oldSize = deq.size();
deq.resize(deq.size() + vec.size());
copy(vec.begin(), vec.end(), deq.begin() + oldSize);

try this: 试试这个:

using T = int; // type int will serve just for illustration

std::deque< T > deq(100); // just some random size
std::vector< T > vec(50);
// ... doing some filling ...
// now moving vector to the end of queue:
std::move( 
    begin(vec),
    end(vec),
    back_inserter(deq)
);
std::cout << deq.size() << std::endl;

Keep in mind that this still copies the vector to the end of the deq . 请记住,这仍然deq vector复制到deq It just applies std::move on each element of vec to the end of deq . 它只是将vec每个元素上的std::move应用到deq As long as T is just an int this is not much different than copying the vector to the end of deq . 只要T只是一个int这与将向量复制到deq的末尾deq

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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