[英]How to search a list element, STL C++
I havd a problem with my code. 我的代码存在问题。 I have class named CPerson. 我有一个名为CPerson的班级。
class CPerson {
private:
string name;
string lastName;
int age;
char *pPesel;
public:
CPerson( string i, string n, int w, char *pPes);
...
};
I have a list. 我有一份清单。
list <CPerson> lst;
list <CPerson> ::iterator it;
it = lst.begin();
CPerson wzor1("John", "Steward", 22, "2323" );
When i fill it up, i want find an CPerson instance whose lastName
field begins, for example, with "Kow". 当我填满它时,我想找到一个其lastName
字段开始的CPerson实例,例如“Kow”。
Is it possible to make that "Kow" as a parameter to the any function? 有可能将“Kow”作为任何函数的参数吗?
I was trying with find
or find_if
but it never worked, dont know how to write a predicate, any ideas? 我尝试使用find
或find_if
但它从未起作用,不知道如何编写谓词,任何想法?
A predicate is like a call back function on each element while iterating over the container. 谓词就像是在迭代容器时对每个元素的回调函数。
bool VerifyLastName( CPerson& obj )
{
return (obj.getLastName() == "Kow");
}
std::list<CPerson>::iterator it = std::find_if(lst.begin(), lst.end(), VerifyLastName);
If it
is not equal to the lst.end()
, then iterator is pointing to the object with the member whose last name is "Kow". 如果it
不等于lst.end()
,则迭代器指向具有姓氏为“Kow”的成员的对象。
//Create a member function getLastName in your class
std::string CPerson::getLastName( void ){
return lastname;
}
//Create a function object for find_if use.
struct checkLastName{
checkLastName(const std::string & test):checkName(test){}
bool operator()( CPerson& ob ){
return ob.getLastName().substr(0, checkName.size()).compare(checkName);
}
std::string checkName;
};
std::string lname;
cin>>lname; //"Kow"
//Use std::find_if
std::list<CPerson>::iterator it =
std::find_if(lst.begin(),
lst.end(), checkLastName(lname));
if(it!=lst.end())
std::cout<<" Found ";
With C++11, you can use lambda function as: 使用C ++ 11,您可以使用lambda函数:
std::list<CPerson>::iterator it =
std::find_if(lst.begin(),
lst.end(),
[lname](CPerson const& ob){
return ob.getLastName().substr(0, lname.size()).compare(lname);
}));
Simple use of find_if is shown in http://www.cplusplus.com/reference/algorithm/find_if/ with a simple predicate function (IsOdd). find_if的简单使用在http://www.cplusplus.com/reference/algorithm/find_if/中显示,带有一个简单的谓词函数(IsOdd)。 To add an argument you are probably better off using a function object (functor) or bind1st on a binary function http://www.cplusplus.com/reference/functional/bind1st/ . 要添加参数,最好在二进制函数http://www.cplusplus.com/reference/functional/bind1st/上使用函数对象(仿函数)或bind1st。
If you are using C++11 you can use a lambda/anonymous function. 如果您使用的是C ++ 11,则可以使用lambda / anonymous函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.