如何自我复制一个矢量? [英] How to self-copy a vector?

查看:159
本文介绍了如何自我复制一个矢量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个向量< string> 包含a和b,我想复制自己2次,使矢量现在包含a code>和 push_back

解决方案

  myvec.reserve(myvec.size()* 3); //保存不仅速度增加它也保护我们ftom迭代器无效
vector< string> :: iterator it = myvec.end(); //我们蚂蚁添加两次原始到结束,所以我们保存结束的原始结束
myvec.insert(myvec.end(),myvec.begin(),it);
myvec.insert(myvec.end(),myvec.begin(),it);

感谢Emilio Garavaglia首先指出这个问题,看到这里有很多问题的原因: std :: vector :: insert()如果向量有足够的空间(通过预留创建),则无效迭代器?



第二次尝试:

  std :: size_t size = myvec.size(); 
myvec.resize(size * 3); // resize必须保护我们免于迭代器无效
vector< string> :: iterator it = myvec.begin()+ size;
std :: copy(myvec.begin(),it,it);
std :: copy(myvec.begin(),it,it + size);

因为没有实现将实现std :: string whos默认构造函数分配堆上的东西



另一个堆访问最小化是将向量复制到另一个插入它然后在原件中移动,我偷了Emilio Garavaglia代码和pimped:

  {
vector< string& m = {a,b};
auto n = m; //保持初始值安全
m.reserve(3 * m.size()); // preallocate,避免连续分配
m.insert(m.end,n.begin(),n.end());
std :: for_each(n.begin(),n.end(),[& n](std :: string& in){n.emplace_back );
}


Let's say I have a vector<string> containing "a" and "b", I wanna copy itself 2 times so that the vector now contains "a", "b", "a", "b", "a", "b"

What is a better approach than using for and push_back?

解决方案

My initial thought:

myvec.reserve(myvec.size()*3);  //reserve not only speeds things upt it also protects us ftom iterator invalidation
vector<string>::iterator it = myvec.end();    //we ant to add two times the origional onto the end so we save the end of the origional end
myvec.insert(myvec.end(), myvec.begin(), it);
myvec.insert(myvec.end(), myvec.begin(), it);

thanks to Emilio Garavaglia for first pointing out problems with this, see here many reasons why this has problems: Does std::vector::insert() invalidate iterators if the vector has enough room (created through reserve)?

Second try:

std::size_t size = myvec.size();
myvec.resize(size*3);  //resize must protects us from iterator invalidation
vector<string>::iterator it = myvec.begin()+size;
std::copy(myvec.begin(),it,it);
std::copy(myvec.begin(),it,it+size);

since no implementation is going to implement a std::string whos default constructor allocates something on the heap this should cause less heap access and therefore be faster than others examples.

Another heap access minimization is to copy the vector into another insert it and then move in the originals, I stole Emilio Garavaglia code and pimped it:

{
vector<string> m = { "a", "b" };
auto n = m; // keep initial value safe
m.reserve(3 * m.size()); // preallocate, to avoid consecutive allocations
m.insert(m.end, n.begin(), n.end());
std::for_each(n.begin(),n.end(),[&n](std::string &in){n.emplace_back(std::move(in));});
}

这篇关于如何自我复制一个矢量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆