加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 在`abcd`和`abc`的情况下,`std :: equal`是否取消引用`end(

发布时间:2020-12-16 10:01:03 所属栏目:百科 来源:网络整理
导读:基于 http://en.cppreference.com/w/cpp/algorithm/equal的std :: equal的实现如下: templateclass InputIt1,class InputIt2 bool equal(InputIt1 first1,InputIt1 last1,InputIt2 first2) { for (; first1 != last1; ++first1,++first2) { if (!(*first1 =
基于 http://en.cppreference.com/w/cpp/algorithm/equal的std :: equal的实现如下:

template<class InputIt1,class InputIt2>
    bool equal(InputIt1 first1,InputIt1 last1,InputIt2 first2)
    {
        for (; first1 != last1; ++first1,++first2) {
            if (!(*first1 == *first2)) {
                return false;
            }
        }
        return true;
    }

当我将字符串str1 =“abcd”与字符串str2 =“abc”进行比较时,等于(str1.begin(),str1.end(),str2.begin())按预期返回false.由于abcd是一个字符更长,我想知道上面的实现是否将’d’与* str2.end()进行了比较.看起来是这样,但不是不安全吗? str2.end()可能指向任何东西,它可能是’d’.

解决方法

假设您正在讨论std :: string或std :: wstring,并假设您正在讨论不包含嵌入空值的字符串(如示例中的文字).然后:

由于C 11解除引用end()实际上保证也为非const实例产生null-char值.因此比较在那里停止,因为它与此时的其他字符串的值不同,或者它是最后一个迭代器位置.

C11§21.4.5/ 2
关于std :: basic_string :: operator []

Returns: *(begin() + pos) if pos < size(),otherwise a reference to an object of type T with value charT(); the referenced value shall not be modified.

对于语言律师来说,这里有一个很好的观点,即为operator []定义了空值效应,它是根据除end之外的迭代器定义的,因此原则上的结束迭代器可以是特殊的.

但这显然违背了尽可能提供C字符串语义的意图.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读