250 likes | 370 Views
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 ;
E N D
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(); }
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.
Access vector elements just like with arrays • variable_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.
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!
Run the following code in the tempdemo project. vector <int> x(3); for (vector <int>::size_typei=0; i < x.size(); i++) cin >> x[i]; for (vector <int>::size_typei=0; i<x.size(); i++) cout << x[i] << " "; cout << endl; x.push_back(99); x.push_back(999); for (vector <int>::size_typei=0; i<x.size(); i++) cout << x[i] << " "; cout << endl; x.pop_back(); x.pop_back(); x.pop_back(); for (vector <int>::size_typei=0; i<x.size(); i++) cout << x[i] << " "; cout << endl;
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.
vector <int> x(3); vector <int> y(3); for (vector <int>::size_typei=0; i < y.size(); i++) cin >> y[i]; for (vector <int>::size_typei=0; i <= x.size(); i++) cin >> x[i]; for (vector <int>::size_typei=0; i< x.size(); i++) cout << x[i] << " "; cout << endl; for (vector <int>::size_typei=0; i< y.size(); i++) cout << y[i] << " "; cin.get();
See p. 274 for a well publicized problem (Internet worm) related to array overflow.
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 _Myfirstis a pointer to a memory location containing the first element of the vector. There is also _Mylast which indicates the end of the vector.
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.
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(inti, int x); int get(inti); private: vector<int> v(5); }; int test::get(inti) { return v[i]; } void test::put(inti, int x) { v[i] = x; } test::test() {} int main() { test x; x.put(2,22); int y = x.get(2); exit (0); }
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).
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.
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.
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).
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!
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.
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.
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.
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.
Examples: char year[]="1999";inty;y=atoi(year); //This is OK!! string year="1999";inty;y=atoi(year); //This is NOT OK!! //Need to use y=atoi(year.c_str());
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)
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.
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.
The banking program demo contains objects with both arrays and vectors.