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

Time:02-24

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?

CodePudding user response:

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;
}

CodePudding user response:

@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;
}
  • Related