【问题标题】:C++ Primer: why string constructor(s, pos) exception is "pos > s.size()" and not "pos >= s.size()"?C++ 入门:为什么字符串构造函数 (s, pos) 异常是 \"pos > s.size()\" 而不是 \"pos >= s.size()\"?
【发布时间】:2023-02-08 03:44:46
【问题描述】:

示例如下:

string s1 = "abcde";
string s2(s1, s1.size()); // s1.size() = 5.

请注意 s1.size() = 5 并且最后允许的索引 = 4(对于字符“e”)。以上运行正常返回空字符串。只有当 pos = 6 时,它才会因异常​​超出范围而失败。为什么?

根据 cppereference 网站:

例外情况
3) std::out_of_range 如果 pos > other.size()

正确的异常不应该是“if pos >= other.size()?
谢谢你的帮助。

【问题讨论】:

  • std::string 现在需要有一个空终止符。
  • 嗯从什么时候开始?我想如果 s 是 C 字符数组那么是的。
  • See this。但正如答案所述,在该位置写除 0 以外的任何内容很可能会搞乱 std::string 将如何连接、删除等。

标签: c++ c++20


【解决方案1】:

自 C++11 起,s1[s1.size()] 需要工作并将返回对 ' 的引用

猜你喜欢
  • 2012-01-27
  • 2012-08-02
  • 2013-09-23
  • 1970-01-01
  • 1970-01-01
  • 2012-05-10
  • 1970-01-01
  • 2011-08-15
  • 1970-01-01
相关资源
最近更新 更多