Dev Notes

Various Cheat Sheets and Resources by David Egan/Carawebs.

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)
        ret.push_back(line);

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

comments powered by Disqus