ST::CrimeSe()在C++中的应用

reverse()是头文件算法中的预定义函数。它被定义为上述头文件中的模板。它颠倒了任何容器的范围[first,last]中元素的顺序。时间复杂度为O(n)。 注: 使用的范围是[first,last],它包含first和last之间的所有元素,包括first指向的元素,但不包括last指向的元素。 语法:

null
void reverse(BidirectionalIterator first, BidirectionalIterator last)
BidirectionalIterator is an iterator that can be used to access any
elements of a container in both forward and backward direction.

例如:

Input : 10 11 12 13 14 15 16 17
Output :10 11 12 13 14 17 16 15
Explanation:
reverse(v.begin() + 5, v.begin() + 8);
In the above function, input we have applied reverse() on the vector
from index 5 to index 7.
Therefore when we display the vector we get reverse order
from index 5 to index 7.

CPP

// CPP program to illustrate
// std::reverse() function of STL
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector< int > vec1;
vector< int >::iterator p;
// Inserting elements in vector
for ( int i = 0; i < 8; i++) {
vec1.push_back(i + 10);
}
// Displaying elements of vector
cout<< "Initial Vector:" <<endl;
for (p = vec1.begin(); p < vec1.end(); p++) {
cout << *p << " " ;
}
cout << endl;
cout << "Reverse only from index 5 to 7 in vector:" ;
// Reversing elements from index 5 to index 7
reverse(vec1.begin() + 5, vec1.begin() + 8);
// Displaying elements of vector after Reversing
for (p = vec1.begin(); p < vec1.end(); p++) {
cout << *p << " " ;
}
cout << endl <<endl;
vector< int > vec2{ 4, 5, 6, 7 };
cout<< "Initial Vector:" <<endl;
for (p = vec2.begin(); p < vec2.end(); p++) {
cout << *p << " " ;
}
cout << endl;
cout << "Reverse full Vector:" <<endl;
// Reversing directly from beginning to end
reverse(vec2.begin(), vec2.end());
// Displaying elements of vector after Reversing
for (p = vec2.begin(); p < vec2.end(); p++) {
cout << *p << " " ;
}
cout << endl;
return 0;
}


输出:

Initial Vector:
10 11 12 13 14 15 16 17 
Reverse only from index 5 to 7 in vector:
10 11 12 13 14 17 16 15 

Initial Vector:
4 5 6 7 
Reverse full Vector:
7 6 5 4 

时间复杂性: O(n)

本文由 哈迪克·高尔 .如果你喜欢GeekSforgek,并想贡献自己的力量,你也可以使用 贡献极客。组织 或者把你的文章寄到contribute@geeksforgeeks.org.看到你的文章出现在Geeksforgeks主页上,并帮助其他极客。 如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写下评论。

© 版权声明
THE END
喜欢就支持一下吧
点赞8 分享