i am trying to sort vector of struct's elements,but i can't construct vector itself here is code
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
struct student_t{
string name;
int age,score;
} ;
bool compare(student_t const &lhs,student_t const &rhs){
if (lhs.name<rhs.name)
return true;
else if (rhs.name<lhs.name)
return false;
else
if (lhs.age<rhs.age)
return true;
else if (rhs.age<lhs.age)
return false;
return lhs.score<rhs.score;
}
int main(){
struct student开发者_如何学Go_t st[10];
return 0;
}
when i declared vector<student_t>st
i can't access element of struct,please give me hint how to do it
std::vector<student_t> st;
for(unsigned i = 0; i < 10; ++i) st.push_back(student_t());
std::sort(st.begin(), st.end(), &compare);
You could also use this vector
constructor instead of lines 1-2:
std::vector<student_t> st (10 /*, student_t() */);
Edit:
If you want to enter 10 students with the keyboard you can write a function that constructs a student:
struct student_t &enter_student()
{
student_t s;
std::cout << "Enter name" << std::endl;
std::cin >> s.name;
std::cout << "Enter age" << std::endl;
std::cin >> s.age;
std::cout << "Enter score" << std::endl;
std::cin >> s.score;
return s;
}
std::vector<student_t> st;
for(unsigned i = 0; i < 10; ++i) st.push_back(enter_student());
to sort the vector:
sort(st.begin(), st.end(), compare);
and to read input to your vector you should first resize the vector or input to a temporary variable and push it to your vector:
www.cplusplus.com/reference/stl/vector/vector/
精彩评论