Reverse an vector
Here's a simple function in C++ that reverses a vector: ```cpp #include <iostream> #include <vector> // Function to reverse a vector void reverseVector(std::vector<int>& vec) { int left = 0; int right = vec.size() - 1; while (left < right) { // Swap elements at left and right indices std::swap(vec[left], vec[right]); left++; right--; } } // Function to print a vector void printVector(const std::vector<int>& vec) { for (const auto& element : vec) { std::cout << element << " "; } std::cout << std::endl; } int main() { // Create a sample vector std::vector<int> vec = {1, 2, 3, 4, 5}; std::cout << "Original vector: "; printVector(vec); // Reverse the vector reverseVector(vec); std::cout << "Reversed vector: "; printVector(vec); return 0; } ``` This code defines two functions: `reverseVector` and `printVector`. The `reverseVector` function takes a reference to a vector as an argument and reverses its elements in-place. The `printVector` function takes a constant reference to a vector and prints its elements. In the `main` function, we create a sample vector, print it, reverse it using the `reverseVector` function, and then print the reversed vector. When you run this code, it will output: ``` Original vector: 1 2 3 4 5 Reversed vector: 5 4 3 2 1 ``` This code uses the `std::swap` function to swap elements at the left and right indices of the vector, effectively reversing the vector. The `left` and `right` indices are initialized to the start and end of the vector, respectively, and then incremented/decremented in each iteration of the loop until they meet in the middle.