c++ reverse part of vector
Reversing Part of a Vector in C++
To reverse part of a vector in C++, you can use the std::reverse
function from the <algorithm>
header. Here are the steps to achieve this:
- Include the Necessary Header Files:
Include the
<vector>
and<algorithm>
header files in your C++ program.Create a Vector:
Create a vector and populate it with elements.
Use the std::reverse Function:
- Use the
std::reverse
function to reverse the elements within a specified range of the vector.
Here's an example of how you can achieve this:
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> vec = {1, 2, 3, 4, 5, 6, 7, 8, 9};
// Reversing part of the vector from index 2 to index 5
std::reverse(vec.begin() + 2, vec.begin() + 6);
// Output the modified vector
for (int num : vec) {
std::cout << num << " ";
}
return 0;
}
This code snippet reverses the elements in the vector from index 2 to index 5. After running this code, the output will be: 1 2 6 5 4 3 7 8 9
.