C++ Sequence Container - Vector iterator example

in cpp •  6 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
Authors get paid when people like you upvote their post.
If you enjoyed what you read here, create your account today and start earning FREE STEEM!
Sort Order:  

Vote back