Here is a function which intends to:
a) accept a vector of int
b) for each int in the input vector, append the inverse of this int
preconditions: none
postconditions: returned vector's size() is exacly 2 * the input vector's size.
Note that the vector is modified in-place.
Question:
Is this function strictly defined behaviour vis-a-vis iterator invalidation during the transform?
Bonus:
Is there a better/more succinct/robust way to write it?
Code:
std::vector<int> append_negatives(std::vector<int> v)
{
v.reserve(v.size() * 2);
std::transform(begin(v), end(v),
back_inserter(v),
[](auto&& x) { return -x; });
return v;
}
Aucun commentaire:
Enregistrer un commentaire