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:

  1. Function shiftToEnd:
  2. Takes a vector (std::vector<int>& vec) and an element (int element).
  3. Uses std::find from the <algorithm> library to find the first occurrence of the element in the vector.
  4. 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)).

  5. main function:

  6. Initializes a vector numbers with some integers and an elementToShift variable.
  7. Displays the elements of the vector before shifting.
  8. Calls shiftToEnd function with the numbers vector and the elementToShift.
  9. Displays the elements of the vector after shifting the specified element to the end.

  10. Output:

  11. 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++.