"at"运算符在C++做什么?例如,string.at 或 word.at

What does the "at" operator do in C++? For example, string.at or word.at

本文关键字:at string word 例如 什么 运算符 C++      更新时间:2023-10-16
// Iterate(loop/repetition) over the word
for(int i = 0; i < (int)word.size(); i++ ){
    // Get a character
    char ch = word.at(i);
    // If the character matches the character we're looking for
    if(searchCh == ch){
        // Increment a counter
        counter++; // counter = counter + 1

word.at(i)在操作符中是什么意思,或者"at"操作符在c++中是做什么的?例如:string。At或word.at

你的意思可能是" word.at(i)word[i]有什么不同"?

word.at(i)一般检查i是否在范围内,如果不在则抛出异常。如果i不在范围内,word[i]就是未定义行为。

同样,对于word[word.size()],您可以访问隐式尾随的'' -字节,但对于word.at(word.size()),索引超出了范围。

at()是c++中的成员函数。s.at()返回字符串中i位置的字母。但是如果这个位置是如果不在范围内,则抛出异常