0

so I have a structure which contains the following,

stuct details {
int emp_id;
int age;
char name[50];
};

so the data for this structure is already present in a binary file and I've read the file, now how do I proceed to sort it just by name? can std::sort be used?How would I write the function for it?

  • `std::sort` works very well for your job with comparision function `sort( RandomIt first, RandomIt last, Compare comp );`. – pvc Nov 11 '20 at 02:26
  • what would RandomIt first , and RandomIt last contain? –  Nov 11 '20 at 02:30
  • They contain what the documentation for `std::sort` says they contain. Have you read the freely available documentation for `std::sort` already, and if not why not? If you did and you don't understand something in the documentation, what exactly is unclear to you? – Sam Varshavchik Nov 11 '20 at 02:48
  • I did read them. I know it's sort(startaddress, endaddress, comparator) but since my input is a name say "abc def" how will the start and end work? if it's just an array of int i get the format is n = sizeof(arr)/sizeof(arr[0]); but what about the occurrence of space? –  Nov 11 '20 at 02:56
  • @Ashwar see the answer I just posted. – Remy Lebeau Nov 11 '20 at 03:11

2 Answers2

1

If I understand your question correctly, you'll have to overload the comparison operator(s) (<,>) and then add code to compare character arrays. I would suggest using std::string from stdlib rather than building your own comparison function, unless you need the name member to be a char array. This should get you started:

struct details {
    int emp_id;
    int age;
    char name[50];
    bool operator<(const details a) {
        //You'll have to find the code to compare character arrays. But that will be a quick google search.
    }
};

This will allow the sort function of whatever container you decide to use to place them in the right order.

sog
  • 493
  • 4
  • 13
0

You don’t sort a single instance of your struct. You sort a container of structs. Whether that be an array, a vector, etc, that is up to you to decide.

You would read the file, populating the container with instances of your struct as needed, and then you would pass begin/end iterators for the range of container elements that you want to sort, providing a comparator that compares the fields of 2 given instances of the struct as needed.

For example:

struct details {
    int emp_id;
    int age;
    char name[50]; // why not std::string?
};

std::vector<details> employees;
// populate employees as needed...

std::sort(employees.begin(), employees.end(),
    [](const details &emp1, const details &emp2){
        return std::strncmp(emp1.name, emp2.name, 50) < 0;
    }
);
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770