std :: find for包含指针的向量

时间:2014-03-31 11:09:43

标签: c++ c++11 vector stl polymorphism

我有一个类Node和派生类ChildNode,如下所示

#include<iostream>
using namespace std;
class Node
{
public:
    int nodeId;
    bool operator==(int id) const { return (this->nodeId ==id);}; //used in STL Find function
    Node(int id)
    {
        this->nodeId=id;
    }
    ~Node(void)
    {
    }
    virtual void SaySomeThing()
    {
        cout<<"Hey! I am node"<<endl;
    }
};
class ChildNode:public Node
{
public:
    ChildNode(int id):Node(id){};
    virtual void SaySomeThing()
    {
        cout<<"Hey! I am a child node"<<endl;
    }
};

现在我在main中调用NodeVectorTest方法,该方法包含包含节点

的向量对象
void NodeVectorTest()
{
    vector<Node> nodes;
    Node *node=new Node(22);
    nodes.push_back(*node);
    delete node;
    node=new ChildNode(23);
    nodes.push_back(*node);
    delete node;
    node=new Node(33);
    nodes.push_back(*node);
    delete node;

    //Find node
    vector<Node>::iterator nodePosition;
    int nodeId=23;
    nodePosition =find(nodes.begin(),nodes.end(),nodeId);
    if(nodePosition == nodes.end()) { ///we didnt find the node id ..

        cerr<<"node id "<< nodeId <<" Could not be found "<<endl;

        return ;
    }

    else{ //now we have the right node to do our desired stuff
        (*nodePosition).SaySomeThing();
    }
}

当我找到节点23时,它被转换为Node对象而不是Node *,因此它显示输出为Hey! I am node以实现多态性,我将此vector<Node> nodes;转换为vector<Node*> nodes;为代码如下:

vector<Node*> nodes;
Node *node=new Node(22);
nodes.push_back(node);
node=new ChildNode(23);
nodes.push_back(node);
node=new Node(33);
nodes.push_back(node);

//Find node
vector<Node*>::iterator nodePosition;
int nodeId=23;
nodePosition =find(nodes.begin(),nodes.end(),nodeId);

if(nodePosition == nodes.end()) { ///we didnt find the node id ..

    cerr<<"node id "<< nodeId <<" Could not be found "<<endl;

    return ;
}

else{ //now we have the right node to do our desired stuff
    (*nodePosition).SaySomeThing();
}

当我将其更改为此时,我收到以下错误

  

错误1错误C2446:&#39; ==&#39; :没有来自&#39; const int&#39;到节点*&#39; microsoft visual studio 11.0 \ vc \ include \ xutility
  错误2错误C2040:&#39; ==&#39; :&#39; Node *&#39;不同的间接水平来自&#39; const int&#39; microsoft visual studio 11.0 \ vc \ include \ xutility

在这方面有任何帮助吗?

2 个答案:

答案 0 :(得分:4)

nodes的元素是指针Node,而不是Node。因此,您应该使用std::find_if

nodePosition = find_if(nodes.begin(), nodes.end(),
    [nodeId](Node *p) { return *p == nodeId; });

PS。虽然c++11是您问题的标记,但您没有使用C ++ 11的任何优秀功能!

PS2。请注意,您的第一个示例vector<Node>将出现切片问题

PS3。在第一个示例中,您不需要也不应该使用new。只需nodes.push_back(Node(22));nodes.emplace_back(22);

答案 1 :(得分:1)

请注意,默认情况下find将使用operator==将对象与同一类型的另一个对象进行比较。在这种情况下,您需要重载bool operator==(const Node*, const Node*)这是不可能的。对你来说更好的选择是使用find with predicate,它在函数std::find_if中实现。

相关问题