Presentation is loading. Please wait.

Presentation is loading. Please wait.

Vectors Updated 11/4/2003 by Kip Irvine. Copyright Kip Irvine 2003. Overview What is a vector? Declaring vector objects Inserting and removing items Using.

Similar presentations


Presentation on theme: "Vectors Updated 11/4/2003 by Kip Irvine. Copyright Kip Irvine 2003. Overview What is a vector? Declaring vector objects Inserting and removing items Using."— Presentation transcript:

1 Vectors Updated 11/4/2003 by Kip Irvine

2 Copyright Kip Irvine 2003. Overview What is a vector? Declaring vector objects Inserting and removing items Using subscripts Getting and changing the size Preallocating space Passing vectors to functions Vector return values

3 Copyright Kip Irvine 2003. What is a Vector? From the Standard C++ Library documentation: A vector is a sequence that supports random access to elements, constant time insertion and removal of elements at the end, and linear time insertion and removal of elements at the beginning or in the middle. The number of elements in a vector may vary dynamically; memory management is automatic. Vector is the simplest of the STL container classes, and in many cases the most efficient.

4 Copyright Kip Irvine 2003. Declaring Vector Objects #include vector scores(20); vector names; vector busyFlags(5); vector classRoll(50); You can declare a vector of any type can be empty or it can have a size

5 Copyright Kip Irvine 2003. Inserting and Removing Items push_back(item) inserts an item pop_back() removes an item, but does not return it to the caller

6 Copyright Kip Irvine 2003. Inserting and Removing Items vector temps; temps.push_back( 88.5 ); temps.push_back( 87.2 ); temps.push_back( 82.1 ); // now the vector contains elements in // positions [0], [1], and [2]. // remove the last element: temps.pop_back();

7 Copyright Kip Irvine 2003. Using Subscripts vector scores; scores[0] = 25; // crashes! scores.push_back( 15 ); scores[0] = 25; // ok now For any subscript n, the following must be true: 0 <= n < size() The C++ vector class does not check index ranges.

8 Copyright Kip Irvine 2003. Constructor A vector constructor can take an integer parameter that sets the size Each element can be optionally initialized by the constructor vector names(10); vector scores(10, 0); // all 10 elements contain zero vector backup( scores ); // make a copy of a vector

9 Copyright Kip Irvine 2003. Getting/Changing the Size size() returns the number of elements in the vector empty() returns true if size == 0 push_back() increases the size by 1 pop_back() decreases the size by 1 resize() changes the size Examples:

10 Copyright Kip Irvine 2003. Getting and Changing the Size vector names( 10 ); cout << names.size( ); // 10 names.push_back( "Sam" ); cout << names.size( ); // 11 names.resize( 15 ); // size = 15 names.pop_back( ); // size = 14

11 Copyright Kip Irvine 2003. Automatic Expansion If push_back() discovers that the vector is full, the vector automatically doubles in size separate copy of the vector is made, with considerable runtime overhead

12 Copyright Kip Irvine 2003. Reserving Space reserve(n) sets aside space for expansion without affecting the value returned by size() Use reserve() to make push_back() more efficient

13 Copyright Kip Irvine 2003. Vectors in Classes class Scores { public: double at(int index) const; // return the score at index private: vector m_vScores; }; A vector should be encapsulated in a class, to provide adequate error checking

14 Copyright Kip Irvine 2003. Vectors in Classes double at( int index ) const { if( index >= 0 && index < m_vScores.size( ) ) return m_vScores[ index ]; else return 0.0; } The following function performs range checking:

15 Copyright Kip Irvine 2003. Vectors in Classes class MyClass { public: private: vector myVec( 20 ); // error! vector myVec; // ok }; A size value cannot be passed to the vector constructor in a class definition:

16 Copyright Kip Irvine 2003. Vectors in Classes MyClass::MyClass( int theSize ) : myVec( theSize ) { } Instead, space for the vector can be reserved in the constructor implementation by using a member initializer:

17 Copyright Kip Irvine 2003. Vectors in Classes MyClass::MyClass( int theSize ) { myVec.reserve( theSize ); // size() still returns 0 } Or, space for the vector can be reserved in the constructor implementation:

18 Copyright Kip Irvine 2003. Vectors in Classes MyClass::MyClass( int theSize ) { myVec.resize( theSize ); // size() returns value of theSize } Or, the vector can be resized, causing empty elements to be inserted:

19 Copyright Kip Irvine 2003. Passing Vectors to Functions double calcAverage( const vector & scores ) { double avg = 0; //... return avg; } Always pass vectors by reference Use const if the vector will not be modified

20 Copyright Kip Irvine 2003. Filling a Vector void fillRandom( vector & vList ) { int i; for( i = 0; i < vList.size( ); i++ ) { int n = rand( ) % 100; vList[i] = n; } Example: fill a vector with random integers between 0 and 99:

21 Copyright Kip Irvine 2003. Vector Return Values vector makeRandomVector( int count ) { vector list( count ); // set the size for( int i = 0; i < count; i++ ) { list[i] = rand( ); } return list; // return a copy } You can declare a vector inside a function and return a copy of the vector: but copying incurs runtime overhead!

22 Copyright Kip Irvine 2003. Vector Return Values // sample call: vector Z = makeRandomVector( 25 );

23 Copyright Kip Irvine 2003. Sorting a Vector #include vector items; sort( items.begin( ), items.end( ) ); Assume that the vector contains items whose type/class is predefined in C++ The sort( ) function belongs to the algorithm library begin( ) points to the first element, and end( ) points one position beyond the last element

24 Copyright Kip Irvine 2003. Iterators vector items; vector ::iterator I; I = items.begin(); // first number cout << *I << endl; // display the number An iterator is a pointer to a vector element that can be moved forward or backward through the vector elements dereference the iterator to access the element it points to

25 Copyright Kip Irvine 2003. Sorting Using Iterators #include vector items; vector ::iterator I1; vector ::iterator I2; I1 = items.begin( ); I2 = items.end( ); sort( I1, I2 ); You can pass iterators to the sort() function:

26 Copyright Kip Irvine 2003. Sorting User-Defined Types vector cop3337; sort( cop3337.begin( ), cop3337.end( ) ); Sorting a vector containing your own class types is slightly more advanced You must overload the < operator in your class (see next panel)

27 Copyright Kip Irvine 2003. Overloading the < Operator class Student { public: bool operator <(const Student & S2) { return m_sID < S2.m_sID; } private: string m_sID; string m_sLastName; };

28 Copyright Kip Irvine 2003. Common Vector Operations vector items; // Reverse the order reverse( items.begin( ), items.end( ) ); // Randomly shuffle the order random_shuffle( items.begin( ), items.end( ) ); // Accumulate the sum #include int sum = accumulate( items.begin( ), items.end( ), 0 );

29 Copyright Kip Irvine 2003. Find/Remove Lowest Value vector items; vector ::iterator I; // find lowest value I = min_element( items.begin( ),items.end( ) ); // erase item pointed to by iterator I items.erase( I );

30 Copyright Kip Irvine 2003. The End


Download ppt "Vectors Updated 11/4/2003 by Kip Irvine. Copyright Kip Irvine 2003. Overview What is a vector? Declaring vector objects Inserting and removing items Using."

Similar presentations


Ads by Google