将空范围(相同的迭代器)传递给 STL 算法是否会导致定义的行为?

发布于 2024-08-21 20:30:40 字数 307 浏览 4 评论 0原文

考虑以下问题:

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);

上面的所有 std::fill 用法都会导致定义的行为吗?我能保证 vec 不会被修改吗?我倾向于认为“是”,但我想确保标准允许这种用法。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

温柔戏命师 2024-08-28 20:30:41

尽管我不认为标准中明确禁止它,但我会说不。该标准要求迭代器范围的类型为[first, last),其中包括first以及直到但不包括last的所有内容。为 firstlast 传递相同的值对于此定义没有逻辑意义,因为它既包含又不包含,所以我希望得到未定义的行为后退。

编辑:
清理了我最初的回复,并添加了以下内容:在温习了我的数学区间符号,我发现[x,x)形式的区间被定义为空集。所以我上面的答案是错误的——我不希望得到未定义的行为。

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.

深海少女心 2024-08-28 20:30:40

不,如果不会导致未定义的行为。

该标准在 24.1/7 中定义了空迭代器范围,但没有任何地方表明向 std::fill 算法提供空范围会导致未定义的行为。

这实际上是人们对经过深思熟虑的实施所期望的结果。对于自然处理空范围的算法,对调用者强加检查空范围的要求将是一个严重的设计错误。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文