Related Articles

Related Articles

std::basic_string::at vs std::basic_string::operator[]
  • Difficulty Level : Hard
  • Last Updated : 17 Jul, 2017

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 hadle 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 –

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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";
    }
}

chevron_right


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[] –



filter_none

edit
close

play_arrow

link
brightness_4
code

// 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";
    }
}

chevron_right


Output:

Undefined result

This article is contributed by Rohit Thapliyal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

Attention reader! Don’t stop learning now. Get hold of all the important C++ Foundation and STL concepts with the C++ Foundation and STL courses at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up
Recommended Articles
Page :