<STL Application> vector & find_if
Someone asked a struct named C as follows:
code:
struct C{ int v1; int v2;};
It should be used to declare a vector as a vector <C> CV;
What should I do when I want to search for internal elements ??
The general solution is to use the for () loop to search for rows. In fact, such a straight picture is also simple.
This provides another solution for ease of use ....
Find_if () provides the find_if () statement, but it is a pity that only one statement can be written.
In addition, the operator inputs the type of * iterator, rather than the equivalent value.
For example, V1 and V2 of the objects in this CV are sequential
V1 v2
1 100
2 52
3 25
4 75
5 84
6 33
So what should we do if we look for an object with V2 = 75?
1. functor point
code:
bool Cfind75(const C& obj){ return obj.v2==75;}
2. functor
code:
class Cfind75{ public: bool operator()(const C& obj) { return obj.v2==75; }};
However, it would be worse than the limit value to be killed !!
No thanks... so this time the template will be used ....
So we have to change
code:
template<int n>class CComp{ public: bool operator()(const C& lhs) { return (lhs.v2==n); }};
How to use it ?? Very simple ....
code:
vector<C>::iterator cviter = find_if(cv.begin(),cv.end(),CComp<75>());
Otherwise, cviter is the position where the V2 value of the C-type object in the original CV is 75.
--
I have no questions about small applications. However, those unfamiliar with STL are often ignored.
- # Include <iostream>
- # Include <algorithm>
- # Include <vector>
- # Include <cstdlib>
- Using namespace STD;
- Struct C
- {
- C (): V1 (0), V2 (0 ){}
- C (const Int & val1, const Int & val2): V1 (val1), V2 (val2 ){}
- C Operator () (const Int & val1, const Int & val2)
- {
- V1 = val1;
- V2 = val2;
- Return * this;
- }
- ~ C (){}
- Int V1;
- Int V2;
- };
- Template <int n>
- Class ccomp {
- Public:
- Bool operator () (const C & LHS)
- {
- Return (LHS. v2 = N );
- }
- };
- Int main (INT argc, char * argv [])
- {
- Vector <C> CV;
- C val;
- Cv. push_back (Val (1,100 ));
- Cv. push_back (Val (2, 52 ));
- Cv. push_back (Val (3,25 ));
- Cv. push_back (Val (4, 75 ));
- Cv. push_back (Val (5, 84 ));
- Cv. push_back (Val (6, 33 ));
- Vector <C >:: iterator cviter =
- Find_if (cv. Begin (), cv. End (), ccomp <75> ());
- Cout <cviter-> V1 <"" <cviter-> V2 <Endl;
- Cout <Endl;
- System ("pause ");
- Return 0;
- }