vector容器中存放结构体变量有两种方式:
1)存放结构体变量本身
2)存放结构体变量的指针
先介绍第一种方式,存放结构体变量到vector容器中,示例如下:
结构体
struct stu
{
int num;
float grade;
};
std::vector v;
stu student;
int num;
float grade;
std::cin>>num>>grade;
student.num = num;
student.grade = grade;
v.push_back(student);
for(std::vector::iterator it=v.begin();it!=v.end();it++)
{
std::cout<<(*it).num<<" "<<(*it).grade<
bool compare(const stu& st1,const stu& st2)
{
return st1.grade>st2.grade;
}
sort(v.begin(),v.end(),compare);
完整代码:
#include
#include
#include
struct stu
{
int num;
float grade;
};
bool compare(const stu& st1,const stu& st2)
{
return st1.grade>st2.grade;
}
int main()
{
int n,k;
std::cin>>n>>k;
std::vector v;
for(int i=0;i>num>>grade;
student.num = num;
student.grade = grade;
v.push_back(student);
}
sort(v.begin(),v.end(),compare);
for(std::vector::iterator it=v.begin();it!=v.end();it++)
{
std::cout<<(*it).num<<" "<<(*it).grade<
以上方法是将这个结构体变量的副本放在vector中,结构体变量放在了内存栈中,
还有另外一种方式是将结构体变量的指针放在vector中,结构体变量放在内存堆中,
参考:http://blog.csdn.net/feliciafay/article/details/9128385
定义一个结构体变量指针的vector容器
std::vector v;
stu *student = new stu();
int num;
float grade;
std::cin>>num>>grade;
student->num = num;
student->grade = grade;
v.push_back(student);
for(std::vector::iterator it=v.begin();it!=v.end();it++)
{
std::cout<<(*it)->num<<" "<<(*it)->grade<
sort自定义排序
bool compare(const stu* st1,const stu* st2)
{
return st1->grade>st2->grade;
}
sort(v.begin(),v.end(),compare);
#include
#include
#include
struct stu
{
int num;
float grade;
};
bool compare(const stu* st1,const stu* st2)
{
return st1->grade>st2->grade;
}
int main()
{
int n,k;
std::cin>>n>>k;
std::vector v;
for(int i=0;i>num>>grade;
student->num = num;
student->grade = grade;
v.push_back(student);
}
sort(v.begin(),v.end(),compare);
for(std::vector::iterator it=v.begin();it!=v.end();it++)
{
std::cout<<(*it)->num<<" "<<(*it)->grade<
参考:http://noi.openjudge.cn/ch0110/01/