CSE 100 Lecture 35: Chapter 8
Chapter 8 Continued
● 8.12 Vectors
○ A vector hold a set of elements, like a one-dimensional array
○ It has a flexible number of elements. It can grow and shrink
■ There is no need to specify the size when defined
■ Space is automatically added as needed
○ Defined in the Standard Template Library (STL)
■ covered in a later chapter
○ Must include vector header file to use vectors
■#include <vector>
○ Vector
■ can hold values of any data type, specified when the vector is defined
● vector<int> scores;
● vector<double> volumes;
■ You can specify initial size if desired
● vector<int> scores(24);
■ Use [ ] to access individual elements
○ Defining Vectors
■ Define a vector of integers (starts with 0 elements)
● vector<int> scores;
■ Define int vector with initial size 30 elements
● vector<int> scores(30);
■ Define 20-element int vector and initialize all elements to 0
● vector<int> scores(20, 0);
■Define int vector initialized to size and contents of vector finals
● vector<int> scores(finals);
●C++ 11 Features for Vectors
○C++ 11 supports vector definitions that use an initialization list
■ vector<int> scores {88, 67, 79, 84};
○Note: no = operator between the vector name and the initialization list
○A range-based for loop can be used to access the elements of a vector
■for(int test : scores)
● cout <, test << “ “;
●Growing a Vector’s Size
○Use the push_back member function to add an elements to a full vector or to a
vector that had no defined size
○ // Add a new element holding a 75 scores.push_back(75);
○Use the size member function to determine the number of elements currently in a
vector
■ howbig = scores.size();
●Removing Vector Elements
○Use the pop_back member function to remove last element form vector
Document Summary
A vector hold a set of elements, like a one-dimensional array. It has a flexible number of elements. There is no need to specify the size when defined. Defined in the standard template library (stl) Must include vector header file to use vectors. You can specify initial size if desired. Use [ ] to access individual elements. Define a vector of integers (starts with 0 elements) Can hold values of any data type, specified when the vector is defined. Define int vector with initial size 30 elements. Define 20-element int vector and initialize all elements to 0. Define int vector initialized to size and contents of vector finals. C++ 11 supports vector definitions that use an initialization list. Note: no = operator between the vector name and the initialization list. A range-based for loop can be used to access the elements of a vector. Growing a vector"s size vector that had no defined size.