中等
技术面试0 次浏览

字节跳动的搜索业务中,需要对搜索结果进行排序。给定一个包含搜索结果的列表,每个结果是一个包含标题、内容和相关性得分的对象,要求根据相关性得分对结果进行降序排序。请用 C++ 实现该功能。

字节跳动算法工程师
C++排序搜索结果

答题要点

推荐使用自定义比较函数的答题框架。关键要点如下:1. 定义一个表示搜索结果的结构体,包含标题、内容和相关性得分。2. 实现一个自定义的比较函数,用于比较两个搜索结果的相关性得分。3. 使用标准库中的排序函数,如 std::sort,结合自定义比较函数对搜索结果列表进行排序。示例话术:首先定义一个结构体来表示搜索结果,然后实现一个比较函数,该函数根据相关性得分判断两个结果的大小关系。最后使用 std::sort 函数对结果列表进行排序。以下是示例代码:#include <algorithm> #include <vector> struct SearchResult { std::string title; std::string content; double score; }; bool compareResults(const SearchResult& a, const SearchResult& b) { return a.score > b.score; } void sortSearchResults(std::vector<SearchResult>& results) { std::sort(results.begin(), results.end(), compareResults); }