【问题标题】:sort and binary_search on array of struct结构数组上的排序和二进制搜索
【发布时间】:2018-04-07 17:17:25
【问题描述】:

这是我的代码

typedef struct Data{
    int date;
    string currency;
    string exchange;
    float low;
    float high;
    long long int daily_cap;
}Data;

bool comp2(const Data *data1, const Data *data2){
        return (data1->date < data2->date);
}

bool comp1(Data *data1, Data *data2){
    if (data1->date != data2->date)
        return (data1->date < data2->date);
    if (data1->currency != data2->currency)
        return (data1->currency < data2->currency);
    else
        return (data1->exchange < data2->exchange);
}

int main()
{
    ifstream infile("test.txt");
    Data tmp;
    vector<Data*> P_data;

        while (infile){
        Data *tmp = new Data();
        infile >> tmp->date;
        infile >> tmp->currency;
        infile >> tmp->exchange;
        infile >> tmp->low;
        infile >> tmp->high;
        infile >> tmp->daily_cap;
        P_data.push_back(tmp);
    }

    sort(P_data.begin(), P_data.end(), comp1);

//  bool yes = binary_search(P_data.begin()+1, P_data.end(), 20140212, comp2);

    int c = 0;
    for (int i = 0; i<= 20; ++i){
        cout << P_data[i]->date << " " << P_data[i]->exchange << " " << c << endl;
        c++;
    }

}

第一个问题是为什么排序后,

第一行是

-842150451  0

第二行开始排序

20130101 Wii 0 ....

第二个问题是binary_search

我的代码有什么问题吗?

错误信息显示

bool(const Data*, const Data*) 无法将 arg1 'const int' 转换为 'const Data*'

【问题讨论】:

    标签: c++ sorting binary-search


    【解决方案1】:
      1234563和一个空字符串exchange
    1. 您收到的错误是当给 binary_search(http://www.cplusplus.com/reference/algorithm/binary_search/) 一个值 20140212 而不是包含该日期的 Data 对象时(我猜你想找到这个日期的对象。

    您应该将搜索代码修改为:

    // Create a temp variable which target date
    Data tmp;
    tmp.date = 20140212;
    
    // Search for it
    bool yes = binary_search(P_data.begin()+1, P_data.end(), &tmp, comp2);
    

    此外,您可能需要考虑将 date 属性更改为 unsigned 以避免奇怪的负值。

    【讨论】:

      【解决方案2】:

      能否请您发布所有代码? 目前你的结构体指针没有分配内存,如果没有你的所有代码,我们无法得到与你相同的结果。

      错误信息显示

      bool(const Data*, const Data*) 无法将 arg1 'const int' 转换为 'const Data*'

      应该会出现,因为您可以将“const int”而不是“const Data *”传递给您的函数。

      【讨论】:

      • 我觉得这个更适合评论区。
      • 我同意你的观点,尽管我实际上并没有赢得足够的声誉来发表评论。但是我想帮助他,今天下午我会删除这个答案,以确保他阅读了它。 @t.m
      猜你喜欢
      • 1970-01-01
      • 2019-11-19
      • 2023-03-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-09
      相关资源
      最近更新 更多