无法实现从文件按字符串 C++ 中的字母顺序排序的函数
coudn't implement function to sort alphabetically in string c++ from file
我试图在我的项目中实现一个函数,该函数从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/
相关文章:
- 函数调用中参数的顺序重要吗
- 优先顺序:智能指针和类析构函数
- C++成员的析构函数顺序与shared_ptr
- C++:使用方法调用析构函数的顺序是什么?
- 以 f() + g() 调用顺序的 C++ 函数
- 为什么用户定义的函数不按照给定的顺序对相同长度的元素进行排序?
- 有没有办法保证析构函数的相对顺序?
- 函数模板实例化、替换和重载解析的顺序是什么?
- 类内初始化与构造函数初始化列表的顺序
- 递归函数的执行顺序
- 运算符 new 的执行顺序和构造函数的参数
- 如果在 C++ 构造函数中以错误的顺序初始化对象数据,会发生什么类型的错误
- std::bind() 参数列表中函子的执行顺序(可能与函数参数的求值顺序无关)
- 构造函数中没有参数的对象类成员按什么顺序初始化?
- std::unique_ptr析构函数顺序
- C++17的可选和可变顺序函数参数
- OpenMP 不在 for 循环中的顺序函数的并行化
- 递归C++字母顺序函数重复返回相同的值
- C++-销毁顺序-函数的静态成员在主类析构函数之前被销毁
- 构造函数执行顺序/顺序:函数中静态变量(类实例)的依赖初始化