C++ 结构向量的二元搜索
我有一个结构向量,它包含这个架构的结构C++ 结构向量的二元搜索,c++,vector,struct,binary-tree,C++,Vector,Struct,Binary Tree,我有一个结构向量,它包含这个架构的结构 struct Main{ int mainID; string mainDIV; string mainNAME; } 可以在结构上使用二进制搜索吗?我知道它很容易使用的价值使用 binary_search( vector.begin() , vector.end() , 5 ) 但有并没有一种方法可以通过回调或其他方法来实际查找struct的属性呢?我找不到任何与这个话题相关的东西。是的,有可能。所取的值仅在与容器的元素进行比较
struct Main{
int mainID;
string mainDIV;
string mainNAME;
}
可以在结构上使用二进制搜索吗?我知道它很容易使用的价值使用
binary_search( vector.begin() , vector.end() , 5 )
但有并没有一种方法可以通过回调或其他方法来实际查找struct的属性呢?我找不到任何与这个话题相关的东西。是的,有可能。所取的
值
仅在与容器的元素进行比较时才有意义。在简单的情况下(如果Main
支持operator,则必须向binary\u search()提供信息)
告诉它如何比较对象。最常见的两种方法是添加一个运算符第二种方法:我不知道我是否愚蠢。但是链接根本没有帮助。是否可以省略字符串并只检查整数?这不会找到具有相同int和字符串的结构吗?您可以添加一些代码来比较其他组件如果mainID上有匹配项,则在Main中使用ents。我最近试图找出我在结构中声明的运算符的相同问题。但是我如何调用二进制搜索?能否请您使用二进制搜索函数提供更多代码?这会抛出此错误C:\Users\Matej\Desktop\PA2\Progtest\2\u trieda\Main.cpp | 107 |错误:无法转换“{invID}”'从''到主'|
// check if this specific Main exists
bool yes = std::binary_search(v.begin(), v.end(), Main{0, "some", "strings"});
// does exactly the same thing as above
bool yes = std::binary_search(v.begin(), v.end(), Main{0, "some", "strings"}
, std::less<Main>{});
// check if there is a Main with mainID 5
bool yes = std::binary_search(v.begin(), v.end(), 5,
[](const Main& element, const int value) {
return element.mainID < value;
});
struct Main {
int mainID ;
string mainDIV ;
string mainNAME ;
bool operator<(const Main & other) const
{
return mainID < other.mainID ;
}
}
struct Main search_key = { 5 } ;
bool yes = std::binary_search( v.begin(), v.end(), search_key ) ;
struct Main
{
Main(int id, const string & a_div, const string & a_name ) : id(id), div(a_div), name(a_name) { }
Main(int id) : id(id) { }
int id ;
string div, name ;
bool operator<(const Main &o) const { return id < o.id ; }
} ;
bool has_3 = std::binary_search( v.begin(), v.end(), Main( 3) ) ;