Strange thing whit for loop...

There is the strangest thing happening on this piece of code...

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
#include <vector>
using namespace std;

vector<int>deck;

int main() {
    int n;
    for (n=1; n<=52; n++) {
        deck.push_back(n);
        cout << deck.at(n) << endl;
        }
        cin.get();
        }


When it closes it puts on the screen
"This application has requested the Runtime to terminate it in an unusual way"

But if I change the n=1 to n=0 it works perfectly. Does anyone know why?
The first element you push_back is at index 0, not 1. So your first push_back inserts element #0 and then you print out element #1 (using at()). Then when you insert element #1 you print out element #2, and so forth. Accessing uninitialized memory.
Oooh. Thanks I made to variables one for the push_back and another for the at and works perfectly :)
Topic archived. No new replies allowed.