Should I check if a vector is empty before I use std::transform

Viewed 174

Would it be a good idea to check if a vector is empty or not before using std::transform and back_inserter or could nothing wrong happen since the vector.begin() will be the same as vector.end() and will not insert nothing in the new vector ?

2 Answers

This is unneeded. If empty() is true, then begin() == end() and transform will become a non-op as it works in the range [begin, end)

All std algorithms are noops on empty containers. The only kind that are an issue is something like std::minmax(std::initializer_list), which requires it be non-empty; it doesn't return an iterator, but instead elements.

(Note that in that case, it takes a list, which is usually right there in {}, so it is usually obvious if it is empty.)

The only reason you'd test for empty prior to calling them should be:

  1. You are about to do many such algorithms in a row on the data.

  2. You want to be able to easily detect, with an assert or a break point or log, being passed an empty container.

  3. There is some difference in how you handle empty data other than "do nothing" (note: this is often, but not always, a sign of a flaw in your design).

Related