Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between string::at and string::operator[]?

Tags:

c++

string

I was taught string::at in school, but by exploring the string library I saw string::operator[], which I was never shown before.

I'm now using operator[] and haven't used at since, but what is the difference? Here is some sample code:

std::string foo = "my redundant string has some text";
std::cout << foo[5];
std::cout << foo.at(5);

They are essentially the same in terms of output, but are there some subtle differences I'm not aware of?

like image 409
ayane_m Avatar asked Feb 05 '13 02:02

ayane_m


People also ask

What is the difference between string and std::string in C++?

There is no functionality difference between string and std::string because they're the same type.

What is the difference between string and std::string?

Differences between std::string and String Pavan. std::string is the string class from the standard C++ library. String is some other string class from some other library. It's hard to say from which library, because there are many different libraries that have their own class called String.

What does std::string () do?

std::string class in C++ C++ has in its definition a way to represent a sequence of characters as an object of the class. This class is called std:: string. String class stores the characters as a sequence of bytes with the functionality of allowing access to the single-byte character.

What does AT () do in C++?

at() is a member function in C++. s.at() returns the letter at position i in the string. But if the position is not in the range, it throws an exception.


2 Answers

Yes, there is one major difference: using .at() does a range check on index passed and throws an exception if it's over the end of the string while operator[] just brings undefined behavior in that situation.

like image 101
Jack Avatar answered Sep 21 '22 05:09

Jack


at does bounds checking, exception of type std::out_of_range will be thrown on invalid access.

operator[] does NOT check bounds and thus can be dangerous if you try to access beyond the bounds of the string. It is a little faster than at though.

like image 23
Karthik T Avatar answered Sep 18 '22 05:09

Karthik T