Vectors the better arrays. Why Vectors l vectors are implemented as a class (a template to be exact) l they serve the same purpose as arrays but using.

Slides:



Advertisements
Similar presentations
Chapter 19 Standard Template Library. Copyright © 2006 Pearson Addison-Wesley. All rights reserved Learning Objectives Iterators Constant and mutable.
Advertisements

Linked Lists: deleting...
SEG4110 – Advanced Software Design and Reengineering TOPIC J C++ Standard Template Library.
Brown Bag #2 Advanced C++. Topics  Templates  Standard Template Library (STL)  Pointers and Smart Pointers  Exceptions  Lambda Expressions  Tips.
. STL: C++ Standard Library (continued). STL Iterators u Iterators are allow to traverse sequences u Methods  operator*  operator->  operator++, and.
Introduction to Linked Lists In your previous programming course, you saw how data is organized and processed sequentially using an array. You probably.
C++ Templates. What is a template? Templates are type-generic versions of functions and/or classes Template functions and template classes can be used.
Exceptions, Templates, And The Standard Template Library (STL) Chapter 16.
Copyright © 2012 Pearson Education, Inc. Chapter 16: Exceptions, Templates, and the Standard Template Library (STL)
Pointers Revisited l What is variable address, name, value? l What is a pointer? l How is a pointer declared? l What is address-of (reference) and dereference.
Chapter 9. 2 Objectives You should be able to describe: Addresses and Pointers Array Names as Pointers Pointer Arithmetic Passing Addresses Common Programming.
Lecture 20 “Standard” Template Library. What is the Standard Template Library? A collection of C++ classes (templates) containers vectors lists stacks.
Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 9 Pointers and Dynamic Arrays.
Rossella Lau Lecture 2, DCO20105, Semester A, DCO Data structures and algorithms  Lecture 2: Vector  Array and vector  Internal structure.
Chapter 5: Control Structures II (Repetition)
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 11a. The Vector Class.
CSE 332: C++ templates and generic programming I Motivation for Generic Programming in C++ We’ve looked at procedural programming –Reuse of code by packaging.
Lecture 11 Standard Template Library Stacks, Queue, and Deque Lists Iterators Sets Maps.
C++ / G4MICE Course Session 3 Introduction to Classes Pointers and References Makefiles Standard Template Library.
Dr. Yingwu Zhu STL Vector and Iterators. STL (Standard Template Library) 6:14:43 AM 2 A library of class and function templates Components: 1. Containers:
Data Structures Using C++ 2E
Chapter 5: Control Structures II (Repetition)
CHAPTER 5: CONTROL STRUCTURES II INSTRUCTOR: MOHAMMAD MOJADDAM.
EGR 2261 Unit 5 Control Structures II: Repetition  Read Malik, Chapter 5.  Homework #5 and Lab #5 due next week.  Quiz next week.
CSE 332: C++ Type Programming: Associated Types, Typedefs and Traits A General Look at Type Programming in C++ Associated types (the idea) –Let you associate.
Project 1 Due Date: September 25 th Quiz 4 is due September 28 th Quiz 5 is due October2th 1.
CSE 232: C++ pointers, arrays, and references Overview of References and Pointers Often need to refer to another object –Without making a copy of the object.
Arrays and ArrayLists in Java L. Kedigh. Array Characteristics List of values. A list of values where every member is of the same type. Each member in.
Software Design 1.1 Tapestry classes -> STL l What’s the difference between tvector and vector  Safety and the kitchen sink What happens with t[21] on.
Chapter 5: Control Structures II (Repetition). Objectives In this chapter, you will: – Learn about repetition (looping) control structures – Learn how.
CS Midterm Study Guide Fall General topics Definitions and rules Technical names of things Syntax of C++ constructs Meaning of C++ constructs.
Friends & Standard Template Library CSCI3110 Advanced Data Structures Lecturer: Dr. Carroll and Nan Chen.
CPSC 252 Operator Overloading and Convert Constructors Page 1 Operator overloading We would like to assign an element to a vector or retrieve an element.
ArrayList Class An ArrayList is an object that contains a sequence of elements that are ordered by position. An ArrayList is an object that contains a.
Chapter 13 – C++ String Class. String objects u Do not need to specify size of string object –C++ keeps track of size of text –C++ expands memory region.
C++ Programming Part 2 Michael Griffiths Corporate Information and Computing Services The University of Sheffield
Slide 1 Linked Data Structures. Slide 2 Learning Objectives  Nodes and Linked Lists  Creating, searching  Linked List Applications  Stacks, queues.
1 Arrays and Vectors Chapter 7 Arrays and Vectors Chapter 7.
CPSC 252 The Big Three Page 1 The “Big Three” Every class that has data members pointing to dynamically allocated memory must implement these three methods:
Iterator for linked-list traversal, Template & STL COMP171 Fall 2005.
 2003 Prentice Hall, Inc. All rights reserved.m ECE 2552 Dr. Këpuska based on Dr. S. Kozaitis Summer Chapter 15 - Class string and String Stream.
Lecture 11 Standard Template Library Lists Iterators Sets Maps.
Copyright 2004 Scott/Jones Publishing Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 8 Arrays.
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
STL CSSE 250 Susan Reeder. What is the STL? Standard Template Library Standard C++ Library is an extensible framework which contains components for Language.
1 Chapter 3 Lists, Stacks, and Queues Reading: Sections 3.1, 3.2, 3.3, 3.4 Abstract Data Types (ADT) Iterators Implementation of Vector.
CSE 332: C++ pointers, arrays, and references Overview of Pointers and References Often need to refer to another object –Without making a copy of the object.
Vectors CSci 588: Data Structures, Algorithms and Software Design Fall 2011 All material not from online sources copyright © Travis Desell, 2011
Glenn Stevenson CSIS 113A MSJC CSIS 123A Lecture 3 Vectors.
Chapter 17 – Templates. Function Templates u Express general form for a function u Example: template for adding two numbers Lesson 17.1 template Type.
Vectors Updated 11/4/2003 by Kip Irvine. Copyright Kip Irvine Overview What is a vector? Declaring vector objects Inserting and removing items Using.
Standard Template Library a collection of useful tools.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Function Templates 16.2.
CPSC 252 ADTs and C++ Classes Page 1 Abstract data types (ADTs) An abstract data type is a user-defined data type that has: private data hidden inside.
1 The Standard Template Library The STL is a collection of Container classes These are class templates for containers. A container is an object that stores.
CMSC 202 Computer Science II for Majors. CMSC 202UMBC Topics Templates Linked Lists.
Pointers. What Is Pointer l every variable has memory address char c=’y’; int i=2; address of variable i is 0022 l address can used to refer to this variable.
Generic Programming in C
Vectors Holds a set of elements, like an array
CSCE 210 Data Structures and Algorithms
Pointers.
CS Computer Science IB: Object Oriented Programming
Pointers Revisited What is variable address, name, value?
Starting Out with C++ Early Objects Eighth Edition
Collections Intro What is the STL? Templates, collections, & iterators
Introduction to Linked Lists
Vectors the better arrays.
COP 3330 Object-oriented Programming in C++
Collections Intro What is the STL? Templates, collections, & iterators
Vectors the better arrays.
Presentation transcript:

Vectors the better arrays

Why Vectors l vectors are implemented as a class (a template to be exact) l they serve the same purpose as arrays but using object oriented mechanisms (such as operator overloading) made more powerful l vectors can n can grow and shrink as needed n can be compared, assigned as a whole n can be passed by reference/value/returned n vector size is always available n still more … l part of so called Standard Template Library (STL) l once you learned vectors, do not use (raw) arrays 2

Declaration include header file using std::vector; l to declare vector vectorName ; where typeParameter – type/class of vector elements –corresponds to base type of the array examples vector items; // declares vector with no elements vector items(5); // declares vector with 5 elements vector items(5); // declares a vector of 5 objects of myclass 3

Typical Array Operations indexing: items[3] sill cannot refer past vector size: items[6]++; // range error checking size: items.size() careful with this one: returns value of type size_t l example: for(size_t i=0; i < items.size(); ++i) cout << items[i]; 4

Atypical Array Operations adding element: items.push_back(55); removing element: items.pop_back(); checking if empty: items.empty(); accessing first/last element: items.front(); items.back(); changing size: items.resize(newSize); emptying: items.erase(); l example: int num=0; cin >> num; while(num !=0){ items.push_back(num); cin >> num; } while(!items.empty()){ cout << items.back(); items.pop_back(); } 5

With Functions, Other Aggregate Operations l can pass by value/reference, return void myfunc(vector ); void myfunc(vector &); vector myfunc(); l can assign vector v; v = items; can swap: items.swap(v); can compare: if(v == items) … 6

With Objects class intData{ // elementary class definition public: void set(int n){data=n;} // simple setter int get() const{return data;} // simple accessor private: int data; }; … vector v(5); // declaring a vector of objects for(int i=0; i<5; ++i){ // using vector as array int num; cin >> num; v[i].set(num); // invoking a method on vector element } 7

Iterators l iterator is a generalization of pointer n not a pointer but usually implemented using pointers further enhances the power of vector l declaring iterator vector ::iterator iteratorName ; where typeParameter – type/class of elements l example vector ::iterator ip; 8

Iterators Operations l operations ++ (pre- and postfix) and -- to advance to the next (previous) data item advance certain number of positions forward/backward = = and != operators to test whether two iterators point to the same data item to compare if two elements are before or after in the vector dereferencing ( * ) provides data item access l functions v.begin() returns an iterator pointing to the first element of container v v.end() returns an iterator pointing past the last element of container v useful to compare for end of iteration inserting: v.insert(ip, 22); // inserts one element at // iterator ip position what does this do? v.insert(v.end()-2, 55); erasing: v.erase(ip); // erases one element at // iterator ip position sorting elements: sort(v.begin(),v.end()); need algorithm header l caution: after using iterator for update, iterators are invalidated, have to reassign 9

Iterator Usage Example vector v; // declare vector … for ( // declare and initialize iterator vector ::iterator p = v.begin(); p != v.end(); // check if end is not reached ++p // move iterator to next element ){ cout << *p; // manipulate element in loop body } 10

Typedef l variable declarations can get long and obscure program meaning typedef – allows to give names to already defined types and classes n note: no new types declared l benefits: shortens the code, gives more intuitive names, adds portability – can change defined type later if needed l syntax: typedef existingType newType; example typedef vector myVector; typedef myVector::iterator myVectorIterator; myVector v; for (myVectorIterator p=v.begin(); p != v.end(); ++p){ cout << *p; do not overdo – typedef s hide original types: give new types intuitive names, do not use for short/understandable types 11

Questions on Vectors l why use vectors instead of arrays? what header file is needed to use vectors? l how is vector declared? how to declare a vector of five integers? how can one determine the size of the vector? What is the size of this vector vector myvector(4); l how does one add/remove elements from a vector? l how does one get the first/last element from a vector? l can vectors be assigned to each other? What happens to their size? contents? compared with each other? when are they equal? l can vectors be passed by value? reference? returned? l can vectors contain objects? l what is iterator? how is it used? what is typedef ? How is it used? What are begin() and end() ? 12