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

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 –

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

// 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

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.

GATE CS Corner    Company Wise Coding Practice

Recommended Posts:







Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.