{[ promptMessage ]}

Bookmark it

{[ promptMessage ]}

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

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

1 Lecture 18: Vectors in Functions PIC 10A Todd Wittman Quick Review of Vectors box4 A vector is a class defined in the <vector> library that can store a list of data. box4 We decide the data type and initial size in the declaration of the vector. vector<string> words(10); vector<int> list(200); box4 We can look up the current size of a vector. int number_words = words.size(); box4 To access an element, use brackets []. box4 Remember vector indices start at 0. words[0]="hello"; cout<<list[1]+list[2]; box4 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.

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

View Full Document
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 box4 A string is actually vector<char> string name = "Frodo"; name[0] = 'G'; cout << name; // Prints Grodo box4 A string variable can use vector member functions. name.push_back('s'); //Adds one char to the end. box4 Recall On Practice Exam 1, you had to replace every s in a string with an f. box4 It was a hard problem because you had to extract the single letter substring, then delete the “s”, and then insert the “f”. box4 Much easier with vector notation. for (int i = 0; i < my_string.length(); i++) { if (my_string[i] == 's') my_string[i] = 'f'; }
3 Sec 6.3 : Vectors in Functions box4 To pass a vector to a function, use the prototype void function_name (vector<type> vector_name) { ...

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

View Full Document
This is the end of the preview. Sign up to access the rest of the document.

{[ snackBarMessage ]}