CS 113: Data Structures and Algorithms Abhiram G.

CS 113: Data Structures and Algorithms Abhiram G.
1 / 1
CS 113: Data Structures and Algorithms Abhiram G. - slide 1 of 6 CS 113: Data Structures and Algorithms Abhiram G. - slide 2 of 6 CS 113: Data Structures and Algorithms Abhiram G. - slide 3 of 6 CS 113: Data Structures and Algorithms Abhiram G. - slide 4 of 6 CS 113: Data Structures and Algorithms Abhiram G. - slide 5 of 6 CS 113: Data Structures and Algorithms Abhiram G. - slide 6 of 6
CS 113: Data Structures and Algorithms Abhiram G. Ranade Some remarks on vectors How much time do different vector operations take? Indexing: The vector class stores elements in an array on the heap. So indexing takes time O(1) Appending an

Related Topics

Download this presentation From Below

"CS 113: Data Structures and Algorithms Abhiram G." is the property of its rightful owner. Permission is granted to download and print the materials on this website for personal, non-commercial use only, and to display it on your personal computer provided you do not modify the materials and that you retain all copyright notices contained in the materials. By downloading content from our website, you accept the terms of this agreement.

Presentation Transcript

01
CS 113: Data Structures and Algorithms Abhiram G. Ranade

Some remarks on vectors<br>
02
How much time do different vector operations take? Indexing:
The vector class stores elements in an array on the heap.
So indexing takes time O(1)
Appending an element (push_back)
When allocating the array, some room is kept for pushbacks.
If size of vector < allocated space, then new element is placed beyond the current size.
So time taken = O(1)
If size of vector = size of allocated array, new space must be allocated, and the vector must be copied to new space.
So time taken = O(vector size)
Typical strategy: If allocated size n is exceeded because of pushback, allocate size 2n (and use only n+1 elements in it).<br>
03
Example of doubling protocol Statement executed
vector v;
v.push_back(1);
v.push_back(2);
v.push_back(3);
v.push_back(4);
v.push_back(5);
v.push_back(6);
v.push_back(7); Content of array
_ allocation
1
1 2 allocation + copy 1
1 2 3 _ a + copy 2
1 2 3 4
1 2 3 4 5 _ _ _ a + copy 4
1 2 3 4 5 6 _ _
1 2 3 4 5 6 7 _<br>