Class Notes (839,626)
CS 138 (14)
Lecture 5

# Data Lecture 5.docx

3 Pages
140 Views

Department
Computer Science
Course Code
CS 138
Professor
Michael Godfrey

This preview shows page 1. Sign up to view the full 3 pages of the document.
Description
Data Lecture 5 January 22, 2013 Arrays, arrays, and vectors in C++  C-style arrays are almost the same in C and C++  Must state max size (extent) up front and must be compile-time constant o Eg: “const int” or explicit positive integer, NOT variable o int A[15]; const int N=15 int B[N]; int M cin>>M; int C[M]; //DOES NOT WORK  In the standard library for C++ 11, there is a library class called “array” o Adds a lot of confusion to dimensions  Using C-style arrays, references to individual elements are unchecked at run-tome o POSSIBLY UNSAFE! o Can write A[i]=A+i  Often have to pass in extent of an array as extra parameter to functions int findMax (vector A) { int max=0; for (int i=0;imax) { max=A[i]; //also A.at(i); } } return max; } Vector  C++ (and Java and other languages) have library element called “vector” o Safe, generic, dynamically resizeable array o More flexible/safer but possible less efficient o Under the hood, vectors are implemented as arrays plus same magic  Not part of C++ language o Member of C++ STL, which is part of C++ SL  #include  Accessing elements o A[i]  Like an array, unchecked and fast o A.at(i)  Through the “at()” method, checked  If i>=A.size(), then program dies vector monthName(12); //creates 12 element vector using "" as default value vector grades; //creates 0-element vector, but we can make it bigger  Once declared, you can only add elements of specified element type o You can treat them either as fixed size container or variable sized container //Vector as (stable, static-sized) array monthName[0]="Jan"; ... monthName[11]="Dec"; //Typical use: declare with fixed size and just use it //Vector as stack (variable size) vector grades; while (in) { int grade; cin>>grade; grades.push_back(grade); } Stacks vector v; //size=0 v.push_back("hello"); //size=1 v.push_back("world
More Less

Only page 1 are available for preview. Some parts have been intentionally blurred.

Unlock Document

Unlock to view full version

Unlock Document
Me

OR

Join OneClass

Access over 10 million pages of study
documents for 1.3 million courses.

Join to view

OR

By registering, I agree to the Terms and Privacy Policies
Just a few more details

So we can recommend you notes for your school.