c++ - How can I use vector or algorithm for finding maximum amount in this code? -


i wrote following code finding maximum score:

#include "stdafx.h" #include <iostream> #include<vector> #include <string> #include <algorithm>  constexpr int max_students = 3;  using namespace std; class student{ public:     void vrod();     void dis();     int stno;     int score     int i;     string name; };  void student::vrod(){     cout << "name=";     cin >> name;     cout << "stno=";     cin >> stno;     cout << "score=";     cin >> score; } void student::dis(){     cout << "name=" << name << "\n" << "stno=" << stno << "\n" << "score=" << score<< "\n";     cin.get(); }  int main(){     int l;     vector<student> my_vector;     for(int = 0; < n; i++)     {         student new_student;         cout << "number: ";         cin >> new_student.stno;         cout << "score: ";         cin >> new_student.score;         cout << "name: ";         cin >> new_student.name;          my_vector.push_back(new_student);     }      l=0;     for(int = 0; < max_students; ++i)     {         if (my_vector[i].score>l) {             l=my_vector[i].score;         }     }      cout << "max=" << l;      cin.get();     cin.get(); } 

i used common ways find maximum amount, how can use vector? how algorithm? found there function max in algorithm, needs 2 argument , not use code. tips beforehand.

you can use std::max_element , lambda expression comparator:

auto l = std::max_element(my_vector.cbegin(), my_vector.cend(),     [](const student& s1, const student& s2) {     return s1.score < s2.score;     }); 

l const iterator, output maximum score need check if did return , output score

if(l != my_vector.cend()){     cout << "max=" << l->score; } 

also few tips:

  • don't do

    #define n 3

this c++, , giving meaningful variable names practice can use

 constexpr int max_students = 3; 
  • you aren't using student::vrod() , student:dis() methods anywhere

update (op request):

lambda expressions more convenient way write functions various uses. lambda in case

 [](const student& s1, const student& s2) {     return s1.score < s2.score;     } 

is more convenient way write comparator function, can implemented functor

struct compare_students {     bool operator() (const student& s1, const student& s2) const {         return s1.score < s2.score;     } }; auto l = std::max_element(my_vector.cbegin(), my_vector.cend(), compare_students()); 

for more information please consider searching c++ lambda tutorials , examples.


Comments

Popular posts from this blog

java - Suppress Jboss version details from HTTP error response -

gridview - Yii2 DataPorivider $totalSum for a column -

Sass watch command compiles .scss files before full sftp upload -