我在学校学过 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/