我现在正在做我的家庭作业的第4部分,我试图弄清楚如何二元搜索只是字符串数组中的前14个字符。我们得到了两个.csv文件:
01110011100110是模拟条形码。
Inventory.csv:以逗号分隔的库存项目 - 条形码,产品,价格 前五行:
01001010100011,Air freshener,12.43
01101000111101,Alfredo sauce,10.71
10000010100101,All spice,4.14
00011011001111,Allergy medication,20.06
00101010111011,Aluminum foil,8.92
Carts.csv:A'购物车'包含购买条形码 前五行:
01000011010100,00010011010100
00110111100000
00100110100000,01011000110111,01011101000110,01011101000000,01001110000010
01110101100101,00100111110101,00101101110110,00100110000000,00100000001100,00101101011100
00101100111110,01000110110000,01010110111110,00100111111001,01011101101010,01011011010011,00010011010100,01010111101001
我正在完成作业的第4部分: 第4部分:编写一个函数来读入Carts.csv文件。一次读一行并处理它。流程步骤如下: 一个。根据逗号分隔符分隔每个购物车中的条形码 湾对于每个条形码,请在产品列表中查找条形码。 C。从产品字符串数据行中提取价格,并将其添加到购物车的运行总计中。 d。处理完生产线后,输出购物车的总价。 即从步骤(a)开始重复,直到文件结束。
当我尝试查找它返回-1时,它正在比较整行而不仅仅是它的一部分。二进制搜索如何只是字符串的一部分。以下是我的代码的摘录:
int binarySearch(string* list, int size, string value){
int first = 0,
last = size - 1, middle,
position = -1;
bool found = false;
while (!found && first <= last){
middle = (first + last) / 2;
if (list[middle].compare(value) == 0){
found = true;
position = middle;
}
else if (list[middle].compare(value) > 0)
last = middle - 1;
else
first = middle + 1;
}
return position;
}
void processFile(string filename, string* list, int size){
ifstream file(filename);
string line;
int count = 1;
if (file.is_open()){
while (!file.eof()){
int ctr = 0;
int start = 0;
getline(file, line);
string substring = "";
int find = line.find(COMMA);
cout << "Cart " << count << ": ";
while (find != string::npos){
substring = line.substr(start, find - start);
int position = binarySearch(list, size, substring);
cout << position << " ";
start = find + 1;
ctr++;
find = line.find(COMMA, start);
}
if (ctr > 0 || find == -1){
substring = line.substr(start, line.length() - start);
int position = binarySearch(list, size, substring);
cout << position << endl;
count++;
}
}
}
file.close();
}
答案 0 :(得分:1)
尝试以下功能实现
int binarySearch( const std::string* list, int size, std::string value )
{
int position = -1;
int first = 0, last = size - 1;
while ( first <= last )
{
int middle = ( first + last ) / 2;
int result = list[middle].substr( 0, value.size() ).compare( value );
if ( result == 0 )
{
position = middle;
break;
}
else if ( result > 0 )
{
last = middle - 1;
}
else
{
first = middle + 1;
}
}
return position;
}
当然,数组列表必须按照升序排列的条形码进行排序。