Overview (Generic algorithm)
Most algorithms in the header file are defined in the algorithm.
The standard library is also the first file numeric it defines a common set of algorithms.
#include <iostream> #include <numeric> #include <vector> #include <algorithm>using namespace Std;int Main () { vector<int> vec; for (size_t t=0; t! =), ++t) { vec.push_back (t); } int val=42; We will find the value //assuming that the desired element is found in the VEC, then the return result points to it, otherwise the result is vec.cend () Auto Result=find (Vec.cbegin (), Vec.cend (), Val); Report results cout<< "The value" <<val << (Result==vec.cend ()?"Isn't present": "Is Present") <<endl; return 0;}
Calling the Find method, finding Val between Vec.cbegin () and Vec.cend () finds that the result points to that element. Result is an iterator that returns a second parameter if it is not found. is Cend ().
String Val= "a value"; We are looking for the value //This call finds the string element in list auto Result=find (Lst.cbegin (), Lst.cend (), Val);
And so on, there are many types, not just this one.
How the algorithm works find Works 1, the first element in the interview sequence 2, compare this element with the value we are looking for 3, assuming this element matches what we are looking for, find returns the value 4 that identifies this element, otherwise. Find advances to the next element, repeatedly running steps 2 and 35, assuming that the end of the sequence is reached, find should stop 6, assuming that find arrives at the end of the sequence, it should return a value that indicates that the element was not found.
This value and the value returned by step 3 must have a compatible type.
Iterators make the algorithm independent of the container, but the algorithm relies on the element type
Exercises:
/*** Features: Generics Overview * Date: June 16, 2014 08:10:18* Author: cutter_point*/#include <iostream> #include <numeric> #include < vector> #include <algorithm> #include <string>using namespace Std;int main () {vector<int> vec={ 22,22,22,2,222,2,22,22,222,22,2,2,22,22}; int val=22; Auto Result=count (Vec.cbegin (), Vec.cend (), Val); cout<< "The value to find is:" <<val<<endl << "appeared" <<result<< "<<endl;/*", String val= " A value "; We are looking for the value//This call looks in the list for the string element auto Result=find (Lst.cbegin (), Lst.cend (), Val); Vector<int> VEC; for (size_t t=0; t! =), ++t) {vec.push_back (t); } int val=42; The value we will look for//assumes that the desired element is found in the VEC, then the result is returned to it, otherwise the result is vec.cend () Auto Result=find (Vec.cbegin (), Vec.cend (), Val); Report results cout<< "the value" <<val << (Result==vec.cend (), "is not Present": "Is Present") <<e ndl;*/return 0;}
Copyright notice: This article blog original articles, blogs, without consent, may not be reproduced.
"Footstep C++primer" 30, overview (generic algorithm)