Advanced Vector Operations in C++
Lesson Overview
Welcome to this introductory lesson focused on Advanced Vector Operations without the use of built-in functions. While C++ provides a myriad of built-in functions to simplify vector operations, understanding the concepts behind these key functions significantly improves your ability to solve complex problems and prepares you for scenarios where built-in functions may not exist, or if they do, may not offer the optimal solution.
Count Occurrences Example
Consider a function, countOccurrences, that takes in an array and its size as input, along with a target element. The function should return the number of times the target element appears in the array. We could use the std::count function from the <algorithm> header, but the task requires that we do not use built-in functions.
Our approach to the countOccurrences function is:
-
Initialize Counter: Declare and initialize a variable
countto zero. This will keep track of the occurrences of thetargetin the array. -
Set Up a Loop: Utilize a
forloop to iterate through each element of the array. The loop variableistarts at zero and increments by one in each iteration, continuing untiliis less thansize. -
Check for Target Match: Inside the loop, use an
ifstatement to check if the current array elementarr[i]is equal to thetarget. -
Increment Counter if Match: If the current element matches the
target, increment thecountvariable by one. -
Return Counter: After the loop completes, return the
countvariable, which now contains the total number of occurrences of thetargetelement in the array.
Here's the solution:
Find Index Example
Consider a function, findIndex, that takes in a vector and a target element as input. The function should return the index of the first occurrence of the target element in the vector. If the target is not found, the function should return -1. We could use the std::find function from the <algorithm> header, but the task requires we do not to use built-in functions.
Our approach to the findIndex function is:
-
Set Up a Loop: Utilize a
forloop to iterate through each element of the vector. The loop variableiof starts at zero and increments by one in each iteration, continuing untiliis less than the size of the vector. -
Check for Target Match: Inside the loop, use an
ifstatement to check if the current vector elementvec[i]is equal to thetarget. -
Return Index if Match: If the current element matches the
target, return the current indexiimmediately, indicating the position of the first occurrence of thetargetin the vector. -
Return -1 if Not Found: If the loop completes without finding the
targetelement, return-1to indicate that thetargetis not present in the vector.
Here's the solution:
