problem with the vector size allocation

Hi,
I am trying following program
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
#include<iostream>
#include<vector>
using namespace 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.
Hi , when i run this code i get no problem . .. what are you trying to say ?
Everytime you do a push_back(), the size() increases by one. Therefore your loop would never end.
Topic archived. No new replies allowed.