std :: basic_string :: at,std :: basic_string ::运算符[]
at()和运算符[]均可用于访问字符串的元素。但是,当pos> = size时,如何处理异常条件之间存在一个区别。
- 如果pos> = size(),则std :: basic_string :: at抛出std :: out_of_range 。
- std :: bsic_string :: 运算符[]不引发异常,并产生未定义的结果。
下面是显示std :: basic_string :: at的异常处理属性的C++实现–
// C++ implementation of std::basic_string::at
#include
#include
int main()
{
// Length = 13. Valid indices are from '0' to '12'
std::string str = "Geeksforgeeks";
// Accessing an out of bounds
try
{
// Throwing an out_of_range exception
std::cout << str.at(13) << "\n";
}
// Error caught
catch (std::out_of_range const& error)
{
std::cout << "Exception caught" << "\n";
// Printing the type of exception
std::cout << error.what() << "\n";
}
}
输出:
Exception caught
basic_string::at: __n (which is 13) >= this->size() (which is 13)
以下是C++实现,显示std :: basic_string ::运算符[]中没有边界检查–
// C++ implementation of std::basic_string::operator[]
#include
#include
int main()
{
// Length = 13. Valid indices are from '0' to '12'
std::string str = "Geeksforgeeks";
// Accessing an out of bounds
try
{
//Throwing an out_of_range exception
std::cout << str[13] << "\n";
}
// Error caught
catch (std::out_of_range const& error)
{
std::cout << "Exception caught" << "\n";
// Printing the type of exception
std::cout << error.what() << "\n";
}
}
输出:
Undefined result
要从最佳影片策划和实践问题去学习,检查了C++基础课程为基础,以先进的C++和C++ STL课程基础加上STL。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程” 。