In article <1143441709.867871.228430@i40g2000cwc.googlegroups .com>,
tehn.yit.chin@gmail.com wrote:
[color=blue]
> I am trying to experiment <algorithm>'s find to search for an item in a
> vector of struct. My bit of test code is shown below.
>
> #include <iostream>
> #include <vector>
> #include <algorithm>
> #include <string>
>
> struct abc_struct
> {
> std::string student;
> std::string school;
> };
>
> int main()
> {
>
> std::vector<abc_struct> abc;
>
> abc_struct temp_abc;
>
> temp_abc.student = "John Snoden";
> temp_abc.school = "Melbourne high school";
> abc.push_back(temp_abc);
>
> temp_abc.student = "Jane Doe";
> temp_abc.school = "Lareto College";
> abc.push_back(temp_abc);
>
> std::vector<abc_struct>::iterator result;
> temp_abc.student = "John Snoden";
>
> result = find( abc.begin(), abc.end(), temp_abc.student);
>
> if (result == abc.end())
> {
> std::cout << "NOT found\n";
> }
> else
> {
> std::cout << "found\n";
> }
> }
>
>
> When I try to build it, the compiler complains for "no match for for
> operation ==' in std_algo.h. I don't fully understand what the error
> message is trying to say. Am I suppose to provide a camparison function
> for the abc_struct? If I am, is it suppose to be a member function of
> the abc_struct class?
>
> many thanks for your assistance.[/color]
The obvious patch is to simply add an op== that compares an abc_struct
to a string:
bool operator==( const abc_struct& abc, const string& str ) {
return abc.student == str;
}
But, what if you later want to look for abc_structs that have a
particular value for 'school'? In that case, your best bet would be to
provide a function that gets the student or school out of abc_struct and
use the op== provided for the string class. For this though, you can't
use 'find' you must use 'find_if' instead...
struct comp_student : std::binary_function<abc_struct, std::string, bool>
{
bool operator()( const abc_struct& abc, const std::string& name )
const {
return abc.student == name;
}
};
result = find_if( abc.begin(), abc.end(),
std::bind2nd( comp_student(), "John Snoden" ) );
However, since you have to create a structure anyway...
struct has_name
{
std::string name_sought;
has_name( std::string n ): name_sought( n ) { }
bool operator()( const abc_struct& abc ) const {
return abc.student == name_sought;
}
};
result = find_if( abc.begin(), abc.end(), has_name( "John Snoden" ) );
--
Magic depends on tradition and belief. It does not welcome observation,
nor does it profit by experiment. On the other hand, science is based
on experience; it is open to correction by observation and experiment.