[Solved] Vectors using C++


why here vector <int> :: iterator i;

The vector <int> :: iterator i; is created in order to traverse the vector vector <int> g1; (actually it can traverse any vector<int>, but in this case, that’s for g1)

is there a difference between vector <int> :: iterator i; and int i?

The scope of vector <int> :: iterator i; is the main function. Inside main, a new scope is created:

for (int i = 1; i <= 5; i++)
        g1.push_back(i);

In that scope, i is the int defined in the loop start, but it dies at the end of the loop, and after that i “returns to be” the vector <int> :: iterator i

int main()
{
    vector <int> g1;
    vector <int> :: iterator i;           // i is the iterator
    vector <int> :: reverse_iterator ir;

    for (int i = 1; i <= 5; i++)         // here i the int
        g1.push_back(i);                 // also here
                                         // from here the int i is dead, and i is back to being an iterator
    cout << "Output of begin and end\t:\t";
    for (i = g1.begin(); i != g1.end(); ++i)  
        cout << *i << '\t';

    cout << endl << endl;
    cout << "Output of rbegin and rend\t:\t";
    for (ir = g1.rbegin(); ir != g1.rend(); ++ir)
        cout << '\t' << *ir;

    return 0;

}

0

solved Vectors using C++