Download presentation
Presentation is loading. Please wait.
Published byDarrell Garrison Modified over 8 years ago
1
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
2
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)
3
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)
4
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.
5
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
6
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
7
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
8
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"
9
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
10
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
11
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)
12
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
13
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
14
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
15
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)
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.