Removing duplicate characters from string using STL

后端 未结 1 1231
面向向阳花
面向向阳花 2020-12-03 19:05

Is there a way to remove duplicate characters from a string like they can be removed from vectors as below

sort( vec.begin(), vec.end() );
vec.erase( unique         


        
相关标签:
1条回答
  • 2020-12-03 19:42

    The whole point of C++’ algorithm and container design is that the algorithms are – as far as possible – container agnostic.

    So the same algorithm that works on vectors works – of course! – on strings.

    std::sort(str.begin(), str.end());
    str.erase(std::unique(str.begin(), str.end()), str.end());
    

    The same even works on old-style C strings – with the small difference that you cannot erase their tails, you need to manually truncate them by re-setting the null terminating character (and there are no begin and end member functions so you’d use pointers to the first and one-past-last character).

    0 讨论(0)
提交回复
热议问题