如何把string的元素逆序呢?

来源:互联网 发布:设置数据库为紧急模式 编辑:程序博客网 时间:2024/06/08 17:53

论坛里见到这个问题:如何把string的元素逆序?

我直接想到的是利用反向迭代器reverse_iterator:rbegin()和rend():

string str1("1234567890");string str2(str1.rbegin(), str1.rend());


这样的话逆序string就保存在str2里了。要是想保存在原string呢,这样:

string str1("1234567890");str1 = string(str1.rbegin(), str1.rend());

 

这是利用operator=(const string&),别忘了还有成员函数assign这个利器:

string str1("1234567890");str1.assign(str1.rbegin(), str1.rend());

这是使用了成员函数assign的一种重载:

template<class InputIterator>basic_string& assign(InputIterator first, InputIterator last);

 

不过这很容易产生疑问(这少我是产生了):看起来都是在相同的内存上操作,会不会有问题。类似memcpy的src和dst有重叠的情况?

C++标准告诉我们,是不会有问题的——标准(ISO2003)21.3.5.3:

template<class InputIterator>basic_string& assign(InputIterator first, InputIterator last);Returns: assign(basic_string<charT,traits,Allocator>(first,last))

原来会产生一个临时变量:basic_string<charT,traits,Allocator>(first,last)。疑虑消除了。

但是,能不能直接在string中逆序元素呢?这样就避免了临时变量的产生。自己动手写是不难,不过,STL中提供了大量的算法,看看其中有没有我们需要的:

template <class BidirectionalIterator>  void reverse ( BidirectionalIterator first, BidirectionalIterator last){  while ((first!=last)&&(first!=--last))    swap (*first++,*last);}

这个template <class BidirectionalIterator>  void reverse ( BidirectionalIterator first, BidirectionalIterator last)相当不错,完美解决了我们的问题:

str1("1234567890");reverse(str1.begin(), str1.end());
原创粉丝点击