开发者

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

开发者 https://www.devze.com 2022-12-20 01:45 出处:网络
Consider the following: std::vector<int> vec(1); // vector has one element std::fill(vec.begin(), vec.b开发者_开发技巧egin(), 42);

Consider the following:

std::vector<int> vec(1); // vector has one element
std::fill(vec.begin(), vec.b开发者_开发技巧egin(), 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.


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号