Vectors CSCE 121 J. Michael Moore
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
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
Vector Abstraction (An array on the heap.) Preferred over arrays If you use .at() Bounds checking Prevents access outside array bounds Resizable #include <vector>
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
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
Multi-dimensional Vectors A vector of vectors vector< vector<int> > ary2d; Access ary2d.at(i).at(j) // safer ary2d[i][j]