1. 程式人生 > >reverse和reverse_copy函數的應用

reverse和reverse_copy函數的應用

main 參數 調用 using space 內容 實現 esp std

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;
}

reverse和reverse_copy函數的應用