Chapter 6 Vectors and arrays :

25
Chapter 6 Vectors and arrays: Arrays: Run the following code. Anything unusual? #include <iostream> using namespace std; #define N 10 #define M 11 int main() { int x = 10; int a[N]; cout << " x is equal to " << x << endl; for (int i=1; i<=M; i++) a[i]=i*i; for (int i=1; i<=N; i++) cout << i << " " << a[i] << endl; cout << " x is equal to " << x << endl; cin.get(); }

description

Chapter 6 Vectors and arrays :. Arrays: Run the following code. Anything unusual? #include < iostream > using namespace std; #define N 10 #define M 11 int main() { int x = 10; int a[N]; cout

Transcript of Chapter 6 Vectors and arrays :

Page 1: Chapter 6 Vectors and arrays :

Chapter 6 Vectors and arrays:

Arrays: Run the following code. Anything unusual?#include <iostream>using namespace std;#define N 10#define M 11

int main(){

int x = 10;int a[N];

cout << " x is equal to " << x << endl;for (int i=1; i<=M; i++)

a[i]=i*i;for (int i=1; i<=N; i++)

cout << i << " " << a[i] << endl;cout << " x is equal to " << x << endl;cin.get();

}

Page 2: Chapter 6 Vectors and arrays :

Vector:

collection of data items of the same type (much like an array)General format: vector <type> name(initial size)

Example declarations:vector <int> scores(50);vector <Employee> staff(20);Need: #include <vector>initial size can be 0 to start with an empty vector.

Page 3: Chapter 6 Vectors and arrays :

Access vector elements just like with arraysvariable_name[i].Legal subscripts are 0 through initial_size-1. If v is the vector variable then v.size() represents the number of elements in the vector. Thus, v.size()-1 is the largest legal subscript.

Page 4: Chapter 6 Vectors and arrays :

v.push_back(value) increases the vector size by one and puts the value in the new spot.v.pop_back() decreases the vector size by one, losing the value in the last position.Although convenient, it can be inefficient!

Page 5: Chapter 6 Vectors and arrays :

Run the following code in the tempdemo project.vector <int> x(3);for (vector <int>::size_type i=0; i < x.size(); i++) cin >> x[i];for (vector <int>::size_type i=0; i<x.size(); i++) cout << x[i] << " ";cout << endl;x.push_back(99);x.push_back(999);for (vector <int>::size_type i=0; i<x.size(); i++) cout << x[i] << " ";cout << endl;x.pop_back();x.pop_back();x.pop_back();for (vector <int>::size_type i=0; i<x.size(); i++) cout << x[i] << " ";cout << endl;

Page 6: Chapter 6 Vectors and arrays :

If you go beyond the vector limits the program MAY NOT generate an out of bounds exception!! This can be dangerous and cause unpredictable results. Try the code on the next slide and see what happens Must take care in writing programs. An exception is thrown in VB.NET 2008. If the cpp file is copied to Linux and compiled using g++, then no exception is thrown at the point where the illegal subscript is referenced but a segment fault error occurs.

Page 7: Chapter 6 Vectors and arrays :

vector <int> x(3);vector <int> y(3);for (vector <int>::size_type i=0; i < y.size(); i++) cin >> y[i];for (vector <int>::size_type i=0; i <= x.size(); i++) cin >> x[i];for (vector <int>::size_type i=0; i< x.size(); i++) cout << x[i] << " ";cout << endl;for (vector <int>::size_type i=0; i< y.size(); i++) cout << y[i] << " ";cin.get();

Page 8: Chapter 6 Vectors and arrays :

See p. 274 for a well publicized problem (Internet worm) related to array overflow.

Page 9: Chapter 6 Vectors and arrays :

Seeing vector values in the debugger:Put the vector name in a watch window.Vector values appear but the display does not tell the whole story of what’s going on.The vector state _Myfirst is a pointer to a memory location containing the first element of the vector. There is also _Mylast which indicates the end of the vector.

Page 10: Chapter 6 Vectors and arrays :

Put *(v._Myfirst) in the watch window to see the first vector item. *(v._Myfirst+1) locates the next item, *(v._Myfirst+2) the next one, and so on.Use *(v._Mylast-1) to show the last item in the vector.

Page 11: Chapter 6 Vectors and arrays :

NOTE: How to declare a vector (vector<type> v(5)) as an item in a struct or class definition!!! Examine the following code and note the error:

#include <iostream>using namespace std;#include <vector>class test{public:

test();void put(int i, int x);int get(int i);

private:vector<int> v(5);

};int test::get(int i){

return v[i];}void test::put(int i, int x){

v[i] = x;}test::test() {}int main(){ test x; x.put(2,22); int y = x.get(2); exit (0);}

Page 12: Chapter 6 Vectors and arrays :

Reasons and solutions follow:The above is more than just a declaration of 5 elements. The intent is to call a constructor, passing a parameter of 5 to it. This cannot be done in a declaration.Vectors are not arrays despite the use of [] to access a particular element. Use of [] is allowed because the [] is overloaded (discussed later).

Page 13: Chapter 6 Vectors and arrays :

Proper way to set up a vector in a class is to write v(5) in the field initializer list p. 248) of the constructor. i.e. if the class name were C then you’d have

C::C(pars) : ….,v(5),…

Thus in the above code declare the vector as vector<int> v; and replace the constructor with test::test():v(5){}.Show what happens if only the first change in the previous bullet is done.

Page 14: Chapter 6 Vectors and arrays :

Suggestion: Do NOT use notation such as v[i++]. It can be confusing.The string type is a vector of characters.See code snippets starting on page 275 to see how a vector can be passed as a value or reference parameter or how it can be returned via a function name.See note on passing by constant reference (p. 277) to increase performance.

Page 15: Chapter 6 Vectors and arrays :

Removing vector elements:If no particular order, overwrite the element to be deleted with the last element and shrink the vector by 1. See logic on p. 277.If elements are in order, must shift, then shrink. See logic on p. 278.

Similar issues for inserting an element (p. 278).

Page 16: Chapter 6 Vectors and arrays :

Quality Tip 6.2, Parallel vectors: Example: collection of students, GPAs, majors, and credits. Might use 4 vectors and represent a student by using the ith element in each vector. This is BAD design! Better to set up a student class and create a vector of objects. Authors call parallel vectors evil. They are!

Page 17: Chapter 6 Vectors and arrays :

Arrays: like vectors but can not be resized.

Array size (capacity) specified at compile time. Programmer must specify the size. Also called static arrays.Programmer must estimate how many elements to allocate to the array. Inefficiency if the array is bigger than you really need. Problems if it is smaller.Each array must have a companion variable, a variable indicating the number of elements actually stored in the array.

Page 18: Chapter 6 Vectors and arrays :

This is different than the array capacity.HOWEVER, arrays are more efficient than vectors when it comes to accessing the elements.Each has its own advantages and disadvantages.

Page 19: Chapter 6 Vectors and arrays :

Character arrays.

Used before string class became available. May see this in CS370.

array of characters with ‘\0’ at the end.Could initialize by using char greeting[6]=”Hello”. Need 6 positions to account for the NULL terminator.C provides a strlen() function that return the number of characters in a string. i.e. strlen(greeting) returns 5.

Page 20: Chapter 6 Vectors and arrays :

See example code on page 287.Also have functions: strcat, strncat, strcpy, strncpy. May see more of this in CS370.must sometimes be used for backward compatibility.

Page 21: Chapter 6 Vectors and arrays :

Examples:

char year[]="1999";int y;y=atoi(year);//This is OK!!

string year="1999";int y;y=atoi(year);//This is NOT OK!!

//Need to use y=atoi(year.c_str());

Page 22: Chapter 6 Vectors and arrays :

There is a problem with trying to return an array via a function name. It will work for a vector but not an array. Reason is related to the fact that an array is NOT a class and that "=" is NOT an overloaded operator for an array.Array parameters are always passed by reference!!An array parameter must always be accompanied by its companion variable (its size)

Page 23: Chapter 6 Vectors and arrays :

Two dimensional arrays: type var[NROWS] [NCOLS].

Access a row using notation var [i] [j]. Each of i and j must be >=0 and <= the limit.When passing as a parameter, must specify the number of columns as a constant in the parameter declaration. Number of rows is not required.Reason is that arrays are stored by placing rows in consecutive memory locations. Need only the row length (# columns) to resolve a memory reference.

Page 24: Chapter 6 Vectors and arrays :

Later you’ll learn that char x[10] and char* x are similar. First is static allocation; second allows memory allocation to be done dynamically. In the latter case, this allows the programmer to design the ability to expand the array into the software. In turn, this allows the programmer to get around some of the array’s disadvantages while preserving its advantages. However, it is more work for the programmer.

Page 25: Chapter 6 Vectors and arrays :

The banking program demo contains objects with both arrays and vectors.