Search is a commonly used function for the classes in these standard libraries, such as list and vector, but these classes do not provide the find function, because for custom types, it does not know how to compare two types.
Http://www.cppreference.com/wiki/container/list/start
However, STL provides a common find function (iterator it0, iterator it1, target). The following describes how to use this function.
// Define a simple data structure, Inst.
Class Inst {
Public:
Inst (string nm, int val ){
Name = nm;
Value = val;
} // There was a semicolon before and it should not appear. Thank you for reminding me.
String Name () const {
Return name;
}
Int Value () const {
Return value;
}
Private:
String name;
Int value;
}; // Define a comparison function, with a heavy load of = Operator.
// If both name and value are the same, the instance is the same
Booloperator = (const Inst & a, const Inst & B ){
Return (a. Name () = B. Name () & a. Value () = B. Value ());
}
// If the name is the same, the instance is the same
Booloperator = (const Inst & a, conststring name ){
Return (a. Name () = name );
}
The test is as follows,
List <Inst> elist;
Inst p1 ("abc", 3 );
Inst p2 ("abcdef", 6 );
List <Inst>: iterator it;
// Find must contain the header file <algorithm>
It = std: find (elist. begin (), elist. end (), p2 );
If (it! = Elist. end ())
Cout <(* it). Value () <endl;
String name = "abc ";
It = std: find (elist. begin (), elist. end (), name );
If (it! = Elist. end ())
Cout <(* it). Value () <endl;
However, if the list saves the pointer, as shown below,
List <Inst *> elist;
Inst * p1 = new Inst ("abc", 3 );
Inst * p2 = New Inst ("abcdef", 6 );
List <Inst *>: iterator it;
It = std: find (elist. begin (), elist. end (), p2 );
If (it! = Elist. end ())
Cout <(* it)-> Value () <endl;
String name = "abc ";
It = std: find (elist. begin (), elist. end (), name );
If (it! = Elist. end ())
Cout <(* it)-> Value () <endl;
The comparison function needs to be modified as follows,
Booloperator = (const Inst * a, const Inst * B ){
Return (a-> Name () = B-> Name () & a-> Value () = B-> Value ());
}
Booloperator = (const Inst * a, conststring nm ){
Return (a-> Name () = nm );
}
If any errors occur during STL learning, please correct them. Thank you!