Вы находитесь на странице: 1из 16

Vectors

Ref.: D.S. Malik, Data Structures Using C++

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.

To copy the elements of an array to a vector


int intArray [5] = {2,4,6,8,10}; vector <int> intList (intArray, intArray+5);

Accessing the elements of a vector


vecList.at (index) vecList [index] Both of the above return the element at position index e.g. vector <int> intList(5); for (int j = 0; j < 5; j++) intList [j] = j;

Accessing the elements of a vector


vecList.front() vecList.back() 1st element last element

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

vecList.resize (num) vecList.resize (num, elem)

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?

Pointer (aka iterator)


declaration: vector<int>::iterator intVecIter; declares an iterator called intVecIter ++intVecIter causes the iterator to point to the next element in a vector *intVecIter returns the value of the current vector element

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

What does the vector look like after executing this?


int intArray [7] = {1,3,5,7,9,11,13}; vector <int> vecList (intArray, intArray + 7); vector <int>::iterator intVecIter; intVecIter = vecList.begin(); ++intVecIter; vecList.insert (intVecIter, 22);

Answer
{1, 22, 3, 5, 7, 9, 11, 13}

Вам также может понравиться