// ------------------------------------------------------------
// A small program demonstrating how to remove every Nth element
// from a std::vector using clear, expressive C++ patterns.
// ------------------------------------------------------------
#include <iostream>
#include <vector>
#include <stdexcept>
/*
This function returns a new vector with every Nth element removed.
It uses a simple loop with an index counter. Because C++ vectors
use zero‑based indexing, we check (index + 1) % n != 0 to keep
elements that are *not* in the Nth position.
The algorithm is efficient: it performs a single pass over the
input and pushes kept elements into the output vector.
*/
template <typename T>
std::vector<T> removeEveryNth(const std::vector<T>& items, int n) {
if (n <= 0) {
throw std::invalid_argument("n must be a positive integer");
}
int size = items.size();
std::vector<T> result;
result.reserve(size); // reserve capacity to avoid reallocations
for (std::size_t i = 0; i < size; i++) {
if ((i + 1) % n != 0) {
result.push_back(items[i]);
}
}
return result;
}
/*
Keeping main small and focused makes the program easy to extend.
Here we demonstrate the function with a simple example.
*/
int main() {
std::vector<int> data;
for (int i = 1; i <= 20; i++) {
data.push_back(i); // Example list: numbers 1–20
}
int n = 3; // Remove every 3rd element
auto cleaned = removeEveryNth(data, n);
std::cout << "Original: ";
for (int x : data) std::cout << x << " ";
std::cout << "\n";
std::cout << "After removing every " << n << "-th element: ";
for (int x : cleaned) std::cout << x << " ";
}
/*
run:
Original: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
After removing every 3-th element: 1 2 4 5 7 8 10 11 13 14 16 17 19 20
*/