C++移除序列中连续重复的特定值示例代码
前言
最近在写YTL中的字符串相关辅助函数。实现到split函数时,希望能够实现类似Python当中的str.split方法的功能。
IfsepisnotspecifiedorisNone,adifferentsplittingalgorithmisapplied:runsofconsecutivewhitespaceareregardedasasingleseparator,andtheresultwillcontainnoemptystringsatthestartorendifthestringhasleadingortrailingwhitespace.
也就是说,在最基本的split的基础上,要添加两个功能:
•删除输入字符串首尾的空白;
•将字符串中的连续分隔符当成一个分隔符看待。
前一个功能很好实现。将空白符保存在constchar*trim_chars="\t\n\r\v\f"当中,然后使用std::string::find_first_not_of以及std::string::find_last_not_of即可找到有效内容的起止位置,最后再std::string::erase一下就好了。
后一个功能也不复杂。但要写得优雅——最好是能利用上标准库的设施——就不那么容易了。
std::unique的基本用法
std::unique是定义在algorithm头文件内的容器算法。它有两种基本形式:
templateForwardItunique(ForwardItfirst,ForwardItlast); template ForwardItunique(ForwardItfirst,ForwardItlast,BinaryPredicatep);
其中,第一种形式是第二种形式的特例,它等价于BinaryPredicatep为连续两元素相等性判断时的第二种形式:
template::value_type&, consttypenamestd::iterator_traits ::value_type&)> ForwardItunique(ForwardItfirst,ForwardItlast, BinaryPredicatep=[](consttypenamestd::iterator_traits ::value_type&lhs, consttypenamestd::iterator_traits ::value_type&rhs){ returnlhs==rhs;});
这也就是说,第一种形式的std::unique会找到每个连续重复的区间,而后保留这些区间的首个元素,最后返回新序列逻辑上的尾后迭代器。例如,aabbccaa经过std::unique处理之后得到:
abca????
↑
这里用箭头标出的位置,即是std::unique的返回值所指向的位置。需要注意的是,经过std::unique处理之后,容器的实际大小没有发生改变,甚至逻辑尾后迭代器到容器实际尾后迭代器之间的左闭右开区间内的迭代器仍然是可解引用的(dereferenceable)。但这部分区间内的元素的值是不确定的。因此,在使用std::unqiue之后,往往会调用容器的erase函数成员,删除逻辑尾后迭代器开始的所有元素。例如:
//#include//#include std::stringsource("aabbccaa"); source.erase(std::unique(source.begin(),source.end()),source.end()); std::cout<