// Native_Iterators.cpp : Defines the entry point for the console application. /* ________________________________________________________________ W O R K I N G W I T H S T L A L G O R I T H M S & I T E R A T O R S These are funtion templates that allow us to iteratate over a range of values in a collection or container data structure. Instead of using Vector.Sort or array.sort, the sort algorithm can be used to sort ANY container that uses the begin and end iterators. Sort stands on its own and is not a member of the vector/array class. That way, one sort algorithm can be used for several types of collections. Algorithms can be used with any data structure that supports iterators. The standard function Accumulate Function Another funtion called consecutive allows us to insert/delete elements Find is another one that is helpful. Count and Find are also often used. Ron Kessler Created 1/8/2017 Native C++ Version Run using CTL-F5 __________________________________________________________________ */ #include "stdafx.h" #include #include #include #include //for the accumulate function #include //to use built-in algorithm functions like sort using namespace std; int main() { cout << "Working With The Standard Template Library & Iterators"<< "\n\n"; //---create a vector of integers vector ages{ 14, 33, 24, 53, 20 }; //the size is determined by the elements in {} int total = 0; //---Option 1: Get total of all vector values using a for loop for (int x = 0; x < ages.size (); x++) { total += ages [x]; } cout << "Using a For Loop, the total of all ages is : " << total << "\n\n"; //---Option 2: Get total of all vector values using a "Ranged For" loop (Like a For-Each loop) // Use int element or auto to define the iterator variable int total2= 0; for (auto element : ages) //auto tells compiler to figure out the correct data type { total2 += element; } cout << "Using a Ranged For Loop, the total is : " << total2 << "\n\n"; //---Option 3: Get total of all vector values using stl accumulator function and iterators //begin and end are the iterators that are exposed by the container/collection of vector. int total3 = accumulate (begin (ages), end (ages), 0); //0 = the starting value of total3 cout << "Using the accumulate function, the total is : " << total3 << "\n\n"; //Option 4: Working with strings string mySentence ="This is a sentence being stored in a std::string instance."; //---find # of spaces in the string cout << "Working with strings like : " << mySentence << "\n\n"; int numSpaces = count (begin (mySentence), end(mySentence), ' '); // ' ' defines the space cout << "My sentence contains " << numSpaces<< " spaces.\n\n"; //---find which character the first : is at. int idx = mySentence.find_first_of(':'); cout << "The first colon is at position " << idx << "\n\n"; return 0; }