簡體   English   中英

std :: find查找包含指針的向量

[英]std::find for vector containing pointers

我有一個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;
    }
};

現在我主要調用具有向量對象的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 Hey! I am 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:'==':沒有從'const int'到'Node *'的轉換Microsoft Visual Studio 11.0 \\ vc \\ include \\ xutility
錯誤2錯誤C2040:'==':'節點*'在間接級別上與'const int'不同,Microsoft Visual Studio 11.0 \\ vc \\ include \\ xutility

在這方面有幫助嗎?

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);

請注意,默認情況下, find將使用operator==將一個對象與另一個相同類型的對象進行比較。 在這種情況下,您需要重載布爾operator==(const Node*, const Node*) ,這是不可能的。 對您而言,更好的選擇是將find與謂詞一起使用,這在功能std :: find_if中實現

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM