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

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?
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
Topic archived. No new replies allowed.