0

I apologize if this question is naive, but I seem to be having some issues with vector push_back. Following Stroustrup's book, I'm trying to write a code to determine primes [1,100]. Everything I have written thus far seems to work, it correctly determines which ones are primes, but when trying to push the primes into a vector, it seems to not be pushing all the values, or doing so incorrectly

#include <iostream>     // std::cout
#include <vector>       // std::vector
using namespace std;

int prime(int num) {
    for (int j = num-1; j >= 2; --j) {
        if (num%j != 0) {}
        else if (num%j == 0) return 1;
        }

    return 0;
    }

int main() {
    vector<int> found_primes;
    int eval {0};
    for (int i = 1; i <= 100; ++i) {
        eval = prime(i);
        if (eval > 0) {}
        else if (eval == 0) found_primes.push_back(i); // I think the problem is here
    }

    for (int j : found_primes) {
        cout << found_primes[j] << '\t';
    }
}

This provides the output: "2 3 5 11 17 31 41 59 67 83 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0"

What exactly am I missing? Thanks in advance.

MVarga
  • 1

1 Answers1

1

Replace this:

for (int j : found_primes) {
    cout << found_primes[j] << '\t';
}

With this:

for (int j : found_primes) {
    cout << j << '\t';
}

Why

Roughly speaking, the range based for syntax is a more convenient syntax for iteration that encapsulates the usage of iterators. Because of this, rather than having to use an iterator, you just obtain the element behind the iterator on each iteration.

The old style was:

for (vector<int>::iterator it = found_primes.begin(); it != found_primes.end(); it++) {
    cout << *it << '\t';
}

You can still do this if you want (ideally using auto rather than vector<int>::iterator), however, iterators can be invalidated under certain circumstances, and the verbose syntax gives you a lot of opportunities for mistakes, especially if you are learning.

More details here.

arboreal84
  • 2,086
  • 18
  • 21
  • This answer would be better if it addressed _why_ your code works but OP's didn't. What is significant about the change and what OP was doing wrong – Tas May 28 '17 at 21:17