Dev Notes

Software Development Resources by David Egan.

Combine Vectors in C++

C++, Containers, Vectors
David Egan

Build a combined vector from two input vectors.

There are a number of ways to achieve this - the function below outlines some options:

using std::string;
using std::vector;

 * Accept two vectors of strings as input parameters.
 * Pass these in by reference for efficiency, and as `const` to protect the originals.
vector<string> vcat(const vector<string>& top, const vector<string>& bottom)
    vector<string> ret = top;

    // Option 1: insert()
    ret.insert(ret.end(), bottom.begin(), bottom.end());

    // Option 2: C++ 11 range-based for-loop
    for(const string& line : bottom)

    // Option 3: Loop through the extra collection using an iterator
    for(vector<string>::const_iterator it = bottom.begin(); it != bottom.end(); ++it) {
    return ret;

comments powered by Disqus