Vector Issue

#include
#include
#include
using namespace std;

int main()

{

vector<char> v;

v.push_back('c');

cout<<v.size()<<"\n";

 int j; cin>>j;

for(int i=0;i<v.size()-j;++i) cout<<i<<" ";

}

The above code is working fine for (j<=size of vector) but as soon as j>size of vector , the code gets stuck in an infinite loop

I dont know the reason behind this.

Thanks in advance for your time and help

Use i<(int)v.size()-j condition.

This is not an infinite loop. v.size() is unsigned data type.

So unsigned -5 is very lage.

Try cout<<v.size()-5<<endl; and cout<<(int)v.size()-5<<endl; you will get to know difference.

Thanks @aryanc403, its working now but could you please tell me the error…I mean what’s the difference between v.size() and (int)v.size()

In short,
v.size() is unsigned int. So It does not take negative value. In case you assign -5 to an unsigned int. Instead of -5. It will store a large +ve value. Which when converted back to signed int will result in -5. By default int is signed int.