Class Notes (1,100,000)
CA (630,000)
UW (20,000)
CS (1,000)
CS138 (10)
Lecture 5

CS138 Lecture Notes - Lecture 5: Bounds Checking


Department
Computer Science
Course Code
CS138
Professor
Michael Godfrey
Lecture
5

This preview shows half of the first page. to view the full 3 pages of the document.
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<int> A) {
int max=0;
for (int i=0;i<A.size();i++) {
if (A[i]>max) {
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 <vector>
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<string> monthName(12); //creates 12 element vector using "" as default value
vector<int> grades; //creates 0-element vector, but we can make it bigger
You're Reading a Preview

Unlock to view full version