Presentation is loading. Please wait.

Presentation is loading. Please wait.

Vectors CSCE 121 J. Michael Moore.

Similar presentations


Presentation on theme: "Vectors CSCE 121 J. Michael Moore."— Presentation transcript:

1 Vectors CSCE 121 J. Michael Moore

2 Group of homogeneous elements accessed by an index.
Array/Vector Group of homogeneous elements accessed by an index. Vector access with ary.at(index) Bounds checking Array and Vector access with ary[index] No bounds checking

3 Array Really a pointer Variable name is a pointer to the first element
For ary[2] Conceptually: address of ary + 2*sizeof(array datatype) Actually: ary + 2 (math is done automatically) Pointer arithmetic Must know size of array at compile time Allows access to elements outside of array bounds Security problem

4 Vector Abstraction (An array on the heap.) Preferred over arrays
If you use .at() Bounds checking Prevents access outside array bounds Resizable #include <vector>

5 Vector Must say what type it is e.g. vector<int>
Define size at beginning vector<int> vec = vector<int>(SIZE); vector<int> vec = vector<int>(SIZE,INIT_VAL); Let vector grow as needed vector<int> vec; vec.push_back(7); Increases size by one

6 Vector vector<int> vec; vec.push_back(7);
vec.erase(vec.begin()+index); vec.at(index); // range checking & harder to read vec[index]; // no range checking & easier to read

7 Multi-dimensional Vectors
A vector of vectors vector< vector<int> > ary2d; Access ary2d.at(i).at(j) // safer ary2d[i][j]


Download ppt "Vectors CSCE 121 J. Michael Moore."

Similar presentations


Ads by Google