无法实现从文件按字符串 C++ 中的字母顺序排序的函数

coudn't implement function to sort alphabetically in string c++ from file

本文关键字:顺序 函数 排序 C++ 实现 文件 字符串      更新时间:2023-10-16

我试图在我的项目中实现一个函数,该函数从txt文件中读取并按字母顺序显示它们。我只想按字母顺序排序 numeStudent 和显示时,显示整行数字学生预编号学生等。这是我阅读和显示的功能,我想在显示之前添加排序:

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();
}

这也是我的整个项目:Dropbox Download.我试图在我的项目中实现这个功能(如下),但我没有成功。

#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;
}

我尝试的代码太混乱了,如果我放在这里什么都不懂。如果有人能帮我按字母顺序排序,我会非常感谢你。

假设您要对Student的容器进行排序。

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

将 comp 定义为

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

现在你可以做

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

其中,print函数打印要打印的所有详细信息。

但是,如果您只想对string容器进行排序,您可以简单地

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

另一种方法是为班级学生重载<运算符,但我建议这样做,因为如果您除了排序之外有任何内容,您现在可以将<用于其他目的。

阅读 : http://www.cplusplus.com/reference/algorithm/sort/