Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does passing an empty range (identical iterators) to an STL algorithm result in defined behavior?

Tags:

c++

iterator

stl

Consider the following:

std::vector<int> vec(1); // vector has one element
std::fill(vec.begin(), vec.begin(), 42);
std::fill(vec.begin()+1, vec.end(), 43);
std::fill(vec.end(), vec.end(), 44);

Will all of the std::fill usages above result in defined behavior? Am I guaranteed that vec will remain unmodified? I'm inclined to think "yes", but I want to make sure the standard allows such usage.

like image 337
Emile Cormier Avatar asked Feb 16 '10 01:02

Emile Cormier


2 Answers

No, if doesn't cause undefined behavior.

The standard defines empty iterator range in 24.1/7 and nowhere it says that supplying an empty range to std::fill algorithm causes undefined behavior.

This is actually what one would expect from a well-thought through implementation. With algorithms that handle emtpy range naturally, imposing the requirement to check for empty range on the caller would be a serious design error.

like image 159
AnT Avatar answered Oct 02 '22 18:10

AnT


Although I don't believe it's specifically forbidden in the standard, I would say no. The standard requires that iterator ranges be of type [first, last) which includes first and everything up to but not including last. Passing in the same value for first and last doesn't make logical sense with this definition as it would be both included and not included, so I would expect to get undefined behavior back.

EDIT: Cleaned up my initial response, and adding this: after brushing up on my mathematical interval notation, I've discovered that an interval of the form [x,x) is defined as the empty set. So my above answer is wrong -- I would NOT expect to get undefined behavior.

like image 32
JonM Avatar answered Oct 02 '22 19:10

JonM