Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth
Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

42,753 questions

55,518 answers

573 users

How to remove every N‑th element from a vector in C++

1 Answer

0 votes
// ------------------------------------------------------------
// 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 

*/

 



answered 1 day ago by avibootz
...