将二叉搜索与向量一起使用
Using Binary Search with Vectors.
我正在尝试实现一种算法,该算法对于第一个向量中的每个字符串,它会在第二个向量中进行二分搜索,如果找到匹配项,它将输出"YES:",否则将输出"No:"。
现在在我的程序中,我的算法总是输出"NO:",我无法找出出了什么问题。任何提示或提示将不胜感激。
我的二叉搜索:
bool binary_search(const vector<string>& sorted_vec, string key) {
size_t mid, left = 0 ;
size_t right = sorted_vec.size(); // one position passed the right end
while (left < right) {
mid = left + (right - left)/2;
if (key > sorted_vec[mid]){
left = mid+1;
} else if (key < sorted_vec[mid]){
right = mid;
} else {
return true;
}
return false;
}
}
我的算法:
if(algo_speed == "fast"){
string key = fileContent[i];
while(getline(ifs1, line)){
fileContent1.push_back(line);
}
sort(fileContent1.begin(), fileContent1.end());
for(size_t i = 0; i < fileContent.size(); i++){
string temp = fileContent[i];
bool found = binary_search(fileContent1,temp) ;
if(found == true) {
cout << "YES:" << fileContent.at(i) << endl;
} else {
cout << "NO:" << fileContent.at(i) << endl;
}
}
}
您在第一次未命中时退出函数,并带有错位的return false
:
bool binary_search(const vector<string>& sorted_vec, string key) {
size_t mid, left = 0 ;
size_t right = sorted_vec.size(); // one position passed the right end
while (left < right) {
mid = left + (right - left)/2;
if (key > sorted_vec[mid]){
left = mid+1;
}
else if (key < sorted_vec[mid]){
right = mid;
}
else {
return true;
}
}
return false;
}
相关文章:
- 将 boost::odeint 与向量类一起使用,而无需调整向量的大小
- 将 [][] 运算符与向量一起使用?
- 如何在 c++ 中将变换与对的向量一起使用
- 与unordered_map向量一起使用的最小示例中的scoped_allocator_adaptor错误
- 将许多向量排序在一起
- 对象的序列化向量为STD :: String,以与MPI一起使用
- C 操作员超载将3个向量加在一起
- 如何将基于范围的 for 循环与未来的<T>向量一起使用
- 如何将"查找"和"substr"函数与向量一起使用?
- 如何将find_first_not_of与字符串向量一起使用
- 尝试实现通过引用传递的向量以与二叉树一起使用,我错过了什么
- 将Mutex和lock_guard与C++中的向量一起使用
- 将 boost odeint 与 std::map 和自定义向量空间代数一起使用时,没有可行的重载'='
- 创建两个或多个std::向量时没有bad_alloc,它们一起超过了内存(MSVC)
- 将赋值运算符与 unique_ptr 向量一起使用
- 在 c++ 中将向量与一个或多个相似元素组合在一起
- 与向量和结构一起工作
- 将 at() 与自定义对象的向量一起使用时的分割错误
- 自定义分配器有时会与stl向量一起崩溃
- 将 C++ 中的"extern C"与 ctypes 的向量一起使用