std::basic_string::at vs std::basic_string::operator[]
Last Updated :
16 Jun, 2021
std::basic_string::at, std::basic_string::operator[]
Both at() and operator[] can be used to access an element in the string. But there exists one difference between them on how to handle exceptional condition when pos>=size.
- std::basic_string::at throws std::out_of_range if pos >= size().
- std::bsic_string::operator[] throws no exception and produces undefined result.
Below is the C++ implementation showing exception handling property of std::basic_string::at –
CPP
#include <stdexcept>
#include <iostream>
int main()
{
std::string str = "Geeksforgeeks" ;
try
{
std::cout << str.at(13) << "\n" ;
}
catch (std::out_of_range const & error)
{
std::cout << "Exception caught" << "\n" ;
std::cout << error.what() << "\n" ;
}
}
|
Output:
Exception caught
basic_string::at: __n (which is 13) >= this->size() (which is 13)
Below is the C++ implementation showing no bounds checking in std::basic_string::operator[] –
CPP
#include <stdexcept>
#include <iostream>
int main()
{
std::string str = "Geeksforgeeks" ;
try
{
std::cout << str[13] << "\n" ;
}
catch (std::out_of_range const & error)
{
std::cout << "Exception caught" << "\n" ;
std::cout << error.what() << "\n" ;
}
}
|
Output:
Undefined result
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...