introduction to stl and the vector container class cs342 data structures based on ford & topp

31
Introduction to STL and the vector container class CS342 Data Structures Based on Ford & Topp

Upload: vanessa-newton

Post on 31-Dec-2015

244 views

Category:

Documents


4 download

TRANSCRIPT

Page 1: Introduction to STL and the vector container class CS342 Data Structures Based on Ford & Topp

Introduction to STL and the vector container class

CS342 Data StructuresBased on Ford & Topp

Page 2: Introduction to STL and the vector container class CS342 Data Structures Based on Ford & Topp

Intro to STL (Standard Template Library) container classes Data structure: a container of data that

supports insertion, deletion, and updating operations on the stored data.

Classical data structures such as vector; queue, deque, and priority queue; list, stack; set and multiset, map and multimap have been pre-programmed as template classes and integrated into C++ as STL.

Page 3: Introduction to STL and the vector container class CS342 Data Structures Based on Ford & Topp

Categories of STL container classesSequence containers

Adapter containers

associative containers

vector stack set and multiset

deque queue map and multimap

list priority-queue

Sequence containers: data elements stored in linear order.

Adapter container: contains another container (usually a sequence container) as its underlying storage structure.

Associative container: stores elements by keys such as Id numbers.

Page 4: Introduction to STL and the vector container class CS342 Data Structures Based on Ford & Topp

Illustrations of STL sequence containers

P o s itio n 0 P o s itio n 4P o s itio n 3P o s itio n 2P o s itio n 1

S eq uenc e C o ntainer

fro n t rear

n ext n extn extn ext

v [ 0 ] v [ 1 ] v [ 2 ] . . . v [ n-1 ] ro o m to gro w

0 1 2 n-1

Linked list

Vertor

Page 5: Introduction to STL and the vector container class CS342 Data Structures Based on Ford & Topp

Illustrations of STL adapter containers (using sequence containers as the storage)

A top

P ush A

top

P ush B P ush C

(a )

C

BA

top

P op C

(b )

B

A top

P op B

topB

A

CBA

A B C D

E

B C D E

A

rear fro ntIns ert D elete

Page 6: Introduction to STL and the vector container class CS342 Data Structures Based on Ford & Topp

Illustrations of STL associative containers

5

3

1

1527

S et A

F o rd

B uic k

H o nd a

S et B

B M W

Jeep

Jaguar

D 7 B -9 1 6

W 9 1 -A 8 3

4 .9 5

1 2 .5 0

M irage

C allo w ay

A 2 9 -4 6 8

D 7 B -9 1 6

W 9 1 -A 8 3

In d ex Ven d o rP riceP art #

A 2 9 -4 6 8 8 .7 5 M art in

Page 7: Introduction to STL and the vector container class CS342 Data Structures Based on Ford & Topp

A quick review of C++ arrays An array is a fixed-size collection of values of the same data type.

An array is a container that stores the n (size) elements in a contiguous block of memory. Once declared, n cannot be changed.

Array name is associated with the address of the array. So when an array is passed to a function, the size (or the number of elements that need to be processed) of the array must also be passed.

Directly assigning one array to another of same size and type are not allows: arrayA = arrayB; // syntax error!

arr[0 ] arr[1 ] arr[2 ]

0 1 2 n -1

. . . arr[n -1 ]

Page 8: Introduction to STL and the vector container class CS342 Data Structures Based on Ford & Topp

The vector container class characteristics Similar to a one-dimensional array: use index for direct access. Can dynamically grow and contract (remember size of an

conventional array cannot be changed once it is declared!)

vector is a STL class, it contains many useful member functions size(), pushback(), back(), popback, resize(), empty(), etc.

v [ 0 ] v [ 1 ] v [ 2 ] . . . v [ n-1 ] ro o m to gro w

0 1 2 n-1

Page 9: Introduction to STL and the vector container class CS342 Data Structures Based on Ford & Topp

A simple example// Vector function writeVetor( )

template <typename T>

void writeVctor(const vector<T> &v )

{

int i, n = v.size( ); // size( ) is a member function

for (i = 0; i < n; i++)

cout << v[i] << '\t'; // identical to an array

cout << endl;

}

Page 10: Introduction to STL and the vector container class CS342 Data Structures Based on Ford & Topp

Examples of how vector objects are declared and initialized

// without initializationvector<int> v(5); // vector of size 5 containing 0'svector<string> s(10); // size 10, each element contain null string// with initializationvector<char> line(80, 'A'); // 80 characters, each initialized to 'A'vector<time> t(5, time(12,30, 0)); // 5 elements with initial value 12:30:00// initialization from an arrayint a[5] = {1, 2, 3, 4, 5}; // array with initial valuesvector<int> v(a, a + 5); // initial values copied from the array a

// notice a + 5 is the address just past the end

// of array a// initialization without specifying the size, the initial size will be defaulted to 0vector<double> dblv;vector<string> s2;

Page 11: Introduction to STL and the vector container class CS342 Data Structures Based on Ford & Topp

Vector member function push_back( ) and pop_back( )

11 22 33 44

v.size( ) = 4

0 1 2 3

11 22 33 44

v.size( ) = 4

0 1 2 3

11 22 33 44 55

v.size( ) = 5

0 1 2 3 4

v.push_back(55);

v.pop_back( );

Page 12: Introduction to STL and the vector container class CS342 Data Structures Based on Ford & Topp

The sizeof( ) operator and back( ) member function

char vowel[ ] = {'a'. 'e', 'i', 'o', 'u'};

int vowelSize = sizeof(vowel)/sizeof(char);

vector<char> v(vowel, vowel + vowelSize);

cout << v.back( ); // output 'u'

v.push_back('w'); // add 'w' to end of v

v.back( ) = 'y'; // change back from 'w' to 'y'

Page 13: Introduction to STL and the vector container class CS342 Data Structures Based on Ford & Topp

Example: start with an empty vector and build a list with input (values of double type) from the user

vector<double> list; // declares an empty listdouble data;cout << “Enter a list of real values: “;cin >> data;while(data != -99) {

list.push_back(data);cin >> data;

}

Page 14: Introduction to STL and the vector container class CS342 Data Structures Based on Ford & Topp

Example: the pairing of back( ) and pop_back( )int a[ ] = {1, 2, 3, 4, 5, 6};

int aSize = sizeof(a) / sizeof(int);

vector<int> v(a, a + aSize);

while(!v.empty( )) {

cout << v.back( ) << '\t';

v.pop.back( );

} // output: 6 5 4 3 2 1

Page 15: Introduction to STL and the vector container class CS342 Data Structures Based on Ford & Topp

Resizing a vector with resize( ) member function

int a[ ] = {1, 2, 3, 4, 5};

int aSize = sizeof(a) / sizeof(int);

vector<int> v(a, a + aSize); // size = 5

v.resize(2 * aSize); // size = 10, "fill" value is 0

v.resize(4); // size = 4, data is lost

v.resize(10, 1); // size = 10. fill value is 1

Page 16: Introduction to STL and the vector container class CS342 Data Structures Based on Ford & Topp

How is the vector class defined: the vector class abstraction The constructors

vector( );

// default constructor creates an empty vector.

vector(int n, const T& value = T( ));

/* creates a vector with n elements, each have the specified value. If value is omitted, the elements are filled with the default value for type T. Type T must have a default constructor, a nd the default value of type T is specified by the notation T( ). */

vector(T *first, T *last);

/* initialize the vector using the address range [first, last).

Page 17: Introduction to STL and the vector container class CS342 Data Structures Based on Ford & Topp

The abstraction of the vector class continued

The member functions or operationsT &back( ); // returns the value of the item at the rear of the

vector

// Pre-condition: the vector must contain at least one element.

const T &back( ); // const version of back( );

bool empty( ) const; // returns true if vector is empty, false otherwise

T &operator[ ](int i);

// allows element at index i to be retrieved or modified.

const T &operator[ ](int i); // const version of T &operator[ ](int i);

void push_back(const T &value); /* Post-condition: a new element is added to the rear and the size of the vector is increased by 1. */

Page 18: Introduction to STL and the vector container class CS342 Data Structures Based on Ford & Topp

The abstraction of the vector class continued

The member functions or operations (continued)void pop_back( ); /* removes the item at the rear;

Precondition: the vector is not emptyPost condition: the size of the vector is decreased by 1. */

void resize(int n, const T & fill = T( )); /* modifies the size of the vector; if the size is increased, new elements with value fill are added to the rear of the vector. If the value is decreased, the original values at the front are retained. Post-condition: the vector has size n. */

int size( ) const; /* returns the number of elements in the vector. */

Page 19: Introduction to STL and the vector container class CS342 Data Structures Based on Ford & Topp

A simple application: join two vectors togethertemplate <typename T>

void join(vector<T> &v1, const vector <T> &v2)

{

int i, sizev2 = v2.size( );

for (i = 0; i < sizev2; i++)

v1.push_back(v2[i]);

}

Page 20: Introduction to STL and the vector container class CS342 Data Structures Based on Ford & Topp

The insertion sort

Ins e r t D ar e atl o c at i o n 1 ;the tai l o f the l i s ts h i ft s to the r i g ht

Star t w i th M o nr o e

C h inIns e r t C hi n i n l o c at i o n 0 ;

M o nr o e m o ve s to l o c at i o n 1

F lo resC h in Ins e r t F l o r e s i n l o c at i o n 1 ;M o nr o e m o ve s to l o c at i o n 2

C h in M o n ro e St einF lo res E l e m e nt Ste i n i s O K

C h in D are M o n ro e St einF lo res

P r o c e s s i ng F l o r e s

P r o c e s s i ng C hi n

P r o c e s s i ng D ar e

P r o c e s s i ng Ste i n

M o n ro e

M o n ro e

M o n ro e

Page 21: Introduction to STL and the vector container class CS342 Data Structures Based on Ford & Topp

The insertion sort//insertionSort():

// sort a vector of type T using insertion sort

template <typename T>

void insertionSort(vector<T>& v)

{

int i, j, n = v.size();

T temp;

// place v[i] into the sublist v[0] ... v[i-1], 1 <= i < n,

// so it is in the correct position

Page 22: Introduction to STL and the vector container class CS342 Data Structures Based on Ford & Topp

The insertion sort continued

for (i = 1; i < n; i++)

{ // index j scans down list from v[i] looking for //correct position to locate target. assigns it to v[j]

j = i;

temp = v[i];

// locate insertion point by scanning downward as // long as temp < v[j-1] and we have not

// encountered the beginning of the list

Page 23: Introduction to STL and the vector container class CS342 Data Structures Based on Ford & Topp

The insertion sort continued

while (j > 0 && temp < v[j-1]) { // shift elements up list to make room for insertion v[j] = v[j-1]; j--; } // the location is found; insert temp v[j] = temp; }}

Page 24: Introduction to STL and the vector container class CS342 Data Structures Based on Ford & Topp

Running time of insertion sort requires (n-1) passes for pass i, the insertion occurs in the sublist v[0] to v[i-1]

and requires an average of i/2 comparisions. Thus, T(n) = 1 / 2 + 2/2 + … + (n-2)/2 + (n-1)/2 = n(n-1)/4 or the running time is O(n2).

The best case occurs when the list is already in order, the total number of comparson T(n) = n-1, leading to O(n) running time.

The worst case occurs when the list is in descending order and T(n) = n(n-1)/2 or O(n2) running time.

The insertion sort exhibits the best performance among the quadratic sorting algorithms when the list is partially ordered.

Page 25: Introduction to STL and the vector container class CS342 Data Structures Based on Ford & Topp

Another vector application: joining three sorted sublists// File: prg4_2.cpp// the program generates 12 random integers in the range// 100 to 999. add each number value to vector vSmall if// value < 400, to vector vMedium if 400 <= value < 700// and to vLarge if 700 <= value < 1000. apply the insertion// sort to order each vector. use join() so that vSmall is// the concatenation of the three vectors. sort the final list// in vSmall by using the insertion sort. display the initial// set of elements in each vector and the final sorted list// by calling writeVector()

Page 26: Introduction to STL and the vector container class CS342 Data Structures Based on Ford & Topp

Another vector application: joining three sorted sublists continued

#include <iostream>#include <vector>

#include "d_random.h" // for randomNumber#include "d_sort.h" // for insertionSort()#include "d_util.h" // for writeVector()using namespace std;// attach vB onto the end of vAtemplate <typename T>void join (vector<T> &vA, const vector<T>& vB);

Page 27: Introduction to STL and the vector container class CS342 Data Structures Based on Ford & Topp

Another vector application: joining three sorted sublists continuedint main(){ // declare 3 integer vectors vector<int> vSmall, vMedium, vLarge; // use a random number generator

randomNumber rnd; int i, value;

for (i = 0; i < 12; i++){

value = rnd.random(900) + 100;if (value < 400)

vSmall.push_back(value);else if (value < 700 )

vMedium.push_back(value);else

vLarge.push_back(value);}

Page 28: Introduction to STL and the vector container class CS342 Data Structures Based on Ford & Topp

Another vector application: joining three sorted sublists continued

// sort the vector of integers in the range// 100 <= n < 400 and outputinsertionSort(vSmall);cout << "Small: ";writeVector(vSmall);// sort the vector of integers in the range// 400 <= n < 700 and outputinsertionSort(vMedium);cout << "Medium: ";writeVector(vMedium);

Page 29: Introduction to STL and the vector container class CS342 Data Structures Based on Ford & Topp

Another vector application: joining three sorted sublists continued

// sort the vector of integers in the range// 700 <= n < 1000 and outputinsertionSort(vLarge);cout << "Large: ";writeVector(vLarge);// join vMedium onto the end of vSmalljoin(vSmall, vMedium);// join vLarge onto the end of the modified vSmalljoin(vSmall, vLarge);// output the new vectorcout << "Sorted: ";writeVector(vSmall);return 0;

}

Page 30: Introduction to STL and the vector container class CS342 Data Structures Based on Ford & Topp

Another vector application: joining three sorted sublists continuedtemplate <typename T>void join (vector<T> &vA, const vector<T>& vB){

// capture the size of vB in sizeBint i, sizeB = vB.size();

// use index i to access the elements of vB and push_back()// to add the elements to the rear of vA

for (i = 0; i < sizeB; i++) vA.push_back(vB[i]);}

/*Run:

Small: 176 213 269 287 357Medium: 482 535 551 649 687Large: 843 901Sorted: 176 213 269 287 357 482 535 551 649 687 843 901

Page 31: Introduction to STL and the vector container class CS342 Data Structures Based on Ford & Topp

The matrix class Because of its importance in science and engineering

applications, matrix class has been included in the C++ STL.

Matrix is implemented as a vector of vectors:vector<vector<T> > mat; /* the outer vector corresponds to

rows of the matrix, the elements in the inner vector of type T correspond to the column entries for each vector row. For example, mat[0] is the vector of column entries corresponding to row 0, etc. Note that there must be a space between the closing angle brackets > > or is will be interpreted as >> which is the extraction operator or right shift operator in bit manipulation. */