Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
203 views
in Technique[技术] by (71.8m points)

c++ - How to use stable_sort to sort the fruit_name (data from file) and print

I need to create an operator< to use the stable_sort. I want to use the stable_sort to sort for fruit_name from a struct Here is my operator< (inside a struct):

struct fruit_t {
        char fruit_name[MAX_LENGTH];                                            // name of fruit
        float quantity;                                                 // in lbs
        float price;                                                    // price tag of the fruit
        friend bool operator< (const fruit_t& f1, const fruit_t& f2){           //overload operator <
                return (strcmp (f1.fruit_name, f2.fruit_name) < 0);
        }
};

I read in the fruit_name by

while(true){
inFile >> fruit[i].fruit_name
if(inFile.eof()) break;
i++
}
question from:https://stackoverflow.com/questions/65889669/how-to-use-stable-sort-to-sort-the-fruit-name-data-from-file-and-print

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

When you have overloaded operator< you can just use std::stable_sort(begin(fruit), end(fruit));

Instead of overload the operator before (so if you only want to use this kind of comparison once, you can use a lambda expression like this:

std::stable_sort(begin(fruit), end(fruit), [](auto const& a, auto const& b){
  return strcmp (a.fruit_name, b.fruit_name) < 0;
});

The syntax in the reference (all these iterators) might be confusing you. For now, just use begin and end and when you get more familiar with the language, you should try to understand iterators.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...