Understanding Vectors in C++: Basics, Syntax, and Functions
Explore the fundamentals of using vectors in C++. Vectors are dynamic arrays that can hold any data type, including user-defined classes. This overview covers vector declarations, accessing and modifying elements, and important member functions like push_back() and size(). Learn about capacity versus size, how to efficiently manage memory with reserve(), and practice with exercises that involve user input and sorting algorithms. Master these concepts to enhance your programming skills in C++.
Understanding Vectors in C++: Basics, Syntax, and Functions
E N D
Presentation Transcript
Vectors 8.3
Basics • Defined in <vector> library • A vector has a base type, just like an array • You can use any type, including class types • Declarations • vector<int> v; • Default constructor • Elements • Indexed starting with 0 • Can access elements using the square bracket notation • v[i] = 42; • cout << “answer is “ << v[i]; • You CANNOT initialize an element using square bracket notation, you can only change an element that has already been given a value
New vector syntax • push_back() • Adds an element in the next available position in the vector • size() • Returns the number of elements in a vector (an unsigned int) • vector<int> v(10) • Vector constructor that takes one argument; will initialize the number of positions given as the argument • The declaration above would initialize the first ten elements of v to 0, thus v.size() would return 10
Copying/Assigning Vectors • The assignment operator does an element by element assignment • However, the assignment operator on a vector is only as good (or bad) as the assignment operator on its base type
Size vs. Capacity • Size – the number of elements in the vector • Capacity – the number of elements for which it currently has memory allocated • When a vector runs out of capacity and needs room for an additional member, capacity is automatically increased • This increase always allows for more space than is needed • Reallocating capacity in large chunks is more efficient than allocating numerous small chunks • If efficiency is an issue, use the member function reserve(int) to explicitly increase the capacity of a vector
Member Functions • push_back() • pop_back() • size() • capacity() • reserve() • resize()
Class Exercises • Write a program that asks a user to enter a list of positive integers. The user will use a negative number sentinel to indicate he/she is finished. Echo the user’s input. • Write a sorting function that has an argument for a vector of ints. Use the selection sort algorithm.