Arrays, Pointers and Structures CS-240 Dick Steflik
Pointers allow us to access something indirectly –index of a book points to some topic in the body of a book –street addresses in a telephone book point to where some lives in the community –a forwarding address points to an address of where some one can be reached (pointer to a pointer)
Arrays and Structures Arrays - ordered collections of objects, all of the same type – int abc[4]; Structure - a collection of objects of dissimilar types –struct MyType { int abc ; double def;}
First Class Objects First Class Object –can be manipulated in all of the “usual ways” –are usually “safer than Second Class Objects –preserve “value semantics” obj2 = obj1 (assignment) objtype a ; objtype b(a) (copy constructor) a =+ b (overloaded assignment operators) –usually implemented as a class –can have bounds checking
Second Class Objects Primitive types (arrays and structs) don’t preserve value semantics are not as safe as First Class Objects –no bounds checking on array indicies
Standard template Library a standard set of templates and class templates that provide a set of First Class types was an “extra” in older compilers built into current generation of compilers
vector vector is a template class that provides a First Class version of the array primitive vector a(3); –allocates a vector containing 3 integers vector methods –size() - return # of elements in the vector –resize(n) - change the size of the vector to n elements
#include using namespace std; int main() { const int DIFFERENT_NUMBERS = 100; int totalNumbers; cout << “How many numbers?”; cin >> totalNumbers vector numbers(DIFFERENT_NUMBERS + 1); for (int I=0 ; I < numbers.size() ; 1++) numbers[I] = 0; for (int j=0 ; j < totalNumbers ; j++) numbers[rand[] % DIFFERENT_NUMBERS + 1] ++; for (int k=1 ; k < = DIFFERENT_NUMBERS ; k++) cout << k << “ occurs “ << numbers[k] << “times” << “\n”; return 0 }