C ++用另一个向量扩展一个向量 [英] C++ extend a vector with another vector

查看:76
本文介绍了C ++用另一个向量扩展一个向量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是C ++领域的C / Python程序员,第一次使用STL。

I'm a C/Python programmer in C++ land working with the STL for the first time.

在Python中,用另一个列表扩展列表使用 .extend 方法:

In Python, extending a list with another list uses the .extend method:

>>> v = [1, 2, 3]
>>> v_prime = [4, 5, 6]
>>> v.extend(v_prime)
>>> print(v)
[1, 2, 3, 4, 5, 6]

我目前使用这种算法方法在C ++中扩展向量:

I currently use this algorithmic approach to extend vectors in C++:

v.resize(v.size() + v_prime.size());
copy(v_prime.begin(), v_prime.end(), v.rbegin());

这是扩展向量的规范方法,还是如果我缺少更简单的方法?

Is this the canonical way of extending vectors, or if there is a simpler way that I'm missing?

推荐答案

来自此处

// reserve() is optional - just to improve performance
v.reserve(v.size() + distance(v_prime.begin(),v_prime.end()));
v.insert(v.end(),v_prime.begin(),v_prime.end());

这篇关于C ++用另一个向量扩展一个向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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