qeaml
qeaml

Reputation: 38

Is there a difference between std::string's front() and [0]?

In my program I need to check the first character of a std::string, and use something like this:

if(string.front() == '-')

I wonder, does using the code below instead make any difference?

if(string[0] == '-')

Upvotes: 2

Views: 616

Answers (2)

pvc
pvc

Reputation: 1180

Both front() and operator[] returns reference to element, so no difference;

If you needs bounds checking you can use std::string::at, which does the boundary checking and throws std::out_of_range exception.

Upvotes: 0

cigien
cigien

Reputation: 60238

From the reference for string::front:

Effects: Equivalent to: return operator[](0);

So there is no difference between the 2 snippets of code you've shown.

Upvotes: 5

Related Questions