#include<iostream>
#include<vector>
usingnamespace std;
int main()
{
vector<char>v(10);
int i;
cout << "current size of vector is\n"<<v.size()<<endl;
for(i=0;i<v.size();i++)
{
v[i] = 'a' + i;
cout << "contents of vector are\n"<<v[i]<<endl;
}
for(i=0;i<10;i++) //why not i<v.size() ?
{
v.push_back('a' + i + 10);
}
cout << "new size of vector is\n"<<v.size()<<endl;
for(i=0;i<v.size();i++)
{
cout << "new contents of vector\n"<<v[i]<<endl;
}
return 0;
}
This one compiles successfully but when I try to replace the size expansion loop of i<10 condition with i<v.size(); compiler throws a bad_alloc error.
Wondering what could go wrong. Isnt i<10 same as i<v.size()?
Kindly help. Thanks in advance.
Firstly, push_back() increases the size of a vector, by definition. Secondly, the loop condition is checked at each iteration: both the value of 'i' and 'size()' are read and compared.
As a result, it's essentially the same as this: for (int i = 0, a = 10; i < a; ++i) a++;
If i < a, then i+1 < a+1. In other words, this loop never ends.
Of course, you can do this:
1 2
int size = v.size();
for (i = 0; i < size; ++i) // Code
That way, you simply fetch the starting value of size() and use that.
Oh. You are right. It rings the bell a bit. But still not clear with the concept why v.size() cannot be used. Anyway, thanks for your input :) I will have to dig a bit into it.