C++ Sequence Container - Vector iterator example

in #cpp3 years ago (edited)

Vectors

A vector is a container similar to an array, but has no fixed size and can dynamically grow by pushing elements to it. A reference to all of its member functions can be found here: http://www.cplusplus.com/reference/vector/vector/

Ex Code
#include <iostream>
#include <vector>
#include <iterator>
#include <string>

using namespace std;

void vector_ex() {
    vector<string> students;

    cout << "\nVECTOR ITERATORS\n";

    students.push_back("Mary");
    students.push_back("Dave");
    students.push_back("Sara");
    students.push_back("Bill");

    cout << "\nWithout iterator\n";
    for (int i = 0; i < students.size(); i++) {
        cout << students[i] << endl;
    }

    cout << "\nWith iterator\n";
    vector<string>::iterator itr;
    for (itr = students.begin(); itr != students.end(); ++itr) {
        cout << *itr << endl;
    }

    cout << endl;
}
int main() {
    vector_ex();
    return 0;
}


Output
Without iterator
Mary
Dave
Sara
Bill

With iterator
Mary
Dave
Sara
Bill