Homework question PLEASE HELP!

Only kidding.

What is the best way for getting the last element of a C++ std::string? I can think of two methods but I'm unsure whether the second is reliable. Any suggestions?

Thanks in advance.

1
2
3
4
5
// version 1
str[str.size() - 1];

// version 2 -- are there situations when this might not work?
*(str.end() - 1);

option 3:
 
str.back();


All 3 will work fine, as long as the string contains at least 1 character.

If you try to do any of these on an empty string, they will all fail / possibly crash.


EDIT:

Crap... does string have a back() function? I just assumed it did, but maybe not.
Last edited on
Topic archived. No new replies allowed.