reverse和reverse_copy函数的应用

reverse函数的作用是:反转一个容器内元素的顺序。函数参数:reverse(first,last);//first为容器的首迭代器,last为容器的末迭代器。它没有任何返回值。
这个函数比较简单,看一个例题:输入一个字符串,输出反转后的字符串。
直接调用函数。
代码:
#include <iostream>
#include <algorithm>
#include <string>
using namespace std;
int main()
{
    string str;
    cin>>str;
    reverse(str.begin(),str.end());
    cout<<str<<endl;
    return 0;
}
reverse_copy函数和reverse函数的唯一区别在于:reverse_copy会将结果拷贝到另外一个容器中,不影响原容器的内容。

还是上面的例题,使用reverse_copy函数来实现。
代码:
#include <iostream>
#include <algorithm>
#include <string>
using namespace std;
int main()
{
    string first,second;
    cin>>first;
    second.resize(first.size());
    reverse_copy(first.begin(),first.end(),second.begin());
    cout<<second<<endl;
    return 0;
}

原文地址:https://www.cnblogs.com/unknownname/p/7794937.html