Vectors CSci 588: Data Structures, Algorithms and Software Design Fall 2011 All material not from online sources copyright © Travis Desell, 2011

Slides:



Advertisements
Similar presentations
1 Linked lists Sections 3.2, 3.3, 3.5 Chapter 3 Lists, Stacks, and Queues Abstract Data Types, Vectors.
Advertisements

Hold data and provide access to it. Random-access containers: -Allow accessing any element by index -arrays, vectors Sequential containers: -Allow accessing.
Lecture 6 Sept 11, 2008 Goals for the day: Linked list and project # 1 list class in STL (section 3.3) stack – implementation and applications.
CSE Lecture 12 – Linked Lists …
Brown Bag #2 Advanced C++. Topics  Templates  Standard Template Library (STL)  Pointers and Smart Pointers  Exceptions  Lambda Expressions  Tips.
Beginning C++ Through Game Programming, Second Edition
Stack and Queue Dr. Bernard Chen Ph.D. University of Central Arkansas.
STL. What is STL? Standard Templates Library Templates are best used for –Defining containers for storing data –Some kinds of algorithms that work the.
COMP 171 Data Structures and Algorithms Tutorial 1 Template and STL.
Stacked Deque Gordon College Stacked Decks - get it?
1 Standard Containers: Lists Gordon College Resource:
Templates & STL Instructor: 小黑. Templates  Template serves as a class outline, from which specific classes are generated at compile time.  One template.
1 Queues and Priority Queues Chapter 8. 2 Introduction to Queues A queue is a waiting line – seen in daily life –Real world examples – toll booths, bank,
OOP Etgar 2008 – Recitation 101 Object Oriented Programming Etgar 2008 Recitation 10.
Lecture 11 Standard Template Library Stacks, Queue, and Deque Lists Iterators Sets Maps.
Data Structures Using C++ 2E
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy.
CNS  Sequences  vector,deque,list,(string),forward_list  Container Adapters  queue, stack, priority_queue  Associative Containers  set, unordered_set.
DATA STRUCTURES AND ALGORITHMS Lecture Notes 12 Prepared by İnanç TAHRALI.
1 Today’s Objectives  Announcements The Final Exam will be on Monday, 31-Jul, at 6 p.m. – There is no alternate time and no makeup!  Intro to the Standard.
COP3530 Data Structures600 Stack Stack is one the most useful ADTs. Like list, it is a collection of data items. Supports “LIFO” (Last In First Out) discipline.
Pointers OVERVIEW.
STL multimap Container. STL multimaps multimaps are associative containers –Link a key to a value –AKA: Hashtables, Associative Arrays –A multimap allows.
STL List // constructing lists #include int main () { // constructors used in the same order as described above: std::list first; // empty list of ints.
CSE 332: C++ STL containers Review: C++ Standard Template Library (STL) The STL is a collection of related software elements –Containers Data structures:
Templates code reuse - inheritance - template classes template classes - a class that is not data-type specific - eg. a class of Array of any type - intArray,
Chapter 9: Part 2: Vectors + Maps and STL Overview JPC and JWD © 2002 McGraw-Hill, Inc. Modified by S. Sudarshan.
An Introduction to STL. The C++ Standard Template Libraries  In 1990, Alex Stepanov and Meng Lee of Hewlett Packard Laboratories extended C++ with a.
CSS 332 PROGRAMMING ISSUES WITH OBJECT-ORIENTED LANGUAGES LECTURE
Iterator for linked-list traversal, Template & STL COMP171 Fall 2005.
Lists Chapter 8. 2 Linked Lists As an ADT, a list is –finite sequence (possibly empty) of elements Operations commonly include: ConstructionAllocate &
 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 8-3 : STL Algorithms. STL Algorithms The Standard Template Library not only contains container classes, but also algorithms that operate on sequence.
Lecture 7 : Intro. to STL (Standard Template Library)
1 STL Containers Copyright Kip Irvine, All rights reserved. Only students enrolled in a class at Florida International University may copy or print.
STL CSSE 250 Susan Reeder. What is the STL? Standard Template Library Standard C++ Library is an extensible framework which contains components for Language.
Mobility Research Lab mobility.ceng.metu.edu.tr Applied Innovative Interdisciplinary (AI2) Research Lab Short Course on Programming in C/C++
Input/Output CSci 588: Data Structures, Algorithms and Software Design Fall 2011 All material not from online sources copyright © Travis Desell, 2011
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.
ICOM 4035 – Data Structures Dr. Manuel Rodríguez Martínez Electrical and Computer Engineering Department Lecture 5 – September 4 th, 2001.
ECE 264 Object-Oriented Software Development Instructor: Dr. Honggang Wang Fall 2012 Lecture 20: Container classes; strings.
Glenn Stevenson CSIS 113A MSJC CSIS 123A Lecture 3 Vectors.
Vectors Updated 11/4/2003 by Kip Irvine. Copyright Kip Irvine Overview What is a vector? Declaring vector objects Inserting and removing items Using.
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.
Lecture 7-3 : STL Algorithms. STL Algorithms The Standard Template Library not only contains container classes, but also algorithms that operate on sequence.
CSCI  Sequence Containers – store sequences of values ◦ vector ◦ deque ◦ list  Associative Containers – use “keys” to access data rather than.
Standard Template Library a collection of useful tools.
Kruse/Ryba Ch071 Object Oriented Data Structures Searching STL Vector Sequential Search Binary Search Comparison Trees.
14-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN
Object-Oriented Programming (OOP) Lecture No. 41
Concepts of Programming Languages
Vectors Holds a set of elements, like an array
Standard Template Library (STL)
Collections Intro What is the STL? Templates, collections, & iterators
Abstract Data Types Iterators Vector ADT Sections 3.1, 3.2, 3.3, 3.4
Introduction to C++ STL
Lists - I The List ADT.
Lists - I The List ADT.
Copyright © – Curt Hill STL List Details Copyright © – Curt Hill.
Lecture 8 : Intro. to STL (Standard Template Library)
STL (Standard Template Library)
Standard Template Library
C++ Programming: chapter 10 – STL
Collections Intro What is the STL? Templates, collections, & iterators
Standard Template Library
An Introduction to STL.
8.3 Vectors Copyright © 2008 Pearson Addison-Wesley. All rights reserved. 1.
Vectors the better arrays.
A dictionary lookup mechanism
Presentation transcript:

Vectors CSci 588: Data Structures, Algorithms and Software Design Fall 2011 All material not from online sources copyright © Travis Desell,

Vector Vectors are part of c++’s standard template library (STL). This library contains a number of predefined classes and algorithms, with very efficient implementations.

Creating Vectors

// constructing vectors #include using namespace std; int main () { unsigned int i; // constructors used in the same order as described above: vector first; // empty vector of ints vector second (4,100); // four ints with value 100 vector third (second.begin(),second.end()); // iterating through second vector fourth (third); // a copy of third // the iterator constructor can also be used to construct from arrays: int myints[] = {16,2,77,29}; vector fifth (myints, myints + sizeof(myints) / sizeof(int) ); cout << "The contents of fifth are:"; for (i=0; i < fifth.size(); i++) cout << " " << fifth[i]; cout << endl; return 0; }

// vector assignment #include using namespace std; int main () { vector first (3,0); vector second (5,0); second=first; first=vector (); cout << "Size of first: " << int (first.size()) << endl; cout << "Size of second: " << int (second.size()) << endl; return 0; } Copying Vectors

Size, Capacity, Max Size Reserving Space for and Resizing Vectors

// vector::size #include using namespace std; int main () { vector myints; cout << "0. size: " << (int) myints.size() << endl; for (int i=0; i<10; i++) myints.push_back(i); cout << "1. size: " << (int) myints.size() << endl; myints.insert (myints.end(),10,100); cout << "2. size: " << (int) myints.size() << endl; myints.pop_back(); cout << "3. size: " << (int) myints.size() << endl; return 0; } Size of a Vector

// comparing size, capacity and max_size #include using namespace std; int main () { vector myvector; // set some content in the vector: for (int i=0; i<100; i++) myvector.push_back(i); cout << "size: " << (int) myvector.size() << "\n"; cout << "capacity: " << (int) myvector.capacity() << "\n"; cout << "max_size: " << (int) myvector.max_size() << "\n"; return 0; } Capacity and max size of a Vector

// vector::empty #include using namespace std; int main () { vector myvector; int sum (0); for (int i=1;i<=10;i++) myvector.push_back(i); while (!myvector.empty()) { sum += myvector.back(); myvector.pop_back(); } cout << "total: " << sum << endl; return 0; } Checking to see if a Vector is Empty

// resizing vector #include using namespace std; int main () { vector myvector; unsigned int i; // set some initial content: for (i=1;i<10;i++) myvector.push_back(i); myvector.resize(5); myvector.resize(8,100); myvector.resize(12); cout << "myvector contains:"; for (i=0;i<myvector.size();i++) cout << " " << myvector[i]; cout << endl; return 0; } Resizing a Vector

// resizing vector #include using namespace std; int main () { vector myvector; unsigned int i; // set some initial content: for (i=1;i<10;i++) myvector.push_back(i); myvector.resize(5); myvector.resize(8,100); myvector.resize(12); cout << "myvector contains:"; for (i=0;i<myvector.size();i++) cout << " " << myvector[i]; cout << endl; return 0; } Resizing a Vector resize adds or drops elements from a vector, but will not change it’s capacity.

// vector::reserve #include using namespace std; int main () { vector content; size_t filesize; ifstream file ("test.bin",ios::in|ios::ate|ios::binary); if (file.is_open()) { filesize=file.tellg(); content.reserve(filesize); file.seekg(0); while (!file.eof()) { content.push_back( file.get() ); } // print out content: vector ::iterator it; for (it=content.begin() ; it<content.end() ; it++) cout << hex << *it; } return 0; } Reserving more space for a Vector

Passing Vectors to Functions

#include using namespace std; void call_by_value_test(vector v) { v[0] = 3; v[1] = 6; v[2] = 9; v[3] = 12; } void call_by_reference_test(vector &v) { v[0] = 3; v[1] = 6; v[2] = 9; v[3] = 12; } int main() { vector v1(4,1); cout << "initial v1 -- " << v1[0] << " " << v1[1] << " " << v1[2] << " " << v1[3] << endl; call_by_value_test(v1); cout << "after call by value test -- " << v1[0] << " " << v1[1] << " " << v1[2] << " " << v1[3] << endl; call_by_reference_test(v1); cout << "after call by reference test -- " << v1[0] << " " << v1[1] << " " << v1[2] << " " << v1[3] << endl; }

Iterating over Vectors

Possible Iterator Positions

// vector::begin #include using namespace std; int main () { vector myvector; for (int i=1; i<=5; i++) myvector.push_back(i); vector ::iterator it; cout << "myvector contains:"; for ( it=myvector.begin() ; it < myvector.end(); it++ ) cout << " " << *it; cout << endl; return 0; } iterating over vectors

// vector::end #include using namespace std; int main () { vector myvector; for (int i=1; i<=5; i++) myvector.insert(myvector.end(),i); cout << "myvector contains:"; vector ::iterator it; for ( it=myvector.begin() ; it < myvector.end(); it++ ) cout << " " << *it; cout << endl; return 0; } iterating over vectors 2

// vector::rbegin/rend #include using namespace std; int main () { vector myvector; for (int i=1; i<=5; i++) myvector.push_back(i); cout << "myvector contains:"; vector ::reverse_iterator rit; for ( rit=myvector.rbegin() ; rit < myvector.rend(); ++rit ) cout << " " << *rit; cout << endl; return 0; } reverse iteration over vectors

// inserting into a vector #include using namespace std; int main () { vector myvector (3,100); vector ::iterator it; it = myvector.begin(); it = myvector.insert ( it, 200 ); myvector.insert (it,2,300); // "it" no longer valid, get a new one: it = myvector.begin(); vector anothervector (2,400); myvector.insert (it+2,anothervector.begin(),anothervector.end()); int myarray [] = { 501,502,503 }; myvector.insert (myvector.begin(), myarray, myarray+3); cout << "myvector contains:"; for (it=myvector.begin(); it<myvector.end(); it++) cout << " " << *it; cout << endl; return 0; } inserting at an iterator

// erasing from vector #include using namespace std; int main () { unsigned int i; vector myvector; // set some values (from 1 to 10) for (i=1; i<=10; i++) myvector.push_back(i); // erase the 6th element myvector.erase (myvector.begin()+5); // erase the first 3 elements: myvector.erase (myvector.begin(),myvector.begin()+3); cout << "myvector contains:"; for (i=0; i<myvector.size(); i++) cout << " " << myvector[i]; cout << endl; return 0; } erasing at an iterator

myvector.at(n) vs myvector[n]

#include using namespace std; int main() { vector myvector(10); myvector[11] = 200; // this may or may not crash; if // it does it will not tell you why myvector.at(10) = 200; // this will crash with an error // saying you tried to access something // outside of the bounds of the vector } at vs [] at is much safer than using [], but it is a little slower. In general, use at unless you have fully debugged your code and have a need for as much performance as possible.

Vectors as Stacks

// vector::push_back #include using namespace std; int main () { vector myvector; int myint; cout << "Please enter some integers (enter 0 to end):\n"; do { cin >> myint; myvector.push_back (myint); } while (myint); cout << "myvector stores " << (int) myvector.size() << " numbers.\n"; return 0; } pushing to the back of the vector

// vector::pop_back #include using namespace std; int main () { vector myvector; int sum (0); myvector.push_back (100); myvector.push_back (200); myvector.push_back (300); while (!myvector.empty()) { sum+=myvector.back(); myvector.pop_back(); } cout << "The elements of myvector summed " << sum << endl; return 0; } removing the back of the vector

// vector::front #include using namespace std; int main () { vector myvector; myvector.push_back(78); myvector.push_back(16); // now front equals 78, and back 16 myvector.front() -= myvector.back(); cout << "myvector.front() is now " << myvector.front() << endl; return 0; } accessing the front of the vector

// vector::back #include using namespace std; int main () { vector myvector; myvector.push_back(10); while (myvector.back() != 0) { myvector.push_back ( myvector.back() -1 ); } cout << "myvector contains:"; for (unsigned i=0; i<myvector.size() ; i++) cout << " " << myvector[i]; cout << endl; return 0; } accessing the back of the vector

Clearing and Assigning Vectors

// clearing vectors #include using namespace std; int main () { unsigned int i; vector myvector; myvector.push_back (100); myvector.push_back (200); myvector.push_back (300); cout << "myvector contains:"; for (i=0; i<myvector.size(); i++) cout << " " << myvector[i]; myvector.clear(); cout << "myvector contains:"; for (i=0; i<myvector.size(); i++) cout << " " << myvector[i]; myvector.push_back (1101); myvector.push_back (2202); cout << "\nmyvector contains:"; for (i=0; i<myvector.size(); i++) cout << " " << myvector[i]; cout << endl; return 0; } Clearing a Vector

// vector assign #include using namespace std; int main () { vector first; vector second; vector third; first.assign (7,100); // a repetition 7 times of value 100 vector ::iterator it; it=first.begin()+1; second.assign (it,first.end()-1); // the 5 central values of first int myints[] = {1776,7,4}; third.assign (myints,myints+3); // assigning from array. cout << "Size of first: " << int (first.size()) << endl; cout << "Size of second: " << int (second.size()) << endl; cout << "Size of third: " << int (third.size()) << endl; return 0; } Assigning a Vector

Operations on Vectors

// sort algorithm example #include using namespace std; bool myfunction (int i,int j) { return (i<j); } struct myclass { bool operator() (int i,int j) { return (i<j);} } myobject; int main () { int myints[] = {32,71,12,45,26,80,53,33}; vector myvector (myints, myints+8); // vector ::iterator it; // using default comparison (operator <): sort (myvector.begin(), myvector.begin()+4); //( ) // using function as comp sort (myvector.begin()+4, myvector.end(), myfunction); // ( ) // using object as comp sort (myvector.begin(), myvector.end(), myobject); //( ) // print out content: cout << "myvector contains:"; for (it=myvector.begin(); it!=myvector.end(); ++it) cout << " " << *it; cout << endl; return 0; } Sorting a Vector

// binary_search example #include using namespace std; bool myfunction (int i,int j) { return (i<j); } int main () { int myints[] = {1,2,3,4,5,4,3,2,1}; vector v(myints,myints+9); // // using default comparison: sort (v.begin(), v.end()); cout << "looking for a 3... "; if (binary_search (v.begin(), v.end(), 3)) cout << "found!\n"; else cout << "not found.\n"; // using myfunction as comp: sort (v.begin(), v.end(), myfunction); cout << "looking for a 6... "; if (binary_search (v.begin(), v.end(), 6, myfunction)) cout << "found!\n"; else cout << "not found.\n"; return 0; } Binary Search on a Vector

// random_shuffle example #include using namespace std; // random generator function: ptrdiff_t myrandom (ptrdiff_t i) { return rand()%i;} // pointer object to it: ptrdiff_t (*p_myrandom)(ptrdiff_t) = myrandom; int main () { srand ( unsigned ( time (NULL) ) ); vector myvector; vector ::iterator it; // set some values: for (int i=1; i<10; ++i) myvector.push_back(i); // // using built-in random generator: random_shuffle ( myvector.begin(), myvector.end() ); // using myrandom: random_shuffle ( myvector.begin(), myvector.end(), p_myrandom); // print out content: cout << "myvector contains:"; for (it=myvector.begin(); it!=myvector.end(); ++it) cout << " " << *it; cout << endl; return 0; } Randomize/Shuffle a Vector

// merge algorithm example #include using namespace std; int main () { int first[] = {5,10,15,20,25}; int second[] = {50,40,30,20,10}; vector v(10); vector ::iterator it; sort (first,first+5); sort (second,second+5); merge (first,first+5,second,second+5,v.begin()); cout << "The resulting vector contains:"; for (it=v.begin(); it!=v.end(); ++it) cout << " " << *it; cout << endl; return 0; } Merging Vectors