提问人:Peter King 提问时间:10/21/2020 更新时间:10/21/2020 访问量:439
如何使用 std::find 查找具有结构成员值的集合元素?
How do I use the std::find to find a set element with a struct member value?
问:
struct Node{
int id;
float x;
float y;
float z;
Node(int newId,float newX,float newY,float newZ){id=newId;x=newX;y=newY;z=newZ;}
bool operator<(const Node& rhs)const {return id < rhs.id;}
};
set<Node> graph;
Node a(1,2,3,4);
Node b(2,1,2,3);
Node c(3,4,5,6);
graph.insert(a);
graph.insert(b);
graph.insert(c);
我想使用 find 函数来查找具有特定 id 的元素。
类似的东西会返回一个迭代器到 id 为 3, x 4, y 5, z 6 的元素。
目前,find 函数将只接受初始化的 Node 作为参数。graph
Node n = graph.find(3)
答:
0赞
eerorika
10/21/2020
#1
如何使用 std::find 查找具有结构成员值的集合元素?
目前,find 函数将只接受初始化的 Node 作为参数。
严格来说,完全没有这样的要求。可以传递与元素类型相当的任何类型的对象。也就是说,您可以使用 .std::find
std::find_if
std::find
请注意,(like ) 具有线性复杂度。如果您想要一个基于相关整数的元素可以有效查找元素的数据结构,那么您需要使用关联映射而不是集合。std::find_if
std::find
评论
0赞
Eugene
10/21/2020
std::find
并且始终具有线性复杂度 - 迭代器是否具有随机访问并不重要。std::find_if
0赞
eerorika
10/21/2020
@Eugene 哦,是的。好点子。我在想.答案已修复。std::distance
2赞
Eugene
10/21/2020
#2
您尝试使用的是 而不是 .您可以使用类似于以下功能轻松执行您想做的事:set<Node>::find()
std::find()
std::find()
std::find_if()
auto iter = std::find_if( graph.begin(), graph.end(), [](const Node& node){return node.id==3;});
此解决方案的问题在于,并且具有计算复杂性(其中是范围内的元素数),而使用只需要复杂性。如果你稍微改变你的设计(并且你至少使用C++14),你可以实现这一点。std::find()
std::find_if()
O(n)
n
set<Node>::find()
O(log(n))
首先,对 struct Node 使用 non-member,并添加更多比较运算符:operator<
struct Node{
int id;
float x;
float y;
float z;
Node(int newId,float newX,float newY,float newZ){id=newId;x=newX;y=newY;z=newZ;}
};
bool operator<(const Node& lhs, const Node& rhs)const {return lhs.id < rhs.id;}
bool operator<(const Node& lhs, int rhs)const {return lhs.id < rhs;}
bool operator<(int lhs, const Node& rhs)const {return lhs < rhs.id;}
接下来,您需要使用带有透明比较器的集合:
std::set<Node, std::less<>> graph;
现在,您正在尝试的应该有效:
auto iter = graph.find(3)
评论