C++ backward()
C++ 算法函数backward()
该函数用于向后移动元素,它接受三个参数,然后移动属于范围的元素[ ,持续)。元素的移动以相反的顺序开始,终止点在'result'。
语法
template<class BidirectionalIterator1, class BidirectionalIterator2>
BidirectionalIterator2 move_backward(BidirectionalIterator1 first, BidirectionalIterator1 last, BidirectionalIterator2 result);
参数
first: 它是范围的第一个元素的双向迭代器,其中元素本身包含在范围中。
last: 它是范围last元素的双向迭代器,其中元素本身不包含在范围中。
result: 它是移动元素最终位置的双向迭代器。
返回值
该函数将迭代器的第一个元素返回到已移动元素的序列。
示例1
#include <iostream>
#include <algorithm>
#include <string>
int main ()
{
std::string elem[10] = {"kunal","suraj","shweta","chhavi"};
std::move_backward (elem,elem+4,elem+5);
elem[0]="keto";
std::cout << "elem contains:";
for (int j=0; j<10; ++j)
std::cout << " [" << elem[j] << "]";
std::cout << '\n';
return 0;
}
输出:
elem contains: [keto] [kunal] [suraj] [shweta] [chhavi] [] [] [] [] []
示例2
#include<bits/stdc++.h>
int main()
{
std :: vector <int> u1 {5,9,14,8,18};
std :: vector <int> u2 {5,5,5,5};
std :: cout << "u1 contains :";
for(int j = 0; j < u1.size(); j++)
std :: cout << " " << u1[j];
std :: cout << "\n";
std :: cout << "u2 contains :";
for(unsigned int j = 0; j < u2.size(); j++)
std :: cout << " " << u2[j];
std :: cout << "\n\n";
std :: move_backward (u2.begin(), u2.begin() + 3, u1.begin() + 3);
std :: cout << "u1 after applying move_backward function contains:";
for(unsigned int j = 0; j < u1.size(); j++)
std :: cout << " " << u1[j];
std :: cout << "\n";
return 0;
}
输出:
u1 contains : 5 9 14 8 18
u2 contains : 5 5 5 5
u1 after applying move_backward function contains: 5 5 5 8 18
复杂度
该函数的复杂度从第一个元素到last元素都是线性的。
数据竞争
访问某些或所有容器对象。
异常
如果任何容器元素抛出一个异常,该函数将引发异常。