结构元素的排序向量 [英] sort vector of struct element

查看:120
本文介绍了结构元素的排序向量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想排序结构的元素的向量,但我不能构造向量本身这里是代码

  #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 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_t st [10];







return 0;当我声明向量< student_t> st 时,



我无法访问struct的元素,请给我提示如何做

解决方案

  std :: vector< student_t> st; 
for(unsigned i = 0; i <10; ++ i)st.push_back(student_t());
std :: sort(st.begin(),st.end(),& compare);

您也可以使用此向量第1-2行:

  std :: vector< student_t> st(10 / *,student_t()* /); 



编辑



如果你想用键盘输入10个学生,你可以写一个构造学生的函数:

  struct student_t& ; enter_student()
{
student_t s;
std :: cout<< 输入名称<< std :: endl;
std :: cin>> s.name;
std :: cout<< 输入年龄< std :: endl;
std :: cin>>智者;
std :: cout<< Enter score<< std :: endl;
std :: cin>>分数
return s;
}
std :: vector< student_t> st;
for(unsigned i = 0; i <10; ++ i)st.push_back(enter_student());


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_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());

这篇关于结构元素的排序向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆