对结构体数组执行排序与二分查找,附相关代码片段
Looks like you're working on sorting an array of Data structs with multi-level criteria and setting up for binary search! Let's clean up your code and walk through how to make it work properly.
Data Struct Array First, here's your struct definition formatted clearly:
#include <string> using namespace std; // Assuming this is included for the string type typedef struct Data{ int date; string currency; string exchange; float low; float high; long long int daily_cap; } Data;
Next, let's fix and present your comparator functions. I noticed comp1 was cut off—here's the complete version that implements your intended multi-key sorting logic:
// Comparator for sorting by date only bool comp2(const Data* data1, const Data* data2){ return data1->date < data2->date; } // Multi-key comparator: sort by date first, then currency, then exchange bool comp1(const Data* data1, const Data* data2){ if (data1->date != data2->date) return data1->date < data2->date; if (data1->currency != data2->currency) return data1->currency < data2->currency; // Complete the final sorting condition for exchange return data1->exchange < data2->exchange; }
Using the Comparators for Sorting
Since you're using C++ (evidenced by the string type), you can leverage the standard sort function from the <algorithm> library. Here's how to apply it to a vector of Data pointers:
#include <algorithm> #include <vector> int main() { vector<Data*> dataCollection; // Populate dataCollection with your Data objects... // Sort using the multi-key comparator (date → currency → exchange) sort(dataCollection.begin(), dataCollection.end(), comp1); // Or sort by date only if that's your priority sort(dataCollection.begin(), dataCollection.end(), comp2); return 0; }
Setting Up Binary Search
For binary search to work correctly, your array must be sorted with the same logic you use for the search. Here's an example of searching for a Data object by date in a date-sorted array:
// Search for a Data* with a specific target date Data* findByDate(vector<Data*>& sortedArray, int targetDate) { auto it = lower_bound(sortedArray.begin(), sortedArray.end(), targetDate, [](const Data* data, int date) { return data->date < date; }); if (it != sortedArray.end() && (*it)->date == targetDate) { return *it; } return nullptr; // Return null if no match is found }
If you need to search using the full multi-key criteria (date + currency + exchange), create a dummy Data struct with your target values and use comp1 to compare against elements in the sorted array.
Just a critical reminder: Always ensure your array is sorted with the exact comparator logic you use for binary search—mismatched logic will break the search functionality!
内容的提问来源于stack exchange,提问作者Sam

