Lec18 - Lecture 18: Vectors in Functions PIC 10A Todd...

Info iconThis preview shows pages 1–4. Sign up to view the full content.

View Full Document Right Arrow Icon
1 Lecture 18: Vectors in Functions PIC 10A Todd Wittman Quick Review of Vectors b A vector is a class defined in the <vector> library that can store a list of data. b We decide the data type and initial size in the declaration of the vector. vector<string> words(10); vector<int> list(200); b We can look up the current size of a vector. int number_words = words.size(); b To access an element, use brackets []. b Remember vector indices start at 0. words[0]="hello"; cout<<list[1]+list[2]; b Vectors are dynamic: they can change size. words.resize(5); //Keep just first 5 elements. words.push_back("Frodo"); //Add "Frodo" to end. words.pop_back(); //Remove last element.
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
2 Vector Member Functions Resizes vector to size n. If n is smaller than old size, deletes elements at back end. resize (int n) Removes the last element from the back end of the vector. pop_back( ) Inserts x at the back end of the vector. push_back (T x) Returns current size of vector. int size( ) Constructs a vector with n elements. vector (int n) vector<T> -- T is the data type (e.g. int, double, string, Card, etc.) Strings as Vectors b A string is actually vector<char> string name = "Frodo"; name[0] = 'G'; cout << name; // Prints Grodo b A string variable can use vector member functions. name.push_back('s'); //Adds one char to the end. b Recall On Practice Exam 1, you had to replace every s in a string with an f. b It was a hard problem because you had to extract the single letter substring, then delete the “s”, and then insert the “f”. b Much easier with vector notation. for (int i = 0; i < my_string.length(); i++) { if (my_string[i] == 's') my_string[i] = 'f'; }
Background image of page 2
3 Sec 6.3 : Vectors in Functions b To pass a vector to a function, use the prototype void function_name (vector<type> vector_name) { . .. b
Background image of page 3

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Image of page 4
This is the end of the preview. Sign up to access the rest of the document.

Page1 / 10

Lec18 - Lecture 18: Vectors in Functions PIC 10A Todd...

This preview shows document pages 1 - 4. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online