[英]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.