counting in a vector

Hey,

1
2

Last edited on
Your condition on line 20 will never be true in your case, so number isn't set anywhere and on line 25 you are using uninitializated variable, which leads to undefined behavior.
Reposting OP code again.
DO NOT delete your question after you get an answer. It is rude.

Original question was why newly pushed number have some random value.
Original code (happens to save it):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include <iostream>
#include <vector>
using namespace std;

int main()
{
    //int one;
    vector<int> vMem;
    int temp = 0;

    // fill vector with numbers 0 - 4
    while(temp < 5){
         vMem.push_back(temp);
         temp++;
    }

    // add next number in sequence
    int number;
    for(int i(0); i < vMem.size(); i++){
        if (i != vMem[i]){
            number = i; // set number to i
            i = vMem.size(); // exit loop
        }
    }
    vMem.push_back(number);

    // display numbers
    for(int i(0); i < vMem.size(); i++){
        cout << vMem[i]  << endl;
    }
    return 0;
}
Last edited on
haha.. this way we will be left with only answers...
Topic archived. No new replies allowed.