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