C语⾔反转字符串函数reverse()
The behavior of this function template is equivalent to:
template <class BidirectionalIterator>
void reverse (BidirectionalIterator first, BidirectionalIterator last)
{
while ((first!=last)&&(first!=--last)) {
std::iter_swap (first,last);
++first;
}
}
Attention:
to the initial and final positions of the sequence to be reversed. The range used is [first,last), which contains all the elements between first and last, including the element pointed by first but not the element pointed by last.
BidirectionalIterator shall point to a type for which is properly defined.
Example:
// reverse algorithm example
#include <iostream> // std::cout
#include <algorithm> // std::reverse
#include <vector> // std::vector
int main () {
std::vector<int> myvector;
// set some values:
for (int i=1; i<10; ++i) myvector.push_back(i); // 1 2 3 4 5 6 7 8 9
std::reverse(myvector.begin(),d()); // 9 8 7 6 5 4 3 2 1
// print out content:
std::cout << "myvector contains:";
for (std::vector<int>::iterator it=myvector.begin(); it!=d(); ++it)
std::cout << '' << *it;
std::cout << '\n';
return0;
}
Output:
myvector contains: 987654321
实例:PAT⼄级
1008 数组元素循环右移问题 (20 分)
⼀个数组A中存有N(>0)个整数,在不允许使⽤另外数组的前提下,将每个整数循环向右移M(≥0)个位置,即将A中的数据由(A0A1⋯A N−1)变换为(A N−M⋯A N−1A0A1⋯A N−M−1)(最后M个数循环移⾄最前⾯的M个位置)。如果需要考虑程序移动数据的次数尽量少,要如何设计移动的⽅法?
输⼊格式:
每个输⼊包含⼀个测试⽤例,第1⾏输⼊N(1≤N≤100)和M(≥0);第2⾏输⼊N个整数,之间⽤空格分隔。
字符串截取函数c语言输出格式:
在⼀⾏中输出循环右移M位以后的整数序列,之间⽤空格分隔,序列结尾不能有多余空格。
输⼊样例:
6 2
1 2 3 4 5 6
输出样例:
5 6 1 2 3 4
代码:
#include <iostream> #include <algorithm> using namespace std; int main(){
int n,m;
int a[1000];
cin>>n>>m;
m%=n;
for(int i=0;i<n;i++){ cin>>a[i];
}
reverse(a,a+n);
reverse(a+m,a+n); reverse(a,a+m);
for(int i=0;i<n;i++){ cout<<a[i];
if(i!=n-1)
cout<<"";
}
return0;
}
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论