这个问题在这里已有答案:
我正在尝试按字母顺序对数组进行排序(使用一些并行数组),但我不知道该怎么做,也无法按字母顺序排序数组 . 我知道一些关于排序的基础知识,但我不知道如何按字母顺序对字符串数组进行排序 .
编辑:我正在使用四个并行数组:名字,姓氏,ID和等级 . 我正在尝试按姓氏排序,这是一个字符串 . 我知道如何交换所有信息,只需要知道如何按字母顺序进行比较 .
试试这个 . .
#include<bits/stdc++.h> using namespace std ; struct Student { string firstName; string lastName; float grade ; string id ; }; bool byLastName(Student b ,Student a) { if( strcmp(a.lastName.c_str() , b.lastName.c_str()) == 1 ) return true ; return false ; } int main() { Student them [] = { {"Sudipto" , "Roy" , 3.5 , "A-51"}, {"Potter" , "Zam" , 4.5 , "X-420"}, }; int themCount = sizeof (them) / sizeof (Student) ; sort(them , them + themCount , byLastName); for ( auto a : them ) cout << a.lastName <<endl ; return 0; }
1 回答
试试这个 . .