【问题标题】:Unexpected behaviour of c++ string::compare() fnc++ string::compare() fn 的意外行为
【发布时间】:2021-03-16 20:15:29
【问题描述】:

string::compare() 的重载形式之一为

int compare (size_t pos, size_t len, const string& str) const;

现在考虑以下两种情况:

场景 1:

string s1="steven", s2="steve";
cout<<s1.compare(0, 5,s2);

场景 2:

string s1="steven", s2="stevec";
cout<<s1.compare(0, 5,s2);

第一种情况下的 O/P 为 0(预期),但在第二种情况下产生 -1(意外)。 fn 调用转换为 比较 s1 的前 5 个字符和 s2 的那些。那么,输出为什么会受到 s2 的第 6 个字符的影响。有人可以解释一下这种实现背后的原因吗?一个标准库 fn。

【问题讨论】:

    标签: c++ c++11 c++14


    【解决方案1】:

    in cppreference所述:

    1. 将此字符串的 [pos1, pos1+count1) 子字符串与 str 进行比较。如果count1 &gt; size() - pos1 子字符串是[pos1, size())。

    没有提到第二个字符串的大小。这意味着比较整个 string2。所以一切都如预期的那样。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-09-23
      • 2012-01-08
      • 2014-07-19
      • 1970-01-01
      • 1970-01-01
      • 2017-05-19
      • 1970-01-01
      • 2022-12-02
      相关资源
      最近更新 更多