Open In App

std::basic_string::at vs std::basic_string::operator[]

Last Updated : 16 Jun, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

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




// C++ implementation of std::basic_string::at
#include <stdexcept>
#include <iostream>
 
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";
    }
}


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




// C++ implementation of std::basic_string::operator[]
#include <stdexcept>
#include <iostream>
 
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";
    }
}


Output: 
 

Undefined result

 



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads