Vectors in C++
Vectors in C++
ELE 1601 2 © tj
Vectors
• Where are vectors stored
• Since they can grow over time
• The elements of the vector are stored on the heap
• The vector template manages the creation (new) and destruction
(delete)
ELE 1601 3 © tj
Vectors
• Syntax
#include <vector>
• creating vectors
vector<type> name;
vector<type> name(initial size);
vector<type> name(initial size, initial value); // initializes all values
vector<type> name{list of element values}; // initializes values with {}
ELE 1601 4 © tj
Vectors
• Accessing Vector elements
• Just like arrays
ELE 1601 5 © tj
Vectors
• Accessing Vector elements
• Use size of the vector function for looping limit
• objectName.size()
Note: unsigned int because
size() returns an unsigned int
and the compiler whines about
a mismatch
ELE 1601 6 © tj
Vectors
• Accessing Vector elements
• Use the vector iterator for looping limits
• objectName.begin(), object_name.end()
ELE 1601 7 © tj
Vectors
• Add/remove elements from a vector
• objectName.push_back(value) // adds element with value
• objectName.pop_back() // removes last element in vector
ELE 1601 8 © tj
Vectors
• Passing vectors to functions
Note use of const in this case
since the vector is not modified
ELE 1601 10 © tj
Vectors
ELE 1601 11 © tj
Vectors
• Using the Algorithm library
#include <vector>
#include <algorithm>
#include <iostream>
using namespace std;
int main(void){
vector<int> v1(20);
vector<int> v2;
load_vector(v1);
print_vector(v1);
cout << "is 44 present? " << binary_search(v1.begin(), v1.end(), 44) << endl;
sort(v1.begin(), v1.end());
cout << "sorted ";
print_vector(v1);
cout << "is 44 present? " << binary_search(v1.begin(), v1.end(), 44) << endl;
random_shuffle(v1.begin(), v1.end());
cout << "random ";
print_vector(v1);
v1.insert(v1.begin()+5, 99);
print_vector(v1);
ELE 1601 12 © tj
Vectors
• Using the Algorithm library
load_vector2(v2);
cout << "vector2 ";
print_vector(v2);
reverse(v2.begin(), v2.end());
cout << "reversed ";
print_vector(v2);
return 0;
}
ELE 1601 13 © tj