I'm Michael Suodenjoki - a software engineer living in Kgs. Lyngby, north of Copenhagen, Denmark. This is my personal site containing my blog, photos, articles and main interests.

Updated 2011.01.23 15:37 +0100

 

C++ basic_string::back() oder was?

In a large C++ codebase I've recently encounted pieces of code that want to check whether a string ends with a specific character. The code typically looks like:

std::string str = ...;
int len = str.length();
if( len>0 && str[len-1]=='@' )
  ...

As a C++ Standard Library user and a modern C++ programmer that does not particular look good in my blue programming eyes. So what to do instead?

Well, you could consult your local C++ Standard Library documentation - in my case the Microsoft Visual C++ v.10 - and find that a possibility is to use the basic_string::back() method, as it provides this more nicer alternative code:

std::string str = ...;
if( !str.empty() && str.back()=='@' )
  ...

The problem is that back() is, as far as I've investigated, unfortunately not a standard method for the basic_string class, so you can not really rely on using it if you want your code to be library independent, as it really desired nowadays. So what to do? Well you probably have to use this:

std::string str = ...;
if( !str.empty() && *str.rbegin()=='@' )
  ...

Unless the intention is that the Standard C++ Library is supposed to support the basic_string::back() method I find it a bit unfortunate that Microsoft have added it to thier basic_string class implementation.

Well, that's it. Take care.

Links: