Академический Документы
Профессиональный Документы
Культура Документы
Vectors
A vector is an array whose size can change. Need to have: #include <vector>
Declaring a vector
vector <elementType> vecList; e.g. vector <int> intList; creates vector intList whose components are of type int; it is empty e.g. vector <string> stringList; creates a vector whose components are of type string
Declaring a vector
vector <elementType> vecList(otherVecList); initialises vecList to the components of an existing vector vector <elementType> vecList(size); vector <elementType> vecList(size,elem); initialises all components to elem
Declaring a vector
vector <elementType> vecList(begin,end); initialises 1st component to begin initialises 2nd component to begin + 1 initialises last component to end - 1
Declaring a vector
Student exercise: Declare a vector intList whose components are of type int and whose size is 10.
Vectors
Description vecList.clear () vecList.erase (position) vecList.erase (beg, end) vecList.insert (position, elem) vecList.insert (position, n, elem) vecList.insert (position, beg, end) vecList.push_back (elem) vecList.pop_back () deletes all elements deletes element located at position deletes from beg to end-1 inserts elem in a new element located at position inserts n elements inserts a copy of the elements at locations beg to end-1 inserts elem at end deletes last element
changes vector size to num change size and set newly created elements to elem
Vectors
e.g. vector <int> intList; intList.push_back (34); intList.push_back (55); Student exercise: What does the above code do?
vector <int> intList; vector <int>::iterator intVecIter; 1. Whats intVecIter = intList.begin(); happening? for (intVecIter = intList.begin(); intVecIter != intList.end(); ++intVecList) cout << *intVecIter << ;
2. Whats happening?
Answers
1. iterator points to 1st element 2. outputs all elements in the vector
Answer
{1, 22, 3, 5, 7, 9, 11, 13}