C++ for loop skipping elements of a vector?

how to skip some of the array elements in c++
how to skip element in array
c++ vector iterator to second element
range based for loop c++ vs iterator

I'm tasked with creating a vector of 'x' numbers and finding the prime numbers in that vector using the "Sieve of Eratosthenes." I iterated through the vector to replace all of the non-prime elements with zero. Then I made a for loop to erase all of the zeros. The loop erased most of the zeros however it skipped some

vector<int> primes;
int userNum = 0; //variable for user to input the size of the vector
cout << "Enter your num, brah";
cin >> userNum;
for (int i = 2; i < userNum; i++) //creates a vector of numbers
{
    primes.push_back(i);
}


int j = 0; //variable to find non-primes

for (int p = primes[0]; p < primes.size(); p++) //loop to replace non-primes with zeros
{
    j = p+p;

    while (j < (primes.size() +2)) {



        replace(primes.begin(), primes.end(), j, 0);

        j+= p;

    }
}

for (int y = 0; y < primes.size(); y++) { //loop to erase the zeros from the vector
    cout << "y1 " << primes[y] << " ";   //cout simply just to find see what is going on
    if (primes[y] == 0) {
        primes.erase(primes.begin() +y);
        cout << "y2: " << y << endl;  //cout simply just to find see what is going on
    }

}

cout << "New Vector is: " << endl; //loop to print the vector
for (int l = 0; l < primes.size(); l++)
{

    cout << primes[l] << ", ";
}

The output I get is: New Vector is: 2, 3, 5, 7, 0, 11, 13, 0, 17, 19, 0, 23, 0, 0, 29, 31, 0, 0, 37, 0, 41, 43, 0, 47, 0, 0, 53, 0, 0, 59, 61, 0, 0, 67, 0, 71, 73, 0, 0, 79, 0, 83, 0, 0, 89, 0, 0, 0, 97, 0, Program ended with exit code: 0


There is no need to write a loop to remove an element from a vector. Use the erase-remove idiom

primes.erase(std::remove(primes.begin(), primes.end(), 0), primes.end());

The above uses std::remove to move the elements that are not to be erased to the "left side" or front of the vector, and returns the iterator that points to the first element that is to be removed "on the right side". Then primes.erase() actually removes the elements to erase from the vector by starting from the iterator returned from the call to std::remove.

You could break up the statement into two lines if you aren't sure how it works:

// returns an iterator to where the elements to erase are to be removed
auto iter = std::remove(primes.begin(), primes.end(), 0);

// Now actually erase them, starting at iter
primes.erase(iter, primes.end());

Iterate from second element of a vector in C++, Iterate from second element of a vector in C++ Using std::advance. Simple solution is to get an iterator to beginning of the vector and use the STL algorithm std::advance to advance the iterator by one position. Using std::next or ++, + operator. skipping the first element inside the loop. Range based for loop and std::for_each() functions are among those. They are new techniques for iterating through the elements of a sequence container, like vector, arrays or strings. Before C++ 11 we used normal for loop or while loop to access the elements of a collection in a container or array. For example if you want to access each element of a vector sequentially using traditional for loop or while loop, the code looks like:


one problem for sure is that you're going to skip elements because when you delete something from a sequence the index of everything after it goes down by 1.

I've made a simplified version of your delete code here that just tries to delete every element from a vector:

string vecToStr(const vector<int> &foos) {
  std::stringstream result;
  std::copy(foos.begin(), foos.end(), std::ostream_iterator<int>(result, " "));
  return result.str();
}

int main() {
  vector<int> foos = { 0,1,2,3,4,5,6 };
  for (int y = 0; y < foos.size(); y++) { //loop to erase the zeros from the vector
    foos.erase(foos.begin() + y);
    cout << "foos is now: " << vecToStr(foos) << " y is " << y << "\n";
  }
  cout << "foos is now: " << vecToStr(foos) << "\n";
  char c;
  cin >> c;
}

Here is the output:

foos is now: 1 2 3 4 5 6  y is 0
foos is now: 1 3 4 5 6  y is 1
foos is now: 1 3 5 6  y is 2
foos is now: 1 3 5  y is 3
foos is now: 1 3 5

You can see how the 0th element is deleted, then the element with value 1 moves into index 0, but y then becomes 1, so it gets skipped, then 2 is deleted at index 1, and 3 moves into index 2, etc.

There are a variety of approaches to this (see Remove elements of a vector inside the loop) the old-fashioned C way of doing this is to go from the end:

  int y = foos.size();
  while(y--) {
    foos.erase(foos.begin() + y);
    cout << "foos is now: " << vecToStr(foos) << " y is " << y << "\n";
  }

Get an iterator to n'th element of a vector in C++, Get an iterator to n'th element of a vector in C++ Another solution is to use the normal for-loop to iterate the vector and skip the first n elements inside the loop  Elements can be removed from a vector of vectors using the pop_back() function of C++ STL. Below example demonstrates the removal operation in a vector of vectors. The code removes elements from a 2D vector by using the pop_back() function and then displays the matrix.


The other answers make good suggestions -- erase remove idiom is well-known and useful.

However, the fix for your code is simple. Look at this loop

for (int y = 0; y < primes.size(); y++) { //loop to erase the zeros from the vector
    if (primes[y] == 0) {
        primes.erase(primes.begin() +y);
    }
}

It can be fixed just by not incrementing y when an element is removed.

for (int y = 0; y < primes.size(); /* no increment here */) { //loop to erase the zeros from the vector
    if (primes[y] == 0) {
        primes.erase(primes.begin() +y);
    } else {
      y++;
    }
}

How to skip some of the array elements in C++?, Here is a tutorial on how you can skip on some elements of an array? If it is, the continue will skip everything down in loop's scope and  Better: have an iterator pointing to foos.begin() before the loop and move those elements that shall remain to: *pos++ = vector[y] (this is what std::remove actually does as well). Afterwards, remove all surplus elements in one single go: foos.erase(pos, foos.end()); .


Range-based for loop in C++, Range-based for loop in C++ · Which C++ libraries are useful for competitive std::cout << '\n' ;. // Just running a loop for every array. // element. for ( int n : a). Inserting Elements; Iterating Over std::vector; Iterator/Pointer Invalidation; Matrices Using Vectors; Reducing the Capacity of a Vector; Using a Sorted Vector for Fast Element Lookup; Using std::vector as a C array; Vector size and capacity; vector: The Exception To So Many, So Many Rules; Storage class specifiers; Stream manipulators; Templates; The ISO C++ Standard


Parallel-Vector Equation Solvers for Finite Element Engineering , loop 2 (with K = 1) a(3, 3) = a(3, 3) – as 3, 1) + as 1, 3) |-loop 3 will be skipped (c) In loop 3, the JI" row of L keeps 196 Parallel-Vector Equation Solvers for  Simple solution is to get an iterator to beginning of the vector and use the STL algorithm std::advance to advance the iterator by one position. Then we use that iterator as starting position in loop In this post, we will discuss how to iterate from second element of a vector in C++.


Finite Element Methods:: Parallel-Sparse Statics and Eigen-Solutions, 2),be(ndofpe)= element (stiffness) matrix, C and element (load) vector C 0) go to 401 1003 skip, if DIRICHLET b.c. k=L-ndofpe 1004 to find location of do 30 j=iaa,iab 1022 loop covering all col numbers associated C ! with global row​  The idea of the for loop is that you are stepping through a sequence, one at a time, and performing an action at each step along the way. That sequence is commonly a vector of numbers (such as the sequence from 1:10 ), but could also be numbers that are not in any order like c(2, 5, 4, 6) , or even a sequence of characters!