什么是最快检查字符串数组中是否存在字符串的方法
What is the fastest way to check if a string is present in a string array?
我希望能够检查字符串std::string x
是否等于字符串数组std::string y[N]
中的任何值。我知道如何使用for
循环并使用if
语句来执行此操作,但是我可以做到这一点更快吗?C 中是否有内置功能可以执行此操作?
假定您使用stl类,可以使用一些机制,具体取决于问题的域。
例如,如果阵列未排序,那么这并不重要:有一些stdlib算法可以更好地传达意图并收缩代码,但是它们的性能将等同于一个简单的前面循环。此代码在性能方面与简单的循环相同。
std::vector<std::string> strings = /*...*/;
//This will find the first string that matches the provided value and return its iterator
auto found_string_iterator = std::find(strings.begin(), strings.end(), "Desired String");
if(found_string_iterator != strings.end()) //found it
std::cout << *found_string_iterator << std::endl;
else //Did not find it
std::cout << "No such string found." << std::endl;
如果分类集合,则可以使用二进制搜索,从而极大地改善了性能:
std::vector<std::string> sorted_strings = /*...*/;
//In a sorted collection, this returns iterators to all strings matching the provided value
auto string_range_iterators = std::equal_range(strings.begin(), strings.end(), "Desired String");
if(string_range_iterators.first != strings.end()) {
for ( auto i = string_range_iterators.first; i != string_range_iterators.second; ++i )
std::cout << *i << std::endl;
} else {
std::cout << "No Strings found." << std::endl;
如果您不需要集合中的重复字符串,则可以使用set
或unordered_set
来收集字符串,这至少可以保证二进制搜索的性能,如果您使用unordered_set
,则可以更快地。
std::set<std::string> collected_strings = /*...*/;
auto found_string_iterator = collected_strings.find("Desired String");
if(found_string_iterator != strings.end()) //found it
std::cout << *found_string_iterator << std::endl;
else //Did not find it
std::cout << "No such string found." << std::endl;
内置容器是 std::unordered_set<std::string>
用该unordered_set
替换字符串数组,并且检查将变得更快:
bool contains( const std::unordered_set<std::string>& set, const std::string& s )
{
return set.find( s ) != set.end();
}
相关文章:
- C++-字符串是否包含一个带有简单循环的单词
- 将常量字符串添加到非常量字符串是否会给出常量字符串
- 检查字符串是否"null" C++
- 使用XOR查找O(n)-解决方案中的两个字符串是否为变位符
- 检查字符串是否为整数
- 使用 SET(C++) 检查两个给定字符串是否是字谜时出现运行时错误
- 如何检查字符串是否正确以将其转换为 int?
- 程序检查字符串是否只包含 1 和 0?
- 检查字符串是否是拉平德罗姆
- 尝试使用 indexOf 创建一个 if 语句来检查字符串是否包含字符.有一点麻烦
- 通过默认复制构造函数比较 C++ 字符串是否会影响性能,原因为何?
- gtest:检查字符串是否等于两个字符串之一
- 如何检查字符串是否包含所有这些:数字、字母和特殊字符
- 如何检查字符串是否以C++中的"ed"结尾;
- 字符串是否在其构造函数中复制数据
- 检查字符串是否是数字,然后将该数字转换为 int?
- 如何检查一个字符串是否包含多个其他字符串?
- 检查字符串是否仅包含字母
- 如何根据一个特定字母的出现来确定两个字符串是否相等?
- 查找字符串是否包含字符串向量的任何一个元素的最佳方法