object.method();
vector
library must be included to use vectors
#include <vector>
<type>
, and initial size in parentheses
// Vector that holds 5 integers (all initially zero) vector<int> numbers(5); // Holds 8 chars (all initially spaces) vector<char> gameBoard(8); // Holds 4 booleans (all initially false) vector<bool> coinFlips(4); // Holds 10 strings (all initially empty) vector<string> teamNames(10);
// Empty vector that holds integers vector<int> numbers;
vector<int> scores(5); scores.at(0) = 88; // First slot contains 88 scores.at(1) = 93; // Second slot contains 93 scores.at(2) = 68; // etc... scores.at(3) = 50; scores.at(4) = 77;
// Empty vector vector<int> scores(5); scores.at(5) = 88; // Run-time error! Only indexes 0-4 are available
vector<int> scores; scores.push_back(88); scores.push_back(93); scores.push_back(68); scores.push_back(50); scores.push_back(77);
// Empty vector vector<int> scores; // Vector now holds 5 integers scores = { 88, 93, 68, 50, 77 };
=
vector<int> scores = { 88, 93, 68, 50, 77 }; // exams contains same 5 integers vector<int> exams = scores;
vector<int> scores = { 88, 93, 68, 50, 77 }; cout << scores.size(); // 5
// Equivalent firstNum = scores.at(0); firstNum = scores.front();
// Equivalent lastNum = scores.at(scores.size() - 1); lastNum = scores.back();
// Vector holds only 5 integers vector<int> scores(5); // Now vector holds 10 integers scores.resize(10);
vector<int> scores(5); cout << scores.size(); // 5 scores.clear(); cout << scores.size(); // 0
size()
as limit in for
loop
vector<int> scores = { 88, 93, 68, 50, 77 }; // Displays: 88 93 68 50 77 for (int i = 0; i < scores.size(); i++) { cout << scores[i] << " "; }
// score is assigned each element in scores for (int score : scores) { cout << score << " "; }
&
// scores is unchanged because s is a copy! for (int s : scores) { s++; } // Pass-by-reference changes scores array for (int &s : scores) { s++; }
// nums is passed by value (copy) int Sum(vector<int> nums) { int sum = 0; for (int n : nums) { sum += n; } return sum; }
vector<int> powersOfTwo = { 2, 4, 8, 16, 32 }; int sum = Sum(powersOfTwo); // 62
// coinFlips is set to random true/false values void FlipCoins(vector<bool> &coinFlips) { for (int i = 0; i < coinFlips.size(); i++) { coinFlips[i] = rand() % 2 == 0; } }
const
// nums is passed by reference but write-protected int Sum(const vector<int> &nums) { int sum = 0; for (int n : nums) { sum += n; } return sum; }
// Returns a vector that contains the sum of vectors a and b vector<int> Sum(const vector<int> &a, const vector<int> &b) { vector<int> sum(a.size()); for (int i = 0; i < a.size(); i++) { sum[i] = a[i] + b[i]; } return sum; } // Calling example vector<int> powersOfTwo = { 2, 4, 8, 16, 32 }; vector<int> powersOfThree = { 3, 9, 27, 81, 243 }; // vectorSum contains: 5, 13, 35, 97, 275 vector<int> vectorSum = Sum(powersOfTwo, powersOfThree);