我有一个包含我的类X的许多元素的向量。 我需要在这个向量中找到第一个出现的元素,称S为S.attrribute1> someVariable。 someVariable将无法修复。我该如何为此进行binary_search? (不是c ++ 11 / c ++ 14)。我可以用更大的搜索功能编写std :: binary_search(理想情况下是检查相等性),但那会是错误的吗?什么是快速搜索的正确策略?
答案 0 :(得分:2)
根据定义,只有当矢量按照二进制搜索的谓词 排序 时,才能进行二分搜索。
因此,除非向量中的所有元素" S.attribute1> someVariable "位于所有不是的元素之后,这将是一个非首发,就在大门之外。
如果向量中的所有元素都以其他方式排序,那么"其他方式"是唯一可以实现的二进制搜索。
假设它们是,你必须使用某种比较器,它在属性上指定严格的弱排序,以便首先提出你的排序向量:
class comparator {
public:
bool operator()(const your_class &a, const your_class &b) const
{
return a.attribute1 < b.attribute1;
}
};
诀窍在于,如果您想单独使用属性值进行搜索,则需要使用可与std::binary_search
template< class ForwardIt, class T, class Compare >
bool binary_search( ForwardIt first, ForwardIt last,
const T& value, Compare comp );
一起使用的比较器:
comp(value, element)
要使std :: binary_search成功,范围[first,last)必须为 至少部分有序,即它必须满足以下所有要求 要求:
对于所有元素,如果元素&lt; value或comp(element,value)为true 那么!(value&lt; element)或!comp(value,element)也是如此
因此,唯一的要求是comp(element, value)
和T
需要工作。您可以传递class search_comparator {
public:
bool operator()(const your_class &a, const attribute_type &b) const
{
return a.attribute1 < b;
}
bool operator()(const attribute_type &a, const your_class &b) const
{
return a < b.attribute1;
}
};
的属性值,而不是要搜索的向量中的整个元素,只要您的比较器可以处理它:
search_comparator
现在,您应该可以使用comparator
代替std::sort
,并按属性值进行二元搜索。
而且,正如我所说,如果向量没有按给定属性排序,所有赌注都会关闭。在这种情况下,您需要首先明确地使用{{1}},或者提出一些自定义容器,以正确的顺序跟踪矢量元素,并分别跟踪主矢量持有他们。或许,使用指针,在这种情况下,您应该能够使用类似的搜索比较器对指针本身执行二进制搜索,而不是查看指针。
答案 1 :(得分:1)
要使std::binary_search
成功,需要对范围进行排序。std::binary_search
,std::lower_bound
适用于已排序的容器。因此,每次在vector
中添加新元素时,都需要对其进行排序。
为此,您可以在插入时使用std::lower_bound
:
class X;
class XCompare
{
public:
bool operator()(const X& first, const X& second) const
{
// your sorting logic
}
};
X value(...);
auto where = std::lower_bound(std::begin(vector), std::end(vector), value, XCompare());
vector.insert(where, value);
再次,您可以使用std::lower_bound
在您的向量中搜索:
auto where = std::lower_bound(std::begin(vector), std::end(vector), searching_value, XCompare());
不要忘记检查std::lower_bound
是否成功:
bool successed = where != std::end(vector) && !(XCompare()(value, *where));
如果您只想知道该元素在向量中,请直接使用std::binary_search
。