Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How C char is different from C++ string element accessed using index

I am using C++ erase remove idiom and facing a weird problem.
If I access element using string index result is not as expected.

   string str = "A man, a plan, a canal: Panama";
   str.erase(remove(str.begin(), str.end(), str[1]), str.end());

Result : Aman, a plan, a canal: Panaa

and if I use as below, result is as expected.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

   string str = "A man, a plan, a canal: Panama";
   str.erase(remove(str.begin(), str.end(), ' '), str.end());

Result : Aman,aplan,acanal:Panama

>Solution :

Look at the signature of std::remove:

template< class ForwardIt, class T >
ForwardIt remove( ForwardIt first, ForwardIt last, const T& value );

The value is passed by const reference, therefore after removing first space your str[1] points to a wrong memory. It’s unsafe to access container elements while modifying the container.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading