Mam wektor typu zdefiniowanego przez użytkownika (Student). Mam 2 funkcje, które są prawie identyczne, z wyjątkiem pojedynczego wywołania funkcji wewnątrz nich.Przekazywanie algorytmu STL do innej funkcji
Oto funkcje 2:
Student lowest_grade(const std::vector<Student> &all_students){
return *std::min_element(std::begin(all_students), std::end(all_students),
[](const Student &a, const Student &b){
return a.get_average() < b.get_average();});
}
Student highest_grade(const std::vector<Student> &all_students){
return *std::max_element(std::begin(all_students), std::end(all_students),
[](const Student &a, const Student &b){
return a.get_average() < b.get_average();});
}
Obie te funkcje działają poprawnie dla mojego użytku, ale wydaje się, że to może być łatwo skonstruowany lepiej. Chcę utworzyć funkcję, którą może przejść w obu min_element lub max_element, coś jak:
template <typename func>
Student dispatch(const std::vector<Student> &all_students, func){
return *func(std::begin(all_students), std::end(all_students),
[](const Student &a, const Student &b){
return a.get_average() < b.get_average();});
}
Ale nie uda się uzyskać to, aby działać poprawnie. Nie jestem pewien, jak to zrobić.
EDIT - To jak mam wywołanie funkcji wysyłki + komunikat o błędzie:
std::cout<<"lowest: "<< dispatch(all_students, std::max_element);
komunikat o błędzie jest:
g++ m.cpp -std=c++11 -Wall -o main
m.cpp: In function ‘int main()’:
m.cpp:86:63: error: missing template arguments before ‘(’ token
std::cout<<"lowest: "<< dispatch(all_students, std::function(std::max_element));
^
[email protected]:~/Desktop/Prog/daily/167m$ make
g++ m.cpp -std=c++11 -Wall -o main
m.cpp: In function ‘int main()’:
m.cpp:86:81: error: no matching function for call to ‘dispatch(std::vector<Student>&, <unresolved overloaded function type>)’
std::cout<<"lowest: "<< dispatch<std::function>(all_students, std::max_element);
^
m.cpp:86:81: note: candidate is:
m.cpp:71:9: note: template<class func> Student dispatch(const std::vector<Student>&, func)
Student dispatch(const std::vector<Student> &all_students, func){
^
m.cpp:71:9: note: template argument deduction/substitution failed:
Czy możecie wyjaśnić, jak to nie działa? Szczególnie proszę pokazać, w jaki sposób korzystasz z funkcji "wysyłki". –
Jeśli obliczasz jednocześnie min i max, weź pod uwagę [std :: minmax_element] (http://en.cppreference.com/w/cpp/algorithm/minmax_element). –