📜  C++中的std :: basic_string :: at

📅  最后修改于: 2021-05-30 19:30:49             🧑  作者: Mango

返回对指定位置pos处字符的引用。该函数自动检查pos是否是字符串字符的有效位置(即pos是否小于字符串长度),如果不是,则抛出out_of_range异常。

句法:

reference at (size_type pos);
const_reference at (size_type pos) const;
Parameters :
pos - position of the character to return
Return value :
Reference to the requested character
Exceptions :
Throws std::out_of_range if pos >= size().
// CPP program to access a character through
// std::basic_string::at 
#include 
#include 
  
int main()
{
    // String with valid indices from 0 to 2
    std::string str = "abc";
  
    // Printing size of string
    std::cout << "string size = " << str.size() << '\n';
  
    // Accessing out of bounds index
    try 
    {
        str.at(4) = 't';
    }
      
    // If error is generated, it is caught
    catch (std::out_of_range const& error) 
    {
        std::cout << error.what() << '\n';
    }
}

输出:

string size = 3
basic_string::at: __n (which is 4) >= this->size() (which is 3)
要从最佳影片策划和实践问题去学习,检查了C++基础课程为基础,以先进的C++和C++ STL课程基础加上STL。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程”