我在插入排序方面遇到了一些麻烦,从结构中传入数据。 它返回错误:| 98 |在分配时无法将'store'转换为'int'。
struct store{
char tag[5];
int cost;
long int volume;
};
void costSort(store storedEntries[], int count);
void volumeSort(store storedEntries[], int count);
int main(){
store record[100];
ifstream fin;
char choice;
int count = 0;
fin.open("stockdata.txt");
//file read in
if(fin.good())
{
while(!fin.eof())
{
fin >> record[count].tag;
fin >> record[count].cost;
fin >> record[count].volume;
count++;
}
count--;
}
cout << "Main Menu:" << endl;
cout << "c: sort data by Cost\nv: sort data by trade Volume\nq: Quit\nEnter Choice: ";
cin >> choice;
switch(choice)
{
case 'C':
case 'c': //costSort(record, count);
break;
case 'V':
case 'v': volumeSort(record, count);
break;
case 'q':
case 'Q': return 0;
break;
}
return 0;
}
void volumeSort(store record[], int count)
{
int p = 0, item = 0;
for(int i=1; i<count; i++){
cout << "test";
item = record[i];
p = (i - 1);
while(p>=0 && item < record[p]){
record[p+1] = record[p];
p--;
}
record[p+1] = item;
cout << record[i].tag << " " << record[i].volume << endl;
}
}
插入排序在函数void volumeSort()中。 任何建议都会受到赞赏,直到现在我还没有遇到任何问题:S
答案 0 :(得分:1)
您正在尝试将int
与store
进行比较。
除非您重载<
运算符以比较int
和store
,否则无效。
store record[];
int p = 0, item = 0;
//[...]
while (p >= 0 && item < record[p])
//Neither can you assign that
record[p + 1] = item;
运营商示例:
bool operator<(const int &left, const store &s)
{
//You could also do some calculation in here,
//if you want to compare a value inside the struct
//like this:
return left < s.cost;
//Please... do it in place.
//item < record[p].cost;
}
答案 1 :(得分:1)
您正在比较非类似类型,并且没有提供运算符来支持比较(如果正确完成,则没有需要)。目前,您正在将int
与store
进行比较。您应该比较的是两个商店对象的两个volume
成员。
一个可能更接近你想要的简单循环是这样的:
// note: count is size_t, an unsigned magnitude. only used signed
// integer types where it makes sense a negative integer will be
// plausible input.
void volumeSort(store record[], size_t count)
{
for(size_t i=1; i<count; ++i)
{
// compare current element to one below us, swapping if needed
// and stopping as soon as we reach an equal or lesser record
size_t j=i;
while(j>0 && record[j].volume < record[j-1].volume)
{
std::swap(record[j-1], record[j]);
--j;
}
}
}
或类似的东西。请注意比较:
record[j].volume < record[j-1].volume
在while条件下。苹果到苹果......
对于使用标准库insertion_sort
和std::upper_bound
的两个精彩功能的有趣std::rotate
,可以创建相当密集的函数版本,如下所示:< / p>
void insertion_sort(store record[], size_t len)
{
for (auto it = record; it != record+len; ++it)
{
std::rotate(std::upper_bound(record, it, *it,
[](const store& lhs, const store& rhs) { return lhs.volume < rhs.volume; }),
it, std::next(it));
}
}
这比首次看起来效率要高得多,因为使用std::upper_bound
在O(logN)中搜索前景元素的正确位置。然后std::rotate
打开元素所在的洞,并将其交换到位。
只是一些值得思考的东西。加上比较器,即使是补救优化也会内联,它比你想象的还要多。仍然不像std::sort
那样吵闹,通常高度使用多种算法优化,但仍然是良好的大脑食物。
祝你好运。
答案 2 :(得分:0)
如果你想按体积排序,你应该采取 记录[i] .volume即使比较......比较值时类型应该相同..
同样适用于其他情况..