Vectors

  1. Overview
    1. A vector is a collection of like items that can change in size dynamically (at run-time)
    2. Vectors consume more memory than arrays but the ability to resize dynamically makes them more useful
    3. A vector is an object, a programming construct that combines the data with the functions (called methods) that work on the data
      object.method();
      
    4. The vector library must be included to use vectors
      #include <vector>
      
  2. Declaring a vector
    1. Data type is in angle brackets <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);
      
    2. Initial size is optional; creates size 0 vector
      // Empty vector that holds integers 
      vector<int> numbers;
      
  3. Initializing a vector
    1. Place numbers into a vector directly using at(index) method
      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;
      
    2. Warning: A run-time error occurs if accessing outside bounds of vector
      						// Empty vector
      						vector<int> scores(5);
      						
      						scores.at(5) = 88;   // Run-time error! Only indexes 0-4 are available
      						
    3. push_back(item) method adds an item to the end of the vector and increase its size
      vector<int> scores;
      
      scores.push_back(88);
      scores.push_back(93);
      scores.push_back(68);
      scores.push_back(50);
      scores.push_back(77);
      
    4. { } to initialize with comma-delimited list
      // Empty vector
      vector<int> scores;
      
      // Vector now holds 5 integers
      scores = { 88, 93, 68, 50, 77 };
      
    5. Copy using =
      vector<int> scores = { 88, 93, 68, 50, 77 };
      
      // exams contains same 5 integers
      vector<int> exams = scores;
      
  4. Other helpful vector methods
    1. size() method return number of elements in the vector
      vector<int> scores = { 88, 93, 68, 50, 77 };
      cout << scores.size();  // 5
      
    2. front() method returns the first element
      // Equivalent
      firstNum = scores.at(0);
      firstNum = scores.front();
      
    3. back() method returns the last element
      // Equivalent
      lastNum = scores.at(scores.size() - 1);
      lastNum = scores.back();
      
    4. resize(newSize) method resizes the vector
      // Vector holds only 5 integers 
      vector<int> scores(5);
      
      // Now vector holds 10 integers 
      scores.resize(10);
      
    5. clear() method removes all elements from the vector
      vector<int> scores(5);
      cout << scores.size();   // 5
      scores.clear();
      cout << scores.size();   // 0
      
  5. Looping (iterating) through a vector
    1. Use 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] << " ";
      }
      
    2. for-each loop useful when index number is not important
      // score is assigned each element in scores 
      for (int score : scores) {
      	cout << score << " ";
      }
      
    3. Warning: for-each loop makes a copy of each element unless using &
      // scores is unchanged because s is a copy!
      for (int s : scores) {
      	s++;
      }
      	
      // Pass-by-reference changes scores array
      for (int &s : scores) {
      	s++;
      }
      
  6. Passing vectors to functions
    1. Vectors follow pass-by-value and pass-by-reference rules of primitive data types
      // nums is passed by value (copy)
      int Sum(vector<int> nums) {
      	int sum = 0;
      	for (int n : nums) {
      		sum += n;
      	}
      
      	return sum;
      }
      
    2. Passing a vector to a function
      vector<int> powersOfTwo = { 2, 4, 8, 16, 32 };
      int sum = Sum(powersOfTwo);   // 62
      
    3. Example of pass-by-reference
      // 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;
      	}
      }
      
    4. Passing a vector by value is computationally expensive, best to pass vector by reference and write-protect with 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;
      }
      
    5. A function may return a vector
      // 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);