快速搜索C++中排序的字符串列表可以使用STL库中的std::set
或std::map
容器。这两个容器都是基于红黑树实现的,它们可以快速地进行插入、删除和查找操作。
std::set
是一个关联容器,它存储的元素是唯一的,并且已经按照排序顺序排列。可以使用std::set
的lower_bound
和upper_bound
成员函数进行快速查找。
std::map
是一个关联容器,它的键值对是唯一的,并且已经按照键的排序顺序排列。可以使用std::map
的lower_bound
和upper_bound
成员函数进行快速查找。
以下是一个使用std::set
的示例代码:
#include<iostream>
#include <set>
#include<string>
int main() {
std::set<std::string> strings = {"apple", "banana", "cherry", "date", "fig"};
std::string target = "cherry";
auto it = strings.lower_bound(target);
if (it != strings.end() && *it == target) {
std::cout << "Found "<< target<< std::endl;
} else {
std::cout << "Not found"<< std::endl;
}
return 0;
}
以上代码会输出Found cherry
,因为cherry
在字符串列表中。
以下是一个使用std::map
的示例代码:
#include<iostream>
#include <map>
#include<string>
int main() {
std::map<int, std::string> strings = {{1, "apple"}, {2, "banana"}, {3, "cherry"}, {4, "date"}, {5, "fig"}};
int target_key = 3;
auto it = strings.lower_bound(target_key);
if (it != strings.end() && it->first == target_key) {
std::cout << "Found " << it->second<< std::endl;
} else {
std::cout << "Not found"<< std::endl;
}
return 0;
}
以上代码会输出Found cherry
,因为cherry
在字符串列表中。
领取专属 10元无门槛券
手把手带您无忧上云