Output of a vector, why doesn't this work?

Jun 21, 2015 at 9:00pm
Why doesn't this code work?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
#include <vector>

using namespace std;

int main()
{
    vector<int> prime={1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
    for(int i = 0;i <= prime.size(); i++)
    {
        cout<<prime[i];
    }

    return 0;
}


This prints me : 12345678910349561861
So what's wrong?
Jun 21, 2015 at 9:26pm
i <= prime.size()

should be

i < prime.size()

That is, you're printing one element beyond the end of the array (which appears to be value 349561861 in your case.)

Andy
Last edited on Jun 21, 2015 at 9:28pm
Topic archived. No new replies allowed.