Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save scraimer/6cfb9db1725fe38cb641a7c340528989 to your computer and use it in GitHub Desktop.
Save scraimer/6cfb9db1725fe38cb641a7c340528989 to your computer and use it in GitHub Desktop.
Using std::copy and std::back_inserter to copy between vectors of different types
/*
* By adding a converting constructor to `person` (that converts from `thingy` to `person`)
* we can allow the std::back_inserter to work when copying from vector<thingy> to vector<person>
*
* This allows a one-liner that calls `push_back` over and over.
*
* Note: The repeated calls to `push_back` might have a performance cost.
* The alternative is to do it in two lines:
*
* people.reserve(N);
* copy(ids.begin(), ids.end(), people.begin());
*
* By calling `reserve` first, we pre-allocate in one go. It avoids repeated reallocations
* (and copies of old data to new memory). And the simpler `copy` can rely on all the
* locations in the vector already having been allocated.
*
* Note #2: Maybe use std::transform instead of std::copy, and implement the conversion
* using lambda or a function-object.
* [See https://stackoverflow.com/a/11686976/54491]
*/
#include <algorithm>
#include <vector>
#include <iterator>
struct thingy
{
int _id;
};
struct person
{
// This non-explicit converting constructor allows std::back_inserter
// to insert from a vector of 'thingy' to a vector of 'person'
person( thingy const & src )
{
_id = src._id;
}
int _id;
};
int main()
{
std::vector<thingy> ids;
ids.reserve(2);
ids.push_back(thingy{11});
ids.push_back(thingy{22});
std::vector<person> people;
copy( ids.begin(), ids.end(), back_inserter( people ) );
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment