问题描述:
考虑一些有std::string name
成员的结构.为清楚起见,我们假设它是a struct Human
,代表人们的信息.除此之外,name
它还可以有许多其他数据成员.
让一个容器std::vector<Human> vec
,对象已经排序name
.同样为了清楚,假设所有名称都是唯一的.
问题是:nameToFind
如果数组中存在具有此名称的元素,请找出一些字符串.
解决方案和我的进展:
明显和自然的解决方案似乎使用该std::binary_search
功能执行二进制搜索.但是存在一个问题:被搜索的元素std::string
的类型(Human
)与容器()中元素的类型不同,并且std :: binary_search需要一个规则来比较这些元素.我尝试用三种方式解决这个问题,如下所述.前两个是为了说明我的解决方案的演变和我遇到的问题.我的主要问题涉及第三个问题.
尝试1:转换std::string
为Human
.
写一个比较函数:
bool compareHumansByNames( const Human& lhs, const Human& rhs )
{
return lhs.name < rhs.name;
}
Run Code Online (Sandbox Code Playgroud)
然后添加一个构造函数,该构造函数构造一个Human
对象std::string
:
struct Human
{
Human( const std::string& s );
//... other methods
std::string name;
//... other members
};
Run Code Online (Sandbox Code Playgroud)
并使用以下形式的binary_search:
std::binary_search( vec.begin(), vec.end(), nameToFind, compareHumansByNames ); …
Run Code Online (Sandbox Code Playgroud)