Anda di halaman 1dari 29

The C++ Vector Class

The contents of this particular lecture prepared by the instructors at the University of Manitoba in Canada and modified by Dr. Ahmad Reza Hadaegh

A.R. Hadaegh Dr. Ahmad R. Hadaegh

National University (NU)

Page

- C- Style Arrays
- are somewhat difficult to use - fixed size, determined at compile time - this is avoidable through pointers and explicit memory management but this is tedious and error prone - they had very strange semantics when being passed to functions

A.R. Hadaegh Dr. Ahmad R. Hadaegh

National University (NU)

Page

C++ Vector Class


- C++ provides an excellent class library to give a comprehensive and consistent implementation of the functionality of arrays - The <vector> class library - much easier to create good, readable, error free and fast code with this class library - In general, <vector> class library is preferred to C-style arrays

A.R. Hadaegh Dr. Ahmad R. Hadaegh

National University (NU)

Page

C++ Vector Class


- Example:

#include <vector> // include the <vector>class library vector<float> x(10), y(10), z(10); .. .. for (i= 0; i<10; i++) z[i]= x[i]+ y[i];
- vector<float>: it is a type for declaring one-dimensional arrays of floats - x, y, z all have room for 10 elements - include the <vector> class library
A.R. Hadaegh Dr. Ahmad R. Hadaegh National University (NU) Page 4

C++ Vector Class


- We can declare vectors of any type: vector<int> x(20); // vector of 20 ints vector<char> y(len); // vector of len chars vector<char> z;
// where len an int variable // empty vector of chars (later)

- General format: vector<T> name(sz); // length sz, type T vector<T> name; // length 0, type T - where T is any legal type

A.R. Hadaegh Dr. Ahmad R. Hadaegh

National University (NU)

Page

C++ Vector Class


vector<T> name(sz): - declares a vector of type T with sz elements - elements are in locations name[0], name[1], ..., name[sz-1] - elements of a vector can be examined and assigned just as with an array, using [ ] - you cannot access or assign beyond the current size of a vector - this may or may not cause an exception (out of bounds error)
A.R. Hadaegh Dr. Ahmad R. Hadaegh National University (NU) Page 6

C++ Vector Class


- You can also declare vectors to be initialized:
#include <vector> vector<char> C(10, 'A'); // C contains space for 10
// chars, all initialized to 'A'

vector<int> Marks(1000,0);
// Marks contains space // for 1000 ints, all // initialized to 0

A.R. Hadaegh Dr. Ahmad R. Hadaegh

National University (NU)

Page

C++ Vector Class


- From what we have seen, vectors can be used whenever C-style arrays are used - Why bother with vectors???

- Vectors offer 4 immediate improvements over C-style arrays: - they are dynamically sized and can change size - they can be passed as parameters by value or reference much as ints, and chars. - the size of the vector is passed along with the vector when used as parameters - vectors can be returned from functions
A.R. Hadaegh Dr. Ahmad R. Hadaegh National University (NU) Page 8

C++ vectors are dynamically sized


- size does not need to be set when variable is initialized, or can be set to a variable - contrast with C-style arrays where the size of an array must be a compile-time constant

- size can be changed dynamically while the program is running - contrast with C-style arrays where the size of an array must be a compile-time constant

A.R. Hadaegh Dr. Ahmad R. Hadaegh

National University (NU)

Page

Appending to Vectors
- The size of a vector can be increased with the function push_back

vector<int> V; V. push_back(17);

// declare vector with no entries // append 17 to the end of // the vector V. The size // of V increases b y 1

- In general: vector<T> V; V. push_back(x);

// V a vector of type T, size 0 // append element x of type T // to end of vector V


Page 10

A.R. Hadaegh Dr. Ahmad R. Hadaegh

National University (NU)

Appending to Vectors
- The current size of a vector can be obtained by the size() function - Example: ... vector<float> W(5,-1.0); W. push_back(- 2.0); // append -2.0 to W cout << W.size() << endl; for (i= 0; i< W.size(); i++) cout << W[i] << ; ... - Output: size after push_ back 6 entries 0.. 5 -1.0 -1.0 -1.0 -1.0 -1.0 -2.0
A.R. Hadaegh Dr. Ahmad R. Hadaegh National University (NU) Page 11

Appending to Vectors
// read a list of integers from fin until end-of-file #include <vector> #include <iostream> #include<fstream> using namespace std; int main() { vector<int> V; int tmp; ifstream fin; fin.open("data.txt"); fin >> tmp; while (fin) { cout << tmp << endl; V.push_back(tmp); fin >> tmp; } cout << "File contains " << V.size() << " entries \n"; }
A.R. Hadaegh Dr. Ahmad R. Hadaegh National University (NU) Page 12

Decreasing Vector Size


- You can also remove the last entry from a vector (and decrease the size by 1) using the pop_back() function:

vector<float> avec( 10,3.14159); cout << avec.size() << endl; for(i= 0;i< 4;i++) avec.pop_back(); cout << avec.size() << endl; - Output: 10 6
A.R. Hadaegh Dr. Ahmad R. Hadaegh

Started with 10 entries removed 4 entries 6 entries remaining

National University (NU)

Page 13

Vectors as Parameters
- One of the best features of vectors as compared to C-style arrays is that they can be passed as parameters and returned from functions in the normal way - pass by reference (with a &) or by value - the size of the vector is included when vector is passed

- can be returned from a function in the normal way

A.R. Hadaegh Dr. Ahmad R. Hadaegh

National University (NU)

Page 14

Vectors as Parameters
// Example: vector addition with value parameter

vector< float> AddVec(vector<float> x, vector<float> y)


// Add vector x to vector y and return result in vector z

{
vector< float> z; if (x.size() != y.size()) cout << "Error: x, y must be same size.\n"; else { for (i= 0; i< x.size(); i++) z.push_back(x[i]+y[i]); } return z; }
A.R. Hadaegh Dr. Ahmad R. Hadaegh National University (NU) Page 15

Vectors as Parameters
// Example: vector addition with reference parameter

void AddVec2( vector<float>& x , vector<float> y) {


// add vector y to vector x

if (x.size()!=y.size()) cout << "Error: x, y must be of same size.\n"; else for (i= 0; i< x.size(); i++) x[i]+= y[i]; return;

}
A.R. Hadaegh Dr. Ahmad R. Hadaegh National University (NU) Page 16

Constant Reference Parameters


- Recall that when we use value parameters, the parameters are assigned copies of the arguments - for example, if we run vector<float> a, b, c; ... a= AddVec(b, c); the vector b is copied to the parameter x and the vector c is copied to the parameter y in addvec - this is time-consuming
A.R. Hadaegh Dr. Ahmad R. Hadaegh National University (NU) Page 17

Constant Reference Parameters


- Since x and y are not modified in addvec, we can make them reference parameters - this means that x just becomes another name for b and y becomes another name for c - this works since x and y are not changed in addvec - no time-consuming copying required - To tell the compiler and those reading the code that x and y are not changed, declare x and y as constant reference parameters

A.R. Hadaegh Dr. Ahmad R. Hadaegh

National University (NU)

Page 18

Constant Reference Parameters


vector<float> AddVec( const vector< float>& x, const vector< float>& y)
// the code is the same as before

{ vector<float> z; if (x.size() != y.size()) cout << "Error: x, y must be same size.\n"; else { for (i= 0; i< x.size(); i++) z.push_back(x[i]+ y[i]); } return z;

}
A.R. Hadaegh Dr. Ahmad R. Hadaegh National University (NU) Page 19

Vector Operators
- <vector> also provides some useful operators for manipulating vectors

- assignment operator = - comparison operators = =, !=, <, <=, >, >=

- No input/output operators or procedures are defined for generic vectors

A.R. Hadaegh Dr. Ahmad R. Hadaegh

National University (NU)

Page 20

Vector Operators
- Assignment operator: - assign (copy) one vector to another using =

#include <vector> vector<float> a(5,3.14159), b(3,2.71828); a=b; cout << a[0] << << a.size() << endl; cout << b[0] << << b.size() << endl;
Output: 2.71828 2.71828
A.R. Hadaegh Dr. Ahmad R. Hadaegh

3 3
Page 21

National University (NU)

Vector Operators
- The assignment operator = is an aggregate operation - copies one structured data type to another - behaves much like int assignment vector<T> v, w; // T is any type ... v= w; - side- effect: change v to contain copy of w

A.R. Hadaegh Dr. Ahmad R. Hadaegh

National University (NU)

Page 22

Vector Operators
- Comparison Operators - vectors can be compared for equality (==) and inequality (!=) - two vectors are equal if - they have equal lengths - their elements are identical in pairs - best way to understand it: - write our own equality function

A.R. Hadaegh Dr. Ahmad R. Hadaegh

National University (NU)

Page 23

Vector Operators
bool vecequal(vector<int> x, vector<int> y) {
// return true if x equals y, false otherwise

int i; if (x.size() != y.size()) return false; for (i= 0; i< x. size(); i++) if (x[i] != y[i]) return false; return true;
} - You don't need to write this function: - just write x = = y - works for vectors of any types Note: we do need the type of vector
A.R. Hadaegh Dr. Ahmad R. Hadaegh National University (NU) Page 24

Vector Inequality
- The best way to explain this is to go through some examples. - Examples: - (3, 5, 6, 7) < (3, 5, 7, 5) true - ('a', 'b', 'c') < ( 'b', 'c', 'd' ) true - ('a', 'b', 'c') < ('a', 'b', 'c') false (they're ==) - (3.25, 4.25, 5.33) < (3.25, 4.25, 5.33, 6.97) true - The last case is interesting - all elements in common are the same - the shorter vector is regarded as smaller - Let's write our own function for vector comparison
A.R. Hadaegh Dr. Ahmad R. Hadaegh National University (NU) Page 25

Vector Inequality
bool VecLessThan(const vector<int>& x, const vector<int>& y) { int i= 0; while (i<x.size() && i<y.size()) { if (x[i] < y[i]) return true; if (x[i] > y[i]) return false; i++; }
// all entries are equal from 0.. min( x. size(), y. size())- 1

if (x.size()< y.size()) return true; else return false; }


A.R. Hadaegh Dr. Ahmad R. Hadaegh National University (NU) Page 26

Vector Inequality
- Other vector comparisons also available !=, <=, >, >= - Once we have <, = =, the others can be defined immediately - For vectors x, y - x != y equivalent to - x <= y equivalent to - x > y equivalent to - x >= y equivalent to

! (x= = y) (( x< y) || (x= = y)) !( x= = y) && !( x< y) !( x< y)

A.R. Hadaegh Dr. Ahmad R. Hadaegh

National University (NU)

Page 27

Some other vector functions:


v.begin(): Returns address of first element
v.end(): returns address of the one after the last element in the vector v.front(): return value of the first element of the the vector v.back(): return value of the last element of the the vector
A.R. Hadaegh Dr. Ahmad R. Hadaegh National University (NU) Page 28

Some other vector functions:


v.insert(v.begin()+1, 400); insert 400 into index 1

v.erase(v.begin()+2); erase the value in index 2

v.erase(v.begin()+2, v.begin()+7); erase from index 2 to index 7 but not including 7

A.R. Hadaegh Dr. Ahmad R. Hadaegh

National University (NU)

Page 29

Anda mungkin juga menyukai