C++ 检查元素是否位于C++;布景真的很慢
我正在实现一个算法,这意味着需要大量检查元素是否在集合/列表中。我使用的是C++ 检查元素是否位于C++;布景真的很慢,c++,performance,set,C++,Performance,Set,我正在实现一个算法,这意味着需要大量检查元素是否在集合/列表中。我使用的是std::vector容器,但随着向量的增长,时间呈指数增长 我决定尝试使用std::set容器,这样就不必查看整个容器以了解它是否包含某个元素。 我实现了以下函数,用于检查元素是否是给定集合的一部分: bool in_set(set<Node> node_set){ return node_set.find(*this) != node_set.end(); } 我实现的比较运算符如下所示: class
std::vector
容器,但随着向量的增长,时间呈指数增长
我决定尝试使用std::set
容器,这样就不必查看整个容器以了解它是否包含某个元素。
我实现了以下函数,用于检查元素是否是给定集合的一部分:
bool in_set(set<Node> node_set){
return node_set.find(*this) != node_set.end();
}
我实现的比较运算符如下所示:
class Node{
public:
int d;
int h_score;
int coordinates [3];
Node* parent_address;
};
bool operator<(Node other) const{
return concatenate(concatenate(this->coordinates[0], this->coordinates[1]), this->coordinates[2]) <
concatenate(concatenate(other.coordinates[0], other.coordinates[1]), other.coordinates[2]);
}
int concatenate(int i, int j) {
int result = 0;
for (int x = i; x <= j; x++) {
result = result * 10 + x;
}
return result;
}
bool操作符坐标[0],this->坐标[1]),this->坐标[2])
连接(连接(其他坐标[0],其他坐标[1]),其他坐标[2]);
}
编辑:连接函数在执行时似乎不会占用很多时间,它看起来如下所示:
class Node{
public:
int d;
int h_score;
int coordinates [3];
Node* parent_address;
};
bool operator<(Node other) const{
return concatenate(concatenate(this->coordinates[0], this->coordinates[1]), this->coordinates[2]) <
concatenate(concatenate(other.coordinates[0], other.coordinates[1]), other.coordinates[2]);
}
int concatenate(int i, int j) {
int result = 0;
for (int x = i; x <= j; x++) {
result = result * 10 + x;
}
return result;
}
int串联(inti,intj){
int结果=0;
对于(intx=i;x您的操作符首先,您可以尝试将Set作为const&传递,而不是在操作符<中也作为const&
bool in_set(const set<Node>& node_set){
return node_set.find(*this) != node_set.end();
}
bool in_集(常量集和节点集){
返回node_set.find(*this)!=node_set.end();
}
及
bool运算符
你知道为什么要花这么多时间吗
concatenate(11000000)
在我的raspberry pi上花费1.3秒,这样做太慢了,而且实际上没有用
另外请注意,由于可能的溢出,CONTAINATE可以为不同的节点提供相同的结果,这与运算符不兼容。如果您真的这样传递集合?按值传递?在类声明中也缺少分号,请发布实际的可编译代码。了解如何创建.s/指数/线性/也许吧?另外,一定要把concatenate
的来源发出来。如果你的性能有问题,那是在你的操作符中Y
这里是如何修复你用得不好的set
的问题,而实际上问题X
是一些数据结构的性能问题。我不相信set
是pr对于X
的操作解决方案,我怀疑某种类型的B-树将是更好的选择。在集合中确实存在的问题,真正的问题不是拷贝,而是操作符使用非常昂贵的连接的工作方式必须在这里使用std::tie
或std::make\u tuple
。