【发布时间】:2020-10-06 09:33:54
【问题描述】:
考虑以下集合实现。在这里,我根据 fScore 参数对集合进行了排序。如果我想在“NodeData”中搜索特定“id”的元素,我应该怎么做。 我知道我可以使用“find”在 O(logn) 的集合中搜索“fScore”的任何元素。 有没有比线性搜索(下面实现)更有效的方法来搜索“id”(时间更短)?
#include<iostream>
#include<algorithm>
#include<iterator>
#include<set>
#include<stdlib.h>
#include<vector>
struct NodeData{
int id;
int parent;
double fScore, gScore, hScore;
std::vector<double> nScores;
NodeData(const int& idIn = 0,
const int& parentIn = -1,
const double& fIn = 1,
const double& gIn = 1,
const double& hIn = 1):id(idIn), parent(parentIn),
fScore(fIn), gScore(gIn), hScore(hIn)
{
}
bool operator<(const NodeData& rhs) const {
return fScore < rhs.fScore;
}
};
class test
{
public:
std::set<NodeData> NodeList;
};
int main()
{
test q;
for(int i=1;i<=5;i++)
{
NodeData n1 = {i,1,i,1,1};
q.NodeList.insert(n1);
}
std::set<NodeData>::iterator it;
//search for node with fScore 1 - cost O(logn)
it = q.NodeList.find(1);
if(it != q.NodeList.end()){
std::cout<<"node with fScore 1 found. id = "<<it->id<<std::endl;
}
else{
std::cout<<"node not found = "<<std::endl;
}
//searching for id=3 - Linear search - cost O(n)
int searchId = 3;
std::set<NodeData>::iterator it1 = q.NodeList.begin();
while(it1 != q.NodeList.end())
{
if(it1->id == searchId)
{
std::cout <<"found node with id = "<<it1->id<<std::endl;
}
it1++;
}
}
【问题讨论】:
标签: performance search iterator set