Previous Lecture Lecture 15 Next Lecture

Lecture 15, Thu 08/23

Standard Library and Vectors

Standard Library

std::vector

Example

#include<vector>

using namespace std;

int main() {
	vector<int> v; // a vector containing int elements
	return 0;
}

Example: Adding to vectors

vector<int> v;
for (int i = 0; i < 5; i++) // adding five elements
	v.push_back(i);
}

// Can access elements in vectors with [] similar to arrays
for (int i = 0; i < v.size(); i++) {
	v[i] *= 2;
}

for (int i = 0; i < v.size(); i++) {
	cout << "v[" << i << "] = " << v[i] << endl;
}

Range based loop

int arr[] = {1,2,3};

for (int x : arr) { // C++11 range-based loop extension
	cout << x << endl;
}

// Loops through the entire array, note if we change
// arr[] to arr[10], then the range based loop will
// loop through the ENTIRE array structure (even through
// values we did not define in { }).

// also can be used with vectors

int index = 0;
for (int i : v) {
	cout << "v[" << index << "] = " << i << endl;
	index++;
}

Vector Initialization

vector<int> v1(100); // initializes vector with 100 elements = 0
vector<int> v2(100, 1); //initializes vector with 100 elements = 1

Pointer to Vectors

vector<int>* v = new vector<int>(10,1);
cout << v->size() << endl;