加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 是否可以使用数组副本复制部分向量?

发布时间:2020-12-16 10:33:56 所属栏目:百科 来源:网络整理
导读:How do you copy the contents of an array to a std::vector in C++ without looping?有一个很好的例子,如何简单地将数组的内容复制到向量中. 你能用同样的技术将一部分矢量复制到另一个矢量吗? 例如 vectorint v;// ...v has some number of elements and
How do you copy the contents of an array to a std::vector in C++ without looping?有一个很好的例子,如何简单地将数组的内容复制到向量中.

你能用同样的技术将一部分矢量复制到另一个矢量吗?

例如

vector<int> v;

// ...v has some number of elements and we're interested in an 
// arbitrary number (y) from an arbitrary start point (x)...

vector<int> v2(&v[x],&v[x + y]);

解决方法

是的,使用迭代器:

vector<int> v2(v.begin() + x,v.begin() + x + y);

如果您愿意,可以使它更通用:

vector<int> v2(std::next(std::begin(v),x),std::next(std::begin(v),x + y));

指针版本(数组衰减为两个参数)的原因在于,指针可以被视为随机访问迭代器.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读