The vector Container Type

Slides:



Advertisements
Similar presentations
Chapter 7: User-Defined Functions II
Advertisements

Kernighan/Ritchie: Kelley/Pohl:
C++ How to Program, 7/e © by Pearson Education, Inc. All Rights Reserved.
Chapter 6. 2 Objectives You should be able to describe: Function and Parameter Declarations Returning a Single Value Pass by Reference Variable Scope.
Rossella Lau Lecture 5, DCO10105, Semester B, DCO10105 Object-Oriented Programming and Design  Lecture 5: Class construction  Encapsulation 
Data Abstraction and Object- Oriented Programming CS351 – Programming Paradigms.
Introduction to Classes and Objects CS-2303, C-Term Introduction to Classes and Objects CS-2303 System Programming Concepts (Slides include materials.
Review of C++ Programming Part II Sheng-Fang Huang.
February 27, 2014CS410 – Software Engineering Lecture #8: C++ Basics II 1 The vector Container Type When a vector is created, its elements are initialized.
March 4, 2014CS410 – Software Engineering Lecture #9: C++ Basics III 1 Today’s Topics The operators new and deleteThe operators new and delete The scope.
C++ for Engineers and Scientists Third Edition
C++ How to Program, 8/e © by Pearson Education, Inc. All Rights Reserved. Note: C How to Program, Chapter 22 is a copy of C++ How to Program Chapter.
A First Book of C++: From Here To There, Third Edition2 Objectives You should be able to describe: Function and Parameter Declarations Returning a Single.
Chapter 6: Modularity Using Functions. In this chapter, you will learn about: – Function and parameter declarations – Returning a single value – Returning.
Learners Support Publications Classes and Objects.
Chapter 9 Pointers and Dynamic Arrays (9.1). Pointers A variables which holds the memory address for a variable of a specific type. Call-by-Reference.
C++ Class Members Class Definition – class Name – { – public: » constructor(s) » destructor » function members » data members – protected: » function members.
Classes In C++ 1. What is a class Can make a new type in C++ by declaring a class. A class is an expanded concept of a data structure: instead of holding.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Templates.
1 Announcements Note from admins: Edit.cshrc.solaris instead of.tcshrc Note from admins: Do not use delta.ece.
C++ Programming Lecture 11 Functions – Part III By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department.
A FIRST BOOK OF C++ CHAPTER 6 MODULARITY USING FUNCTIONS.
CS-1030 Dr. Mark L. Hornick 1 Basic C++ State the difference between a function/class declaration and a function/class definition. Explain the purpose.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Brief Edition Chapter 6 Functions.
1 Classes II Chapter 7 2 Introduction Continued study of –classes –data abstraction Prepare for operator overloading in next chapter Work with strings.
Object-Oriented Programming (OOP) and C++
Computer Programming II Lecture 5. Introduction to Object Oriented Programming (OOP) - There are two common programming methods : procedural programming.
C++ Lesson 1.
Eine By: Avinash Reddy 09/29/2016.
Inheritance Modern object-oriented (OO) programming languages provide 3 capabilities: encapsulation inheritance polymorphism which can improve the design,
Lecture 3 (UNIT -1) SUNIL KUMAR CIT-UPES.
Classes (Part 1) Lecture 3
Boston High School Education Project
Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes
C++ INTERVIEW QUESTIONS
Friend Class Friend Class A friend class can access private and protected members of other class in which it is declared as friend. It is sometimes useful.
Introduction to C++ Systems Programming.
Andy Wang Object Oriented Programming in C++ COP 3330
Chapter 14 Templates C++ How to Program, 8/e
Review: Two Programming Paradigms
Object Lifetime and Dynamic Objects
Instructor: Ioannis A. Vetsikas
This pointer, Dynamic memory allocation, Constructors and Destructor
Lecture 4-7 Classes and Objects
(5 - 1) Object-Oriented Programming (OOP) and C++
Pointers and References
Chapter 5 - Functions Outline 5.1 Introduction
Advanced Programming Basics
6 Chapter Functions.
Lecture 18 Arrays and Pointer Arithmetic
Operators.
Constructors and Other Tools
Dr. Bhargavi Dept of CS CHRIST
Classes and Objects.
Classes, Constructors, etc., in C++
Chapter 11 - Templates Outline Introduction Function Templates Overloading Function Templates Class Templates Class.
(5 - 1) Object-Oriented Programming (OOP) and C++
Operator Overloading Professor Hugh C. Lauer CS-2303, System Programming Concepts (Slides include materials from The C Programming Language, 2nd edition,
7 Arrays.
Based on slides created by Bjarne Stroustrup & Tony Gaddis
Submitted By : Veenu Saini Lecturer (IT)
Recitation Course 0603 Speaker: Liu Yu-Jiun.
CS410 – Software Engineering Lecture #5: C++ Basics III
Chapter 11 - Templates Outline Introduction Function Templates Overloading Function Templates Class Templates Class.
C++ Class Members Class Definition class Name { public: constructor(s)
C Language B. DHIVYA 17PCA140 II MCA.
Pointers and References
The Three Attributes of an Identifier
四時讀書樂 (春) ~ 翁森 山光照檻水繞廊,舞雩歸詠春風香。 好鳥枝頭亦朋友,落花水面皆文章。 蹉跎莫遣韶光老,人生唯有讀書好。
Introduction to Classes and Objects
Presentation transcript:

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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