-1

I tried to implement in my project a function which read from txt file and display them sorted alphabetically. I want to sort alphabetically only numeStudent and when display, to display entire line numeStudent prenumeStudent etc. This is the function where I read and display, I would like to add the sort before displaying:

void Student::ListareStudenti()
{
ifstream fisier;
fisier.open ("studenti.txt");
cout <<setw(14)<< "NUME"<<setw(14)<<"PRENUME"<<setw(10)<<"FACULTATE"<<setw(10)<<"SPECIALIZ"<<setw(10)<<"MATERIE"<<setw(10)<<"LABORATOR"<<setw(10)<<"EXAMEN"<<setw(10)<<"MEDIA"<<endl<<endl;
while(!fisier.eof())
{
fisier>>numeStudent>>prenumeStudent>>facultate>>specializare>>materie>>notaLaborator>>notaExamen>>media;
cout<<setw(14)<<numeStudent<<setw(14)<<prenumeStudent<<setw(10)<<facultate<<setw(10)<<specializare<<setw(10)<<materie<<setw(10)<<notaLaborator<<setw(10)<<notaExamen<<setw(10)<<media<<endl;
}
fisier.close();
}

Also this is my entire project: Dropbox Download . I tried to implement this function(below) to my project but I didn't succes.

#include <iostream>
#include <set>
#include <algorithm>

void print(const std::string& item)
{
    std::cout << item << std::endl;
}

void sort()
{
std::set<std::string> sortedItems;

for(int i = 1; i <= 5; ++i)
{
    std::string name;
    std::cout << i << ". ";
    std::cin >> name;

    sortedItems.insert(name);
    }

    std::for_each(sortedItems.begin(), sortedItems.end(), &print);
}
int main(void)
{
    sort();
    return 0;
}

The code where I tried is too much clutter and not understand anything if i put here. If someone could help me to sort alphabetically I would thank you very much.

Ashoka Lella
  • 6,128
  • 1
  • 26
  • 36

1 Answers1

0

Let's say you want to sort a container of Student .

vector<Student> vec;
// input and store the required values from the file
std::sort(vec.begin(),vec.end(),comp);

where you define comp as

bool comp(Student &a,Student &b)
{
return a.numeStudent < b.numeStudent ;  // assuming they are public members
}

now you can do

std::for_each(vec.begin(), vec.end(), &print);

where the print function prints all the details you want to print.

However if you just want to sort a container of string , you can simply

std::sort(vec_strings.begin(),vec_strings.end());

Another way can be to overload the < operator for the class student , but i recommend doing it this way as you can now use < for other purposes if you have any beside sorting.

Read : http://www.cplusplus.com/reference/algorithm/sort/

Abhishek Gupta
  • 1,221
  • 12
  • 26