-5
#include<bits/stdc++.h>
using namespace std;
int main()
{
    vector <int> v;
    vector<int> :: iterator ip;
    v.push_back(2);
    for(int i=3;i<=32000;i+=2)
    {
        int top;
        top = sqrt(i)+1;
        int flag=0;
        if(*ip>top) break;
        if(i%*ip==0)
        {
            flag=1;
            break;
        }
        if(flag==0)
        {
            v.push_back(i);
        }
    }
    int t;
    cin>>t;
    while(t--)
    {
        int n;
        cin>>n;
        cout<<v.at(n)<<endl;
    }
    return 0;
}

can you please explain me why my code is getting runtime error. is size of the vector is getting out of range ?? I dont know why i am getting wrong answer in this code although my code is perfectly fine.

1 Answers1

2

You're dereferencing an uninitialized iterator, you want something more like:

vector<int>::iterator ip = v.begin();
Paul Evans
  • 27,315
  • 3
  • 37
  • 54
  • That's part of the story. This will keep getting invalidated whenever the vector grows. – Mike Seymour Oct 08 '14 at 16:54
  • Only works if v contains a value, i.e. first the push_back(2) from above, then your line of code. – chrizke Oct 08 '14 at 16:54
  • 1
    Except that if the vector re-sizes, it will probably invalidate the iterator. Not even sure what they are trying to do, but an index is probably simpler. – crashmstr Oct 08 '14 at 16:54