具体来说,我有一个具有多个字符串对象数据成员(NID,customerNumber,studentNumber,fName,lName)的类的对象列表。
我想重用以下代码来搜索与搜索关键字匹配的节点,无论所查找的数据成员是NID还是该类的字符串数据成员的任何其他成员。
nodePtr = firstPtr; for(; nodePtr != NULL && nodePtr->str != str; nodePtr = nodePtr->nextPtr); if(nodePtr != NULL) //the nodePtr points to the node that matches the search key else //no node matched the search key如果它是PHP代码我可以使用变量的值作为另一个的名称:
$node->${$var}但是在C ++中无论如何都要重用代码?
specifically I have a list of objects of a class with multiple string object data members(NID, customerNumber, studentNumber, fName, lName).
I want to reuse the following code to search for the node that matches the search key whether the data member that is looked for is NID or any other of the class's string data members.
nodePtr = firstPtr; for(; nodePtr != NULL && nodePtr->str != str; nodePtr = nodePtr->nextPtr); if(nodePtr != NULL) //the nodePtr points to the node that matches the search key else //no node matched the search keyif it was PHP code I could use the value of a variable as the name of another:
$node->${$var}but in C++ is there anyway to reuse the code?
最满意答案
最灵活的方法是提供谓词作为模板参数:
template <typename Pred> Node * find_if(Node * node, Pred pred) { for (; node && !pred(node); node = node->next); return node; }在C ++ 11中,您可以使用lambda调用它:
if (Node * node = find_if(first, [&](Node * n){return n->NID == nid;})) { // node points to the matching node } else { // not found }或者,如果你被困在过去的年代,一个函数对象:
struct CompareNID { CompareNID(std::string nid) : nid(nid) {} bool operator() {Node * n) {return n->NID == nid;} std::string nid; }; Node * node = find_if(first, CompareNID(nid));或者,因为你的所有字段都是字符串,你可以使用成员指针牺牲灵活性,给出类似于PHP示例的内容:
Node * find(Node * node, std::string Node::*member, std::string const & value) { for (; node && node->*member != value; node = node->next); return node; } Node * node = find(first, &Node::NID, nid);The most flexible way to do this is to provide a predicate as a template parameter:
template <typename Pred> Node * find_if(Node * node, Pred pred) { for (; node && !pred(node); node = node->next); return node; }In C++11, you can call it with a lambda:
if (Node * node = find_if(first, [&](Node * n){return n->NID == nid;})) { // node points to the matching node } else { // not found }or, if you're stuck in ages past, a function object:
struct CompareNID { CompareNID(std::string nid) : nid(nid) {} bool operator() {Node * n) {return n->NID == nid;} std::string nid; }; Node * node = find_if(first, CompareNID(nid));or, since all your fields are strings, you could sacrifice flexibility for tersity using member pointers, giving something similar to your PHP example:
Node * find(Node * node, std::string Node::*member, std::string const & value) { for (; node && node->*member != value; node = node->next); return node; } Node * node = find(first, &Node::NID, nid);更多推荐
发布评论