मेरे पास उपयोगकर्ता परिभाषित प्रकार (छात्र) का वेक्टर है। मेरे पास 2 फ़ंक्शन हैं जो लगभग एक ही फ़ंक्शन कॉल को छोड़कर लगभग समान हैं।किसी अन्य फ़ंक्शन पर एसटीएल एल्गोरिदम पास करना
यहाँ 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();});
}
इन कार्यों के
दोनों अपने प्रयोग के लिए सही ढंग से काम कर रहे हैं लेकिन ऐसा लगता है जैसे यह आसानी से बेहतर निर्माण किया जा सकता है। मैं एक समारोह जो मैं या तो min_element या max_element पास कर सकता है, जैसे कुछ बनाना चाहते हैं:
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();});
}
लेकिन मैं इसे पाने के लिए ठीक से काम करने का प्रबंधन नहीं कर सकते हैं। मुझे यकीन नहीं है कि यह करने के बारे में कैसे जाना है।
संपादित करें - यह है कि कैसे मैं प्रेषण समारोह + त्रुटि संदेश बोल रहा हूँ:
std::cout<<"lowest: "<< dispatch(all_students, std::max_element);
त्रुटि संदेश है:
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:
क्या आप कृपया यह बता सकते हैं कि यह कैसे काम नहीं कर रहा है? विशेष रूप से कृपया दिखाएं कि आप अपने 'प्रेषण' फ़ंक्शन का उपयोग कैसे करते हैं। –
यदि आप एक ही समय में न्यूनतम और अधिकतम दोनों की गणना कर रहे हैं, तो [std :: minmax_element] (http://en.cppreference.com/w/cpp/algorithm/minmax_element) खाते में लें। –