views:

1253

answers:

3

I'm a C/Python programmer in C++ land, really working with the STL for the first time. In Python, extending a list with another list uses the list's extend method:

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

In C++, I'm currently using this algorithmic approach for vector extension:

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

I just want to find out if this was the canonical way of doing vector extension or if there is a simpler way that I'm missing.

+16  A: 

From here

// 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());
Dmitry Khalatov
I don't think there's a specialization of vector::insert for random access input iterators, so if performance matters, reserve() first.
Greg Rogers
Both VC++ 9.0 and GCC 4.3.2 determine iterator category internally, so you don't need to reserve.
Vadim Ferderer
+14  A: 
copy(v_prime.begin(), v_prime.end(), back_inserter(v));
CTT
I think space still has to be reserve()-d to improve performance
Dmitry Khalatov
+1, since the questioner asked for "simplest", not "fastest", so reserving space (while worth mentioning as an option) is unnecessary.
Steve Jessop
i think dmitry solution is both simplier and faster. upvote for this guy anway :)
Johannes Schaub - litb
This answer should be discouraged. See Effective STL, Item 5: Too many STL programmers overuse `copy`, so the advice I just gave bears repeating: Almost all uses of `copy` where the destination range is specified using an insert iterator should be replaced with calls to range member functions.
Chris Jester-Young
@Chris, thus defeating the architecture of the STL.
Frank Krueger
A: 

i could be wrong but you might try "vectorC = vectorA + vectorB". I know this works with stl strings and i'm to lazy to try it/check it works with vectors but hey try it and sorry if it doesn't

Nope, std::vector does not implement an operator+. That's not to say you can't implement one, though! (The beauty of C++ is that operator overloading can be done as free functions. :-P)
Chris Jester-Young