L26vectors

L26vectors - Vectors the better arrays Why Vectors q q q q...

Info iconThis preview shows pages 1–6. Sign up to view the full content.

View Full Document Right Arrow Icon
Vectors the better arrays
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full Document Right Arrow Icon
Why Vectors vectors are implemented as a class (a template to be exact) they serve the same purpose as arrays but using object oriented mechanisms (such as operator overloading) made more powerful vectors can can grow and shrink as needed can be compared, assigned as a whole can be passed by reference/value/returned vector size is always available still more … part of so called Standard Template Library (STL) once you learned vectors, do not use (raw) arrays
Background image of page 2
Declaration include <vector> header file to declare vector< type_parameter > vectorName ; where type_parameter – type/class of vector elements corresponds to base type of the array examples vector<int> items; // declares vector with no elements vector<double> items(5); // declares vector with 5 elements vector<myclass> items(5); // declares a vector of 5 objects of myclass
Background image of page 3

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full Document Right Arrow Icon
Typical Array Operations indexing: items[3] sill cannot refer past vector size: items[6]++; // range error another indexing: items.at(5) this one is preferred because there is a safety check (more later) checking size: items.size() careful with this one: returns value of type size_t example: for(size_t i=0; i < items.size(); i++) cout << items[i];
Background image of page 4
Atypical Array Operations adding element: items.push_back(55); removing element: items.pop_back(); checking if empty: items.empty(); accessing first/last element: items.front(); items.back(); changing size: items.resize(newSize);
Background image of page 5

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full Document Right Arrow Icon
Image of page 6
This is the end of the preview. Sign up to access the rest of the document.

{[ snackBarMessage ]}

Page1 / 15

L26vectors - Vectors the better arrays Why Vectors q q q q...

This preview shows document pages 1 - 6. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online