我有一个类 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
具有包含节点的 vector 对象的方法
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();
}
当我把它改成这个时,我得到了以下错误
Error 1 error C2446: '==' : no conversion from 'const int' to 'Node *' microsoft visual studio 11.0\vc\include\xutility
Error 2 error C2040: '==' : 'Node *' differs in levels of indirection from '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; });
附言。虽然c++11
是你问题的标签,你没有使用 C++11 的任何好的特性!
PS2。注意你的第一个例子 vector<Node>
会出现切片问题。
PS3。在你的第一个例子中,你不需要也不应该使用 new
.只是 nodes.push_back(Node(22));
或 nodes.emplace_back(22);
.
关于c++ - std::find 包含指针的 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22760062/