shift element to end of vector c++
#include <iostream>
#include <vector>
#include <algorithm>
void shiftToEnd(std::vector<int>& vec, int element) {
auto it = std::find(vec.begin(), vec.end(), element);
if (it != vec.end()) {
vec.erase(it);
vec.push_back(element);
}
}
int main() {
std::vector<int> numbers = {4, 7, 2, 9, 5, 7, 2};
int elementToShift = 7;
std::cout << "Before shifting: ";
for (int num : numbers) {
std::cout << num << " ";
}
std::cout << std::endl;
shiftToEnd(numbers, elementToShift);
std::cout << "After shifting " << elementToShift << " to the end: ";
for (int num : numbers) {
std::cout << num << " ";
}
std::cout << std::endl;
return 0;
}
This C++ code defines a function shiftToEnd
that takes a vector of integers and an element to shift to the end of the vector. It uses the <vector>
and <algorithm>
libraries. Here's a step-by-step breakdown:
- Function
shiftToEnd
: - Takes a vector (
std::vector<int>& vec
) and an element (int element
). - Uses
std::find
from the<algorithm>
library to find the first occurrence of the element in the vector. If the element is found (
it != vec.end()
), it removes it from its current position (vec.erase(it)
) and appends it to the end of the vector (vec.push_back(element)
).main
function:- Initializes a vector
numbers
with some integers and anelementToShift
variable. - Displays the elements of the vector before shifting.
- Calls
shiftToEnd
function with thenumbers
vector and theelementToShift
. Displays the elements of the vector after shifting the specified element to the end.
Output:
- Prints the elements of the vector before and after shifting the specified element.
This program demonstrates shifting a specific element to the end of a vector in C++.