Complex data types Structures Defined types Structures and functions Structures and pointers (Very) brief introduction to the STL

Similar documents
GE U111 Engineering Problem Solving & Computation Lecture 6 February 2, 2004

Arrays. Returning arrays Pointers Dynamic arrays Smart pointers Vectors

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program

Chapter 2: Basic Elements of C++

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction

Lab 2: Pointers. //declare a pointer variable ptr1 pointing to x. //change the value of x to 10 through ptr1

Lab Instructor : Jean Lai

Stack memory - "scratch pad" memory that is used by automatic variables.

! Pass by value: when an argument is passed to a. ! It is implemented using variable initialization. ! Changes to the parameter in the function body

Pointers, Dynamic Data, and Reference Types

Functions, Arrays & Structs

Basic memory model Using functions Writing functions. Basics Prototypes Parameters Return types Functions and memory Names and namespaces

Object Oriented Software Design II

C++ Structures Programming Workshop 2 (CSCI 1061U)

21. Exceptions. Advanced Concepts: // exceptions #include <iostream> using namespace std;

Chapter-14 STRUCTURES

BTE2313. Chapter 2: Introduction to C++ Programming

CS31 Discussion. Jie(Jay) Wang Week8 Nov.18

Pointers II. Class 31

Pointers. Addresses in Memory. Exam 1 on July 18, :00-11:40am

cout << "How many numbers would you like to type? "; cin >> memsize; p = new int[memsize];

Linked List using a Sentinel

C++ Programming: From Problem Analysis to Program Design, Third Edition

Arrays and functions Multidimensional arrays Sorting and algorithm efficiency

Functions, Arrays & Structs

Chapter 11: Structured Data

CSC1322 Object-Oriented Programming Concepts

Lab # 02. Basic Elements of C++ _ Part1

Binomial pricer (1.1)

Objectives. In this chapter, you will:

CMSC 313 COMPUTER ORGANIZATION & ASSEMBLY LANGUAGE PROGRAMMING LECTURE 13, SPRING 2013

The American University in Cairo Department of Computer Science & Engineering CSCI &09 Dr. KHALIL Exam-I Fall 2011

Getting started with C++ (Part 2)

3/22/2016. Pointer Basics. What is a pointer? C Language III. CMSC 313 Sections 01, 02. pointer = memory address + type

WHAT POINTERS REALLY ARE

10/20/2015. Midterm Topic Review. Pointer Basics. C Language III. CMSC 313 Sections 01, 02. Adapted from Richard Chang, CMSC 313 Spring 2013

Chapter 11: Structured Data

Review of Important Topics in CS1600. Functions Arrays C-strings

Program Organization and Comments

Object Reference and Memory Allocation. Questions:

Kingdom of Saudi Arabia Princes Nora bint Abdul Rahman University College of Computer Since and Information System CS242 ARRAYS

Algorithms for Arrays Vectors Pointers CS 16: Solving Problems with Computers I Lecture #14

CS242 COMPUTER PROGRAMMING

Structured Data. CIS 15 : Spring 2007

Short Notes of CS201

LAB 4.1 Relational Operators and the if Statement

By the end of this section you should: Understand what the variables are and why they are used. Use C++ built in data types to create program

Consider the above code. This code compiles and runs, but has an error. Can you tell what the error is?

FORM 1 (Please put your name and section number (001/10am or 002/2pm) on the scantron!!!!) CS 161 Exam II: True (A)/False(B) (2 pts each):

COEN244: Class & function templates

2.1. Chapter 2: Parts of a C++ Program. Parts of a C++ Program. Introduction to C++ Parts of a C++ Program

CS201 - Introduction to Programming Glossary By

CS24 Week 3 Lecture 1

Data Structures using OOP C++ Lecture 3

[CSE10200] Programming Basis ( 프로그래밍기초 ) Chapter 9. Seungkyu Lee. Assistant Professor, Dept. of Computer Engineering Kyung Hee University

CS 31 Discussion 1A, Week 8. Zengwen Yuan (zyuan [at] cs.ucla.edu) Humanities A65, Friday 10:00 11:50 a.m.

Fundamentals of Programming. Lecture 19 Hamed Rasifard

C++ Programming Fundamentals

Chapter 11: Abstract Data Types. Abstraction and Data Types. Combining Data into Structures 8/23/2014. Abstract Data Types

BEng (Hons) Electronic Engineering. Resit Examinations for / Semester 1

1. In C++, reserved words are the same as predefined identifiers. a. True

CMSC 313 COMPUTER ORGANIZATION & ASSEMBLY LANGUAGE PROGRAMMING LECTURE 13, FALL 2012

Computer Programming : C++

calling a function - function-name(argument list); y = square ( z ); include parentheses even if parameter list is empty!

THE GOOD, BAD AND UGLY ABOUT POINTERS. Problem Solving with Computers-I

CE221 Programming in C++ Part 2 References and Pointers, Arrays and Strings

Computer Programming

CS201- Introduction to Programming Current Quizzes

Pointers and References

Welcome Back. CSCI 262 Data Structures. Hello, Let s Review. Hello, Let s Review. How to Review 1/9/ Review. Here s a simple C++ program:

Why VC++ instead of Dev C++?

Agenda. The main body and cout. Fundamental data types. Declarations and definitions. Control structures

Structures. Lecture 15 COP 3014 Spring April 16, 2018

Object-Oriented Programming for Scientific Computing

SFU CMPT Topic: Control Statements

CHAPTER 3 BASIC INSTRUCTION OF C++

OBJECT ORIENTED PROGRAMMING

CS2141 Software Development using C/C++ C++ Basics

Introduction to Programming using C++

Principles of Programming Pointers, Dynamic Memory Allocation, Character Arrays, and Buffer Overruns

G52CPP C++ Programming Lecture 18

Computer Programming

Pointers, Arrays and C-Strings

A Quick Look at C for C++ Programmers

Absolute C++ Walter Savitch

Pointers. Variable Declaration. Chapter 10

LECTURE 11 STRUCTURED DATA

CS201 Some Important Definitions

The American University in Cairo Computer Science & Engineering Department CSCE Dr. KHALIL Exam II Spring 2010

Reference operator (&)

Today USING POINTERS. Functions: parameters and arguments. Todaywewilllookattopicsrelatingtotheuseofpointers

CS 231 Data Structures and Algorithms, Fall 2016

Lesson 2 Variables and I/O

Non-numeric types, boolean types, arithmetic. operators. Comp Sci 1570 Introduction to C++ Non-numeric types. const. Reserved words.

Introduction Of Classes ( OOPS )

Input And Output of C++

UEE1302 (1102) F10 Introduction to Computers and Programming (I)

Chapter 6: User-Defined Functions. Objectives (cont d.) Objectives. Introduction. Predefined Functions 12/2/2016

Basic program The following is a basic program in C++; Basic C++ Source Code Compiler Object Code Linker (with libraries) Executable

Pointers. Reference operator (&) ted = &andy;

Transcription:

Complex data types Structures Defined types Structures and functions Structures and pointers (Very) brief introduction to the STL

Many programs require complex data to be represented That cannot easily be represented using base type variables and arrays Base types are the defined C++ types like int, char, float, etc. C++ allows structures to be defined and used in a program A structure is a complex type that collects a number of variables, arrays or even other structures

Let s assume that we want to represent student data for a small university For each student we want to maintain First name a string Last name a string Student number an integer GPA a float this is a simplified version of what would be necessary, some of the complicating issues will be discussed later

If we wanted to maintain a list of a hundred students we could use four separate arrays One for each of the four attributes First name, last name, student number, GPA Referred to as parallel arrays Whenever we want to retrieve student data we would use the same index in all arrays

index 0 1 2... 33... 97 98 99 id 9101 7234 5678 4864 1789 2457 4444 index 0 1 2... 33... 97 98 99 first Bob Kate Sue Dave Joe Ella Anna index 0 1 2... 33... 97 98 99 last Wing Smith Abel Dodd Ng Moss Frenc index 0 1 2... 33... 97 98 99 gpa 3.00 3.50 2.75 3.75 2.25 4.00 3.50 Represents the student Dave Dodd

Maintaining parallel arrays can be fiddly We must make consistent changes to all arrays If we delete an element from one, elements at the same index must be deleted from the others If we sort one array then all the other arrays must be sorted in the same way Passing student data to functions is tedious A function to print student data needs four parameters Or we can use structures Or classes

Parallel arrays with sample data assume we want to sort by ID index 0 1 2 3 4 5 6 7 8 id 9101 7234 5678 4475 4864 3459 1789 2457 4444 index 0 1 2 3 4 5 6 7 8 first Bob Kate Sue Alan Dave Joy Joe Ella Anna index 0 1 2 3 4 5 6 7 8 last Wing Smith Abel Flim Dodd Shae Ng Moss Frenc index 0 1 2 3 4 5 6 7 8 gpa 3.00 3.50 2.75 2.00 3.75 3.50 2.25 4.00 3.50

Sort ID array The data is now corrupt students no longer have the right IDs index 0 1 2 3 4 5 6 7 8 id 9101 1789 2457 7234 3459 5678 4444 4475 4864 4475 4864 3459 5678 1789 2457 7234 4444 9101 index 0 1 2 3 4 5 6 7 8 first Bob Kate Sue Alan Dave Joy Joe Ella Anna index 0 1 2 3 4 5 6 7 8 last Wing Smith Abel Flim Dodd Shae Ng Moss Frenc index 0 1 2 3 4 5 6 7 8 gpa 3.00 3.50 2.75 2.00 3.75 3.50 2.25 4.00 3.50

A structure declaration defines a complex type keyword student member variables struct Student { int id; string first; string last; float gpa; }; structure name ending ;

A structure declaration describes what data types are associated with a struct It does not allocate space for any variables It is like a blueprint for a type Space is allocated when a variable is declared Student st1; Instructs the compiler to reserve space for an int, two strings and a float These four components of st1 are allocated memory on the stack in sequence

It is common for struct definitions to appear outside any function including main So that they are available anywhere in the file If a struct is defined inside a function it is only available in that function Variables of a struct type are declared wherever they are needed Just like any other variable

A structure can be initialized in much the same way as an array Using a comma separated list of values enclosed in curly brackets Student st1 = { 123, "bob", "bobson", 2.5 };

Variables of a structure have to be accessed individually using the member operator (.) To access a structure variable use the structure name and the variable name separated by a dot s1.id = 12345; They can then be used like any variable of the same type And can be accessed, assigned new values, passed to functions and so on

We will look at an example that enters and prints student data The student structure is declared A student variable is defined The user is requested to enter values for the structure attributes The student data is printed

declares the student structure #include "<iostream>" #include "<string>" using namespace std; // Student structure struct Student { int id; string first; string last; float gpa; }; the student structure // Forward Declarations void printstudent(student st);

int main() { Student s1; cout << "Enter ID: "; cin >> s1.id; cout << "Enter first name: "; cin >> s1.first; cout << "Enter last name: "; cin >> s1.last; cout << "Enter GPA: "; cin >> s1.gpa; cout << endl; the one and only student use dot notation to access student attributes (member variables) } printstudent(s1); return 0; call the print function

and finally the print function definition note: passed by value void printstudent(student st) { cout << st.id; cout << " " << st.first << " " << st.last; cout << " GPA: " << st.gpa; }

Structures can be used as function parameters and arguments In the same way as any other variable Parameter passing is pass by value Structure variables are not pointers Unlike array variables When a structure is passed to a function the parameter is a copy of the original Even if the original structure contained arrays!

It is possible to create arrays of structures They are declared like any other kind of array e.g. Student class[100]; Individual elements are also accessed like any other array struct attributes are accessed with dot notation Let's say we want to find the first name of the student with index 15 class[15].first not class.first[15]...

Unlike arrays, one structure can be assigned to another structure of the same type Again, even if the structure contains an array A note on memory allocation A structure might include an array in dynamic memory It's array variable is really a pointer to that array Pointer size is constant, even though the size of arrays in two different structures might vary Two structures that contain different sized arrays are still the same size in bytes

Let s make the example more complex It isn t realistic to just record GPA GPA is calculated from the grades that a student receives for courses We will create a simple course structure Department (like CMPT) Number (like 130) Grade (A, B, C, D and F)

Here is the course structure // Course structure struct Course { string department; int number; char grade; }; it is perfectly OK to nest structures and to make arrays of structures And the revised student structure struct Student { int id; string first; string last; Course* grades; int coursestaken; int maxcourses } ; an array of courses!

There is an issue with the Student structure What happens with the array of courses when we create a new Student? The array has not yet been created by calling new So the array variable should be set to NULL or nullptr It is possible to define methods for C++ structures Functions that belong to the structure We will write a constructor for Student

struct Student { int id; string first; string last; Course* grades; int coursestaken; int maxcourses; }; Student() { id = 0; first = last = ""; grades = NULL; coursestaken = 0; maxcourses = 0; } The revised student structure This is the definition of the constructor for a Student it sets the initial values of the attributes Note that there is no return type

A constructor is a special kind of function That is used to initialize the member variables of a struct or a class It is called automatically whenever a new Student variable is created Student s1; Setting the array to NULL allows us to write a function to insert values into a student To recognize that the array has not been created And create the array using new

The Student struct still has some issues We need two variables to deal with the array size maxcourses records the actual size of the array Which could be increased if necessary coursestaken records the number of courses that the student has actually taken We would need to write an insertion function to ensure that these values are set correctly And that the array is created Using a vector instead of an array would simplify some of these issues