c++ - string::at 和 string::operator[] 有什么区别?

标签 c++ string

我在学校学过 string::at,但通过探索字符串库,我看到了 string::operator[],这是我以前从未见过的。

我现在正在使用 operator[] 并且从那以后就没有使用过 at,但是有什么区别呢? 这是一些示例代码:

std::string foo = "my redundant string has some text";
std::cout << foo[5];
std::cout << foo.at(5);

它们在输出方面基本相同,但是否存在一些我不知道的细微差别?

最佳答案

是的,有一个主要区别:使用 .at()operator[] 时对传递的索引进行范围检查,如果超出字符串的末尾则抛出异常在那种情况下只会带来未定义的行为

关于c++ - string::at 和 string::operator[] 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14699060/

相关文章:

C++ 输出错误的字母

c++ - 使用宏的编译时条件类型操作

c++ - 将 char* 与字符串宏进行比较

c# - 如何从字符串中获取数字

c++ - 即使在向其添加新成员后,结构大小也保持不变

C++ 更新结构

c - 如何连接子字符串以形成更大的字符串

c++ - 如何为用户定义的类型构造散列函数?

c++ - IContextMenu::QueryContextMenu 被调用,但 IContextMenu::InvokeCommand 没有

c++ - cout 和 printf 的 pow 函数输出不同?