Presentation is loading. Please wait.

Presentation is loading. Please wait.

The vector Container Type

Similar presentations


Presentation on theme: "The vector Container Type"— Presentation transcript:

1 The vector Container Type
The vector class is an alternative to the standard array type in C++. Its implementation uses the C++ template facility. This facility allows programmers to build generic (polymorphic) classes, that is, classes that are defined independently of the type of data they hold and operate on. When you define such a class, you can use placeholders (parameters) instead of explicit type specifiers. You can then instantiate objects of that class for any compatible data type. March 5, 2019 CS410 – Software Engineering Lecture #4: C++ Basics II

2 The vector Container Type
To use a vector, we have to include the following header file: #include <vector> We can use vectors in two quite different ways: the array idiom the STL idiom (STL = Standard Template Library) March 5, 2019 CS410 – Software Engineering Lecture #4: C++ Basics II

3 The vector Container Type
The array idiom is very similar to the built-in array type. We specify the type and size of the array and then manipulate elements of the array in the usual way: void main() { int vecSize = 8; vector<int> intVec(vecSize); intVec[0] = 1; intVec[1] = 1; for (int i = 2; i < intVec.size(); i++) intVec[i] = intVec[i – 1] + intVec[i – 2]; cout << intVec[intVec.size() - 1]; } Output: ’21’ (Fibonacci) March 5, 2019 CS410 – Software Engineering Lecture #4: C++ Basics II

4 The vector Container Type
When a vector is created, its elements are initialized with the default value for their type. However, we can specify a different value. Example: vector<char> charVec(10, ‘x’); initializes all ten elements of charVec with the value ‘x’. (By the way, the default value for characters is the blank character or space.) March 5, 2019 CS410 – Software Engineering Lecture #4: C++ Basics II

5 The vector Container Type
A vector can also be initialized by specifying the first and one past the last element of an existing array. Example: int intArray[8] = {10, 20, 30, 40, 50, 60, 70, 80}; vector<int> intVec(intArray + 1, intArray + 5); creates a vector of size four with elements 20, 30, 40, and 50. A vector can also be initialized with or assigned to another vector. March 5, 2019 CS410 – Software Engineering Lecture #4: C++ Basics II

6 The vector Container Type
The STL idiom is quite different from the array idiom. We start with defining an empty vector, for example: vector<double> dblVec; Then we can add items to the back of the vector (and thereby expanding the vector) using the push_back operation: dblVec.push_back(3.7); dblVec.push_back(2.2); dblVec.push_back(-5.1); results in vector of size 3 with elements 3.7, 2.2, -5.1. March 5, 2019 CS410 – Software Engineering Lecture #4: C++ Basics II

7 CS410 – Software Engineering Lecture #4: C++ Basics II
The pair Type Another class in the standard library that uses the template facility is the pair class. It allows us to combine two values of either the same or different types within a single object. If we want to use pairs, we must include the following header file: #include <utility> Then we can start defining pairs such as: pair<string, double> FranksData(“Frank Miller”, 4.0); March 5, 2019 CS410 – Software Engineering Lecture #4: C++ Basics II

8 CS410 – Software Engineering Lecture #4: C++ Basics II
The pair Type We use member access notation to access the individual members of a pair: string name = FranksData.first; double GPA = FranksData.second; We can manipulate the values of the members analogously: FranksData.second = 1.0; March 5, 2019 CS410 – Software Engineering Lecture #4: C++ Basics II

9 CS410 – Software Engineering Lecture #4: C++ Basics II
Typedef Names For pair objects, it is often helpful to use the typedef mechanism. This mechanism allows us to define mnemonic synonyms for built-in and user-defined data types. Example: typedef pair<string, double> studentGPA; studentGPA frank(“Frank Miller”, 4.0); studentGPA doris(“Doris Carpenter”, 3.5); studentGPA jeff(“Jeff Bridges”, 2.47); March 5, 2019 CS410 – Software Engineering Lecture #4: C++ Basics II

10 CS410 – Software Engineering Lecture #4: C++ Basics II
Typedef Names Typedef names can improve the readability of our programs. Notice that typedef names do not introduce new types but only synonyms for existing data types. For example, the following code is correct: typedef double GPA; GPA JohnsGPA = 3.4; double BobsGPA; BobsGPA = JohnsGPA; March 5, 2019 CS410 – Software Engineering Lecture #4: C++ Basics II

11 CS410 – Software Engineering Lecture #4: C++ Basics II
Class Types In C++, classes are defined as follows: class Classname { public: // public member variables and member functions private: // private member variables and member functions protected: // protected member variables and member functions }; March 5, 2019 CS410 – Software Engineering Lecture #4: C++ Basics II

12 CS410 – Software Engineering Lecture #4: C++ Basics II
Class Types Public members are accessible from anywhere within the program. To achieve information hiding, you should generally limit the public members of a class to a small set of member functions that allow the manipulation of the class objects. Private members can be accessed only by the member functions and friends of its class. For information hiding, you should declare all member variables (data members) as private. Protected members behave as public members to a derived class and as private members to the rest of the program. March 5, 2019 CS410 – Software Engineering Lecture #4: C++ Basics II

13 CS410 – Software Engineering Lecture #4: C++ Basics II
Class Types The declaration of class data members is identical to the declaration of variables. Member functions are usually declared within the class definition and defined outside of it. Notice that when you define member functions outside the class definition, you have to provide the class name and the scope resolution operator (::). March 5, 2019 CS410 – Software Engineering Lecture #4: C++ Basics II

14 CS410 – Software Engineering Lecture #4: C++ Basics II
Class Types class StudentAdmonisher { public: bool SetRobotState(robotState); robotState GetRobotState(); private: robotState currentState; }; bool StudentAdmonisher::SetRobotState(robotState rs) { currentState = rs; return true; } robotState StudentAdmonisher::GetRobotState() return currentState; March 5, 2019 CS410 – Software Engineering Lecture #4: C++ Basics II

15 CS410 – Software Engineering Lecture #4: C++ Basics II
Class Types However, short member functions can also be placed inside the class body. Example: class StudentAdmonisher { public: bool SetRobotState(robotState rs) { currentState = rs; return true }; robotState GetRobotState() { return currentState }; private: robotState currentState; }; March 5, 2019 CS410 – Software Engineering Lecture #4: C++ Basics II

16 CS410 – Software Engineering Lecture #4: C++ Basics II
Storage Classes Every variable and function in the C++ kernel language has two attributes: type and storage class. The four storage classes are automatic, external, register, and static. Variables are assigned a storage class by placing the corresponding keyword before the type specifier. Examples: auto int a, b, c; extern float f = 7.22; March 5, 2019 CS410 – Software Engineering Lecture #4: C++ Basics II

17 CS410 – Software Engineering Lecture #4: C++ Basics II
The Storage Class auto Variables declared within function blocks are by default automatic. Therefore, automatic is the most common of the four storage classes. Automatic variables can be acted on within the scope of the enclosing block. March 5, 2019 CS410 – Software Engineering Lecture #4: C++ Basics II

18 The Storage Class extern
If we want to transmit information across blocks and functions, we can use external variables. When a variable is declared outside a function at the file level, storage is assigned to it permanently, and its storage class keyword is extern. Such a variable is considered to be global to all functions declared after it. The keyword extern is used to tell the compiler, “Look for it elsewhere, either in this file or in another one.” March 5, 2019 CS410 – Software Engineering Lecture #4: C++ Basics II

19 The Storage Class register
The storage class register tells the compiler that the associated variable should be stored in high-speed memory registers. This is not always possible. Increases time efficiency of manipulating this variable. Optimizing compilers assign register storage classes by themselves. March 5, 2019 CS410 – Software Engineering Lecture #4: C++ Basics II

20 The Storage Class static
Static variables retain their previous value when their block is re-entered. Static functions are visible only within the file in which they are defined. Therefore, the static storage class provides a privacy mechanism that is very important for program modularity. March 5, 2019 CS410 – Software Engineering Lecture #4: C++ Basics II

21 The Operators new and delete
The unary operators new and delete are available to manipulate free store. They are more convenient than the C functions malloc(), calloc(), and free(). Free store is a system-provided memory pool for objects whose lifetime is directly managed by the programmer. This adds responsibility to the programmer and can easily lead to problems such as memory leaks. On the other hand, manipulating free store is an efficient and flexible way to handle data structures such as trees and lists. March 5, 2019 CS410 – Software Engineering Lecture #4: C++ Basics II

22 The Operators new and delete
The programmer creates an object using new, and destroys the object using delete. The operator new is typically used in the following forms: new type-name new type-name initializer new type-name [expression] In each case, there are at least two effects: An appropriate amount of store is allocated from free store to contain the named type. The base address of the object is returned as the value of the new expression. March 5, 2019 CS410 – Software Engineering Lecture #4: C++ Basics II

23 The Operators new and delete
Example: int *p, *q; p = new int(5); q = new int[10]; In this code, the pointer variable p is assigned the address of the store obtained, The location pointed at by p is initialized to the value 5, the pointer variable q is assigned the base address of an int array of size 10. March 5, 2019 CS410 – Software Engineering Lecture #4: C++ Basics II

24 The Operators new and delete
Notice the following things: When memory is unavailable, the operator new can either throw a bad_alloc exception or return the value 0. If no initializer is provided, the content of the allocated memory is undefined. Arrays cannot be initialized using the new operator. Objects created by the new operator always need to be destroyed by the delete operator as soon as they are not used by the program any more. March 5, 2019 CS410 – Software Engineering Lecture #4: C++ Basics II

25 The Operators new and delete
The operator delete destroys an object created by new. This returns its allocated storage to free store for reuse. The operator delete is used in the following forms: delete expression delete [] expression The first form is used when the corresponding new expression has not allocated an array. The second form (empty brackets) is used when the original allocation was an array. The return type of delete is void (no return value). March 5, 2019 CS410 – Software Engineering Lecture #4: C++ Basics II

26 The Operators new and delete
Example: Dynamic allocation of an array int main() { int *data; int size; cout << “\nEnter array size: “; cin >> size; assert(size > 0); data = new int[size]; assert(data != 0); for (int j = 0; j < size; j++) cout << (data[j] = j) << ‘\n’; delete [] data; return 0; } Starting the program: Enter array size: 4 1 2 3 March 5, 2019 CS410 – Software Engineering Lecture #4: C++ Basics II

27 The Scope Resolution Operator
The concept of classes adds new scope rules to those of the kernel language. You remember that one point of classes is to provide an encapsulation technique. It makes sense that all names declared within a class be treated within their own scope as distinct from external names, function names, and other class names. This creates the need for the scope resolution operator. March 5, 2019 CS410 – Software Engineering Lecture #4: C++ Basics II

28 The Scope Resolution Operator
The scope resolution operator is the highest-precedence operator in the C++ language. It comes in two forms: ::j (unary operator – refers to external scope) MyClass::j (binary operator – refers to class scope) Its unary form is used to access a name that has external scope and has been hidden by local or class scope. March 5, 2019 CS410 – Software Engineering Lecture #4: C++ Basics II

29 The Scope Resolution Operator
Example: int count = 0; void how_many(double w[], int N, double x, int &count) { for (int i = 0; i < N; i++) count += (w[i] == x); // local count ++ ::count; // global count tracks calls } March 5, 2019 CS410 – Software Engineering Lecture #4: C++ Basics II

30 The Scope Resolution Operator
To better understand this program fragment, we change the parameter int &count to int &cnt: int count = 0; void how_many(double w[], int N, double x, int &cnt) { for (int i = 0; i < N; i++) cnt += (w[i] == x); // local count ++count; // global count tracks calls } March 5, 2019 CS410 – Software Engineering Lecture #4: C++ Basics II

31 The Scope Resolution Operator
Binary scope resolution is used to clarify names that are reused within classes. For example, we need scope resolution to define member functions: class Student { public: void PrintName(); private: string studentName; }; void Student::PrintName() { cout << studentName; } March 5, 2019 CS410 – Software Engineering Lecture #4: C++ Basics II


Download ppt "The vector Container Type"

Similar presentations


Ads by Google