'Why does my loop never stop when using vector .size() as the stop condition?

vector<int> x (100.0);
//int vsize = x.size();

for(int i = 0; i < x.size(); i++){
    x.insert(x.begin() + i, 100 - i);
    cout << "Index " << i << ": " << x[i] << endl;
}

I want to add 1 into x[99], 2 into x[98], 3 into x[97], ...99 into x[1] and 100 into x[0].

However, the loop never stops. When I use int vsize instead, it will work. Can someone explain to me what is going on here? I am aware of how .capacity() works with vectors. Is this whats happening here? Does the vector just keep increasing itself?



Solution 1:[1]

Because you are inserting a new element every time in the loop, so it never stops.

It seems like instead of inserting, you want assigning. So:

for(int i = 1; i <= x.size(); i++){
    x[100 - i] = i;
    std::cout << "Index " << i << ": " << x[i] << endl;
}

Solution 2:[2]

@Descode if using break statement is a problem then please look into this

vector<int> x(100);

for(int i = 0;i<100;i++){
    x[i] = 100-i;
    std::cout << "Index " << i << ": " << x[i] << endl;
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 justANewb stands with Ukraine
Solution 2 Fallen