Presentation is loading. Please wait.

Presentation is loading. Please wait.

Announcements Midterm 2 is on TODAY, December 19 th at 19:40. Extra Recitation TODAY at 15:40-18:30 in FENS L062 Midterm Places: if (LastName<= "Hatipoğlu")

Similar presentations


Presentation on theme: "Announcements Midterm 2 is on TODAY, December 19 th at 19:40. Extra Recitation TODAY at 15:40-18:30 in FENS L062 Midterm Places: if (LastName<= "Hatipoğlu")"— Presentation transcript:

1 Announcements Midterm 2 is on TODAY, December 19 th at 19:40. Extra Recitation TODAY at 15:40-18:30 in FENS L062 Midterm Places: if (LastName<= "Hatipoğlu") cout << " FENS G077 "; else cout << " FMAN 1099 ";

2 struct s (7.4) Used as data aggregates for an entity can be different types of data e.g. for student id, name, GPA, address,... Similar to classes, but everything is public structs can have constructors structs can have member functions we will not deal with constructors and member functions for structs unless they are necessary mostly we will use structs for combining data for an entity into a single structure

3 Structs Example: struct for student First struct must be defined by giving it a name and its fields (data) struct student // student is struct name { unsigned int id; // fields of student struct string name, lastname; double gpa; }; // dont forget ; at the end Then variables of that type are declared and used. dot operator is used to refer fields of a struct variable student stu; stu.name = "Ali"; cout << stu.gpa; See structdemo.cpp (not in book)

4 What can and can’t be done with structs Structs can be passed to functions as parameters use const-reference if not changing (using value parameter is syntactically OK, but not preferred due to performance reasons) use reference parameter if changing struct fields behave as variables/objects of field type id is an integer name is a string You may read, write, use as operands in operations, etc. However, processing the entire struct variable is restrictive cannot read or write (using >> and <<) structs unless those operators are specially defined for that struct cannot use operators between two structs unless those operators are specially defined for that struct see 7.4.2 for operator definitions for structs, but not responsible structs are useful mostly in vectors (arrays)

5 Vectors and Arrays Arrays are collections of several elements of the same type E.g. 100 integers, 20 strings, 125 students, 12 dates, etc. Single name is given to the entire array But each element is accessed separately Any element of an array can be accessed just as quickly as any other element (this is called “random access” but do not get confused with RandGen type of randomness) In C/C++ there is a built-in array type We will see it, but later Vectors are a class-based version of arrays First we will see vectors.

6 Vectors We’re using the class tvector Copy tvector.h and tvector.cpp to your project folder need #include "tvector.h" But do NOT add tvector.cpp to your project It is already included within tvector.h If you mistakenly add tvector.cpp to your project, then you get tons of errors. tvector is a tapestry class that has the same functionality and based on the standard C++ class vector, but safer “Safe” means programming errors are caught rather than ignored

7 Why do we need arrays/vectors? Consider the following example (not in the book): pick n random numbers between 0 and 6 and count total number of occurrences of all outcomes (0, 1, 2, 3, 4, 5, 6) n is an input we need 7 counters 7 declarations 7 initializations 7 conditions to increment after each occurrence 7 cout statements to display the result Fortunately, we have shorter way: ARRAYS/VECTORS We can use vectors to store counters for all possible outcomes of the random numbers under a single name easier processing in loops see next slide for the program

8 Example Previous example using vectors - see randnums.cpp int num; int k; RandGen random; tvector randStats(7); // vector for counters int n = PromptRange("how many random numbers",1,20000); for(k=0; k <= 6; k++) // initialize counters to zero { randStats[k] = 0; } for(k=0; k < n; k++) // pick all random numbers { num = random.RandInt(7); // between 0 and 6 randStats[num] = randStats[num] + 1; // and increment // corresponding counter } cout << "number\t\t# of occurrences" << endl; for(k=0; k <= 6; k++) { cout << k << "\t\t" << randStats[k] << endl; } 0 1 2 3 4 5 6 randStats

9 Vector/Array basics Vectors/Arrays are homogeneous each item (sometimes called element) has the same type that type must be specified at declaration Items in a vector/array are numbered (e.g. 1 st, 3 rd, or 105 th ) those are called index or subscript numbering starts with 0 we have to use the index value to refer an element in a vector/array Example definition and use of vectors (array definition is a bit different) tvector ivals(10); // ivals can store 10 ints ivals[0] = 3; // 0 th element becomes 3 tvector svals(20); // svals can store 20 strings svals[4] = "cs201"; // 4 th element contains "cs201"

10 Vector basics Syntax of vector declaration tvector is a class, its declaration is construction 3 different methods tvector variable_name; empty vector (will see later) tvector variable_name (size_expression); vector with size_expression elements in it tvector variable_name (size_expression, init_value); vector with all size_expression elements initialized to init_value

11 Vector basics size_expression can be any expression of type integer (or cast into integer) not necessarily a constant value (this is actually a very important flexibility as compared to built-in arrays) examples: tvector letters (int('Z')-int('A') + 1); creates a vector of 26 integer elements and name it letters cin >> num; tvector counters (num); creates a vector of doubles; total number of elements is input Index value starts with 0 and ends with size-1 type is type of the vector elements can be built-in types (int, double,...) or user defined types or classes or structs (string and date are class examples; student is struct example) classes must have default constructors to be used in vector definition as element type

12 Defining tvector objects Can specify # elements in a vector, optionally an initial value tvector counts(300); //300 ints, values not initialized tvector nums(200, 0); // 200 ints, all zero tvector d(10, 3.14); // 10 doubles, all pi tvector w(10, "cs"); // 10 strings, all "cs" tvector words(10); // 10 strings, all "" If the vector type is a class, then this class must have a default constructor Default constructor is the one without parameters Cannot define tvector cubes(10); since Dice doesn’t have default constructor Vectors of classes are initialized with the default constructor that is why all words are "" (empty string) Vectors with built-in types are not initialized (unless explicitly initialized with the second argument of tvector definition)

13 Example tvector definitions tvector counter(9, 0); each element is an integer (all initialized to 0) 0 1 2 3 4 5 6 7 8 counter 0 1 2 3 4 5 6 7 8 letters 9 10 11 12 13 14 15 16 17 tvector letters(18); each element is a char (not initialized yet) 0 1 2 3 4 5 holidays tvector holidays(6); each element is a date object that contains todays date 17 12 2007 17 12 2007 17 12 2007 17 12 2007 17 12 2007 17 12 2007 0 0 0 0 0 0 0 0 0

14 How to reach a single vector/array element specify the index value within square brackets after the vector/array name var_name [index_expr] the value of index expression must be between 0 and (vector size – 1) Examples tvector nums(9); nums[5] = 102; nums[0] = nums[5]*2-1; nums[nums[5]/20-3] = 55; nums[10] = 5; // error 0 1 2 3 4 5 6 7 8 nums 102 20355

15 Passing vectors to functions as parameters Vectors can be passed as parameters to functions Pass by reference (if function changes the vector) void Count (tvector & counts); Pass by const-reference (if no changes made). void Print(const tvector & counts); Passing by value makes a copy, requires time and space, so not preferred IMPORTANT!!! Vector size cannot be given in parameter definition. Three solutions to this problem: the size may be passed as another parameter the size may be fixed and known tvector has a member function, size, to return the size of a vector

16 Example Counting letters of a file display number of occurrences of each letter at the end counting is case insensitive see letters.cpp (the one in book is a bit different)

17 tvector as a return type Vector can be return type of a function tvector Count (istream & input, int & total); Example: modify letters.cpp such that count returns the vector (not as reference parameter) see letters2.cpp

18 Vectors of structs We can define vectors of structs struct student { unsigned int id; string name, lastname; double gpa; }; tvector class(11); // a vector with 11 students class[1].gpa = 3.2; for (i = 0; i <= 10; i++) class[i].id = i + 1250; 1250 id gpa name lastname 1251 id 3.2 gpa name lastname 1260 id gpa name lastname 0 1 10

19 Vector of struct Example define a struct for a track on a CD track number and title are fields define a vector for 10 tracks shuffle these 10 tracks at random see shuffle.cpp (in book, but this version is slightly modified)

20 Vectors as lists The “vector as counters” example constructs and initializes a vector with a specific number of elements Other uses of vector require the vector to “grow” to accommodate new elements Consider reading words from a text file, storing them in a vector How big should we define vector initially? What are potential problems? When a vector is used as a list, we’ll use a different method for adding elements to the vector so that the vector can “grow”

21 Reading words into a vector (problematic version) tvector words(1000); string w; int i = 0; string filename = PromptString("enter file name: "); ifstream input(filename.c_str()); while (input >> w) { words[i]=w; i++; } cout << "read " << i << " words" << endl; What is the problem? there might be more than 1000 words in the file in this case index runs out of range

22 Reading words into a vector (with index range control but still problematic) tvector words(1000); string w; int i = 0; string filename = PromptString("enter file name: "); ifstream input(filename.c_str()); while ((input >> w) && (i < 1000)) { words[i]=w; i++; } cout << "read " << i << " words" << endl; What is the problem? works fine if there are no more than 1000 words but if there are more than 1000 words, the rest is not read

23 Reading words into a vector (no problems) One method would be to pass over the file two times one to find out number of words second to read the words into array Another method is to benefit from tvector class utilities as in the following code tvector words; //create empty vector string w; string filename = PromptString("enter file name: "); ifstream input(filename.c_str()); while (input >> w) { words.push_back(w); //adds the next word to the vector //also increases the size if necessary } cout << "read " << words.size() << " words" << endl;

24 Using tvector::push_back The method push_back adds new objects to the “end” of a vector, Internally, the vector keeps track of its capacity If there is capacity, then there is no problem; the new item is added to the end of the vector When the capacity is reached and push_back attempts to add a new element to the vector, then the vector automatically “grows” by doubling the capacity 0, 2, 4, 8, 16, 32,... If you want to use push_back mechanism, then the vector should be defined initially without specifying a size empty vector (zero size)

25 Size versus Capacity Capacity is the allocated size of the vector Size is how many elements are in the vector so far They are not the same concepts, but related as described in the previous slide and illustrated below tvector names; // size is 0, capacity is 0 names.push_back("Ali"); // size is 1, capacity is 2 names.push_back("Husnu"); // size is 2, capacity is 2 names.push_back("Ayse"); // size is 3, capacity is 4 names.push_back("Cem"); // size is 4, capacity is 4 names.push_back("Jale"); // size is 5, capacity is 8

26 size() member function size() member function basically returns the number of elements in the vector When a vector is defined with no initial capacity, and push_back is used to add elements, size() member function returns the number of elements exist in the vector This is the number of calls of push_back() if no elements are deleted If elements deleted using pop_back(), size updated too (decremented) If a non-empty vector is created, then the capacity and the size is set to the number of elements of the vector. This capacity is considered full, so the first push_back causes to double the capacity. What about size() in case the vector is created as a non- empty one returns the size specified during declaration if no push_back() is used returns the size specified during declaration + the number push_back() s, if push_back() is used

27 capacity() and reserve() The capacity of vector is accessible using capacity() member function programmers don’t often need this value An initial capacity of N elements can be specified using reserve(N) member function

28 Demo Example Read some strings from keyboard and store in a tvector of strings. At the end display the vector. version 1: no reserve version 2: (decomment the reserve lines): with reserve version 3: vector is not created empty (decomment second definition and comment out first one and reserve lines) See tvectordemo.cpp (not in the book)

29 Vector Processing Examples – 1 (vectorproc.cpp – not in book) write a function that takes a tvector of integers as parameter and returns the maximum of numbers in it process all array elements – for loop from 0 to vector’s size - 1 int max (const tvector & v) //pre: vector v is not empty //post: return max of elements in v { int i, max_so_far = INT_MIN; for (i=0; i < v.size(); i++) { if (v[i] > max_so_far) { max_so_far = v[i]; } return max_so_far; }

30 Vector Processing Examples – 2 (vectorproc.cpp – not in book) Write a function that takes a tvector of integers as parameter and returns true if the vector is sorted in ascending manner, false otherwise may not process all vector elements In this type of rule-checking applications, a possible method is to assume that the rule is satisfied before the loop and find a counterexample in the loop bool issorted (const tvector & v) //post: returns true if the array is acsending sorted { bool s = true; // initially assume that array is sorted //in the function try to break this assumption int i =1; while (i < v.size() && s == true) { //check until the end of array or until a counterexample is found if (v[i-1] > v[i]) // if not sorted s = false; // counterexample is found i++; } return s; }

31 Searching a vector We can search for one occurrence, return true/false or the index of occurrence Search the vector starting from the beginning Stop searching when match is found We can search and count the number of occurrences and return count Search entire vector Similar to one occurrence search, but do not stop after first occurrence We can search for many occurrences, but return occurrences in another vector rather than count In all these cases, we search the vector sequentially starting from the beginning This type of search is called “sequential search”

32 Counting search int countmatches(const tvector & a, const string& s) // post: returns # occurrences of s in a { int count = 0; int k; for(k=0; k < a.size(); k++) { if (a[k] == s) { count++; } return count; } How can we change this code to return the index of the first occurrence? see next slide

33 One occurrence search int firstmatch(const tvector & a, const string& s) // post: returns the index of occurrence of s in a, -1 // otherwise { int k; for(k=0; k < a.size(); k++) { if (a[k] == s) { return k; } return -1; } Does not search the entire array if one match is found good for efficiency purposes How could you modify this to return true/false?

34 Collecting search Collect the occurrences in another vector void collect(const tvector & a, tvector & matches) // pre: matches is empty // post: matches contains all elements of a with // first letter 'A' { int k; for(k=0; k < a.size(); k++) { if (a[k].substr(0,1) == "A") { matches.push_back(a[k]); }

35 Binary search Alternative to sequential search for sorted vectors If a vector is sorted we can use the sorted property to eliminate half of the vector elements with one comparison What number (between 1 and 100) do we guess first in number guessing game? Idea of creating program to do binary search Check the middle element If it has the searched value, then you’re done! If not, eliminate half of the elements of the vector search the rest using the same idea continue until match is found or there is no match how could you understand that there is no match? let’s develop the algorithm on an example we need two index values, low and high, for the search space

36 Binary Search (search for 62) 10 24 34 52 55 62 67 75 80 81 90 92 100 101 111 low=0 mid=7 high=14 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 low = 0 mid=3 high=6 low=4 high=6 mid=5 => FOUND

37 Binary Search (search for 60) 10 24 34 52 55 62 67 75 80 81 90 92 100 101 111 low = 0 mid=7 high =14 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 low=0 mid=3 high=6 low=4 high=6 mid=5 low=4 high=4 mid=4 low=5 high=4 => NO MATCH FOUND – STOP

38 Binary search code int bsearch(const tvector & list, const string& key) // pre: list.size() == # elements in list // post: returns index of key in list, -1 if key not found { int low = 0; // leftmost possible entry int high = list.size()-1; // rightmost possible entry int mid; // middle of current range while (low <= high) { mid = (low + high)/2; if (list[mid] == key) // found key, exit search { return mid; } else if (list[mid] < key) // key in upper half { low = mid + 1; } else // key in lower half { high = mid - 1; } return -1; // not in list }

39 Comparing Sequential and Binary Search Given a list of N elements: Binary search makes on the order of log N operation O(log N) Linear (sequential) search takes on the order of N operations O(N)

40 Sorting One of the fundamental operations in Computer Science Given a randomly ordered array, sort it ascending descending Many algorithms exists some in Chapter 11 we will discuss two of them – Selection Sort (11.1.1) and Insertion Sort (11.1.2) Analysis in 11.4

41 Selection Sort N is the number of elements in vector/array Find smallest element, move into 0 th vector/array location examine all N elements 0.. N-1 Find next smallest element, move into first location 0 th location is already the minimum examine N-1 elements 1.. N-1 Find next smallest element, move into 2 nd location 0 th and 1 st locations are already the minimum two elements examine N-2 elements 2.. N-1 Generalize for k th element, 0 <= k <= N-2 - find the minimum between k th and last element (element with index N-1) of array - swap the k th element with the minimum one

42 Selection Sort: The Code void SelectSort(tvector & a) // pre: a contains a.size() elements // post: elements of a are sorted in non-decreasing order { int j, k, temp, minIndex, numElts = a.size(); for(k=0; k < numElts - 1; k++) { minIndex = k; // minimal element index for(j=k+1; j < numElts; j++) { if (a[j] < a[minIndex]) { minIndex = j; // new min, store index } temp = a[k]; // swap min and k-th elements a[k] = a[minIndex]; a[minIndex] = temp; }

43 insertion and deletion It’s easy to insert at the end of a vector, use push_back() However, if the vector is sorted and if we want to keep it sorted, then we can’t just add to the end We have to find an appropriate position to insert the element and do some shifts. If we need to delete an element from a sorted vector, how can we “close-up” the hole created by the deletion? Shift elements left by one index, decrease size We decrease size using pop_back() pop_back() changes size, not capacity

44 Inserting an element into a sorted array 2 7 11 18 21 22 26 89 99 Insert NewNum which is e.g. 23 Is the array “capacity” sufficient for an extra element? What would you do to insert newNum in the right spot?

45 Insertion into sorted array 2 7 11 18 21 22 26 89 99 NewNum = 23 2 7 11 18 21 22 26 26 89 99 0 1 2 3 4 5 6 7 8 0 1 2 3 4 5 6 7 8 9

46 Insert into sorted vector void insert(tvector & a, int newnum) // NOT const vector // pre: a[0] <= … <= a[a.size()-1], a is sorted // post: newnum inserted into a, a still sorted { int count = a.size(); //size before insertion a.push_back(newnum); //increase size – newnum is inserted at // the end but the inserted value is not important int loc = count; // start searching insertion loc from end while (loc > 0 && a[loc-1] > newnum) { a[loc] = a[loc-1]; loc--; // shift right until the proper insertion cell } a[loc] = newnum; //actual insertion } See vectorproc.cpp (not in book)

47 What about deletion? Remove the element at a given position ( pos ) void remove(tvector & a, int pos) // post: original a[pos] removed, size decreased { int lastIndex = a.size()-1; a[pos] = a[lastIndex]; a.pop_back(); } What about if vector is sorted, what changes? What’s the purpose of the pop_back() call?

48 Deletion from sorted vector 2 7 11 18 21 22 26 89 99 0 1 2 3 4 5 6 7 8 Ex: Delete element at position 3 2 7 11 21 22 26 89 99 99 0 1 2 3 4 5 6 7 8 2 7 11 21 22 26 89 99 99 0 1 2 3 4 5 6 7 Size is 9 Size is now 8 First shift all elements on the right of 3 rd element one cell to the left pop back the last element of vector

49 Deletion from sorted vector void remove(tvector & a, int pos) // pre: a is sorted // post: original a[pos] removed, a is still sorted { int lastIndex = a.size()-1; int k; for(k=pos; k < lastIndex; k++) { a[k] = a[k+1]; } //shift all elements on the right of pos one cell left a.pop_back(); //remove the last element of the array } Does pop_back() actually remove an element? no, it just decreases the size so that the last element becomes unreachable Capacity remains the same See vectorproc.cpp (not in book)

50 Insertion Sort Insert 1 st element before or after 0 th first 2 sorted Insert 2 nd element (element with index 2) in proper location first 3 sorted Generalize insert k th element (element with index k) within first k elements first k+1 sorted run this for all k between 1.. N-1

51 Insertion Sort – The Code void InsertSort(tvector & a) // precondition: a contains a.size() elements // postcondition: elements of a are sorted in non- decreasing order { int k,loc, numElts = a.size(); for(k=1; k < numElts; k++) { string hold = a[k]; // insert this element loc = k; // location for insertion // shift elements to make room for hold (i.e. a[k]) while (0 < loc && hold < a[loc-1]) { a[loc] = a[loc-1]; loc--; } a[loc] = hold; }

52 Which one faster? No exact answer! It depends on the vector to be sorted already ordered, totally disordered, random Let’s see how many iterations do we have in Selection Sort Outer loop  k: 0.. N-2 Inner loop  j: k+1.. N-1 (N-1) + (N-2) + (N-3) +.. + 1 = N(N-1)/2 = (N 2 – N)/2 Worst case, best case, average case??? Complexity is O(N 2 ) order of N 2 Big-oh notation used to describe algorithmic complexities. This is not a precise amount of operations and comparisons. Minor terms and coefficients are not taken into consideration

53 Which one faster? Let’s analyze Insertion Sort Outer loop  k: 1.. N-1 N-1 iterations for the outer loop What about inner loop? worst case, best case differ worst case: k times, so total is 1+2+3+…+(N-1) = N(N-1)/2, complexity is O(N 2 ) best case: inner loop does not iterate, complexity is O(N), but best case complexity analysis is not done too often what are the best and worst cases? average case: inner loop iterates k/2 times, order is still O(N 2 ) Complexities of both Selection and Insertion Sort are O(N 2 ) Which one would you prefer to use? Let’s run timesorts.cpp (modified from book) – needs several Tapestry.h and.cpp files in the project folder to run (comparer.h, ctimer.h, ctimer.cpp, prompt.h, prompt.cpp, randgen.h, randgen.cpp, sortall.h, sortall.cpp, tvector.h, tvector.cpp – red ones to be added to the project).

54 Built-in Arrays C++ native array type Two versions fixed size arrays array size is fixed and must be specified with a constant expression at the declaration we will see this type now array pointers array size is dynamically allocated we will not see it in this course use of both types are the same except definition tvector versus built-in arrays tvector is a class based on built-in arrays tvector has member functions and operators, built-in arrays do NOT tvector is more flexible, but slower

55 Built-in Array declaration As we said, we will discuss fixed size built-in arrays, not the pointer version with dynamic allocation size must be able to be determined at compile time constant, literal or an expression that involves constants and literals only const int CLASSSIZE = 100; // constant string names[CLASSIZE]; // array of 100 strings double grades[CLASSIZE*5]; // array of 500 doubles int list[200]; // array of 200 integers The following array declaration is INVALID int size; cout "Enter how many students ? "; cin >> size; string names[size]; // array size cannot be a variable

56 Built-in array initialization at declaration You may specify a list of initial values at declaration. See following example: string dayNames [] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday","Friday", "Saturday"}; dayNames is an array with 7 elements of type string 0 th element is “Sunday”, 1 st is “Monday”,... not necessary to specify size (7), since the number of elements make the size clear but you can specify the size, if you wish string dayNames [7] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday","Friday", "Saturday"};

57 Assignment rules in arrays tvectors with the same element type can be assigned to each other by = LHS vector becomes the same as the RHS vector size and capacity also become the same Built-in arrays cannot be assigned to each other by = int coins[] ={1,5,10,25}; int temp[4]; temp = coins; // illegal temp[1] = coins[2]; // legal – array element assignment How can we assign coins to temp? element by element for (i=0; i<4; i++) temp[i] = coins[i];

58 Passing built-in arrays as parameters A built-in array can be passed only as reference parameter or const-reference parameter cannot be passed as value parameter But, we do not use ampersand character, &, at parameter declaration and we do not specify the array size in array parameter however array size is generally passed as another integer parameter since we do not have a size() member function for built-in arrays void Change(int list[], int numElts); void Print(const int list[], int numElts); reference parameter const-reference parameter

59 Built-in array demo See fixlist.cpp (slightly modified from the version in book) Why did we use const in Print ? to avoid accidental changes in array list Why did we pass numElts as parameter for the number of elements in the array? because we don’t know the total number of elements in the array while writing the functions

60 Example – Fibonacci numbers Used in many areas of Mathematics and Computer Science F 0 = 1 F 1 = 1 F n = F n-1 + F n-2 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 You can see many examples of Fibonacci numbers in nature E.g. Increase of number of branches of trees in time See http://www.mcs.surrey.ac.uk/Personal/R.Knott/Fibonacci/fibnat.html for more exampleshttp://www.mcs.surrey.ac.uk/Personal/R.Knott/Fibonacci/fibnat.html const int MAX_SIZE = 100; int list[MAX_SIZE]; int k; list[0] = list[1] = 1; for (k=2; k < MAX_SIZE, k++) { list[k] = list[k-1]+list[k-2]; }

61 Use of strings as arrays Characters in a string can be referred as an array using [ ] string s="cs201";... s[0] = 'n'; // makes 0 th character of s 'n'... for (k=0; k<s.length(); k++) cout << s[k] << " "; In general, s[k] means s.at(k)

62 The Class tmatrix (Section 10.6.1) To represent two dimensional arrays rows and columns tmatrix mymatrix (3,5); mymatrix[2][3] = 100; First index is for row, second is for column Basically a matrix is a vector of vectors 100 0 1 2 3 4 012012

63 tmatrix definitions Syntax of matrix declaration tmatrix is a class, its declaration is construction 3 different methods tmatrix variable_name; empty matrix (zero rows, zero columns) tmatrix variable_name (rows, columns); matrix with rows*columns elements in it tmatrix variable_name (rows, columns, init_value); matrix with all elements initialized to init_value

64 tmatrix member functions tmatrix::numrows() number of rows in matrix tmatrix::numcols() number of columns in matrix tmatrix::resize(int newRows, int newCols) resizes matrix so that the new matrix has newRows rows and newCols columns elements are copied, may lose data if downsized see tmatrix.h for all other member functions Example: Let’s run matdemo.cpp


Download ppt "Announcements Midterm 2 is on TODAY, December 19 th at 19:40. Extra Recitation TODAY at 15:40-18:30 in FENS L062 Midterm Places: if (LastName<= "Hatipoğlu")"

Similar presentations


Ads by Google