本文介绍了string :: at和string :: operator []有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I was taught string::at in school, but by exploring the string library I saw string::operator[], which I was never shown before.

我现在正在使用 operator [] 并没有t以来一直在使用,但是有什么区别?
这是一些示例代码:

I'm now using operator[] and haven't used at since, but what is the difference?Here is some sample code:

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

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

They are essentially the same in terms of output, but are there some subtle differences I'm not aware of?

推荐答案

是的,有一个主要区别:使用对通过的索引进行范围检查,如果索引在在这种情况下只会带来未定义的行为

Yes, there is one major difference: using .at() does a range check on index passed and throws an exception if it's over the end of the string while operator[] just brings undefined behavior in that situation.

这篇关于string :: at和string :: operator []有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-13 12:46