转载他人文章,只为自己方便查找使用
vector容器中存放结构体变量有两种方式:
1)存放结构体变量本身
2)存放结构体变量的指针
先介绍第一种方式,存放结构体变量到vector容器中,示例如下:
结构体
struct stu
{
int num;
float grade;
};
定义一个结构体变量的vector容器
std::vector<stu> v;
添加
stu student;
int num;
float grade;
std::cin>>num>>grade;
student.num = num;
student.grade = grade;
v.push_back(student);
遍历
for(std::vector<stu>::iterator it=v.begin();it!=v.end();it++)
{
std::cout<<(*it).num<<" "<<(*it).grade<<std::endl;
}
sort自定义比较函数
bool compare(const stu& st1,const stu& st2)
{
return st1.grade>st2.grade;
}
sort(v.begin(),v.end(),compare);
完整代码:
#include <iostream>
#include <vector>
#include <algorithm>
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<stu> v;
for(int i=0;i<n;i++)
{
stu student;
int num;
float grade;
std::cin>>num>>grade;
student.num = num;
student.grade = grade;
v.push_back(student);
}
sort(v.begin(),v.end(),compare);
for(std::vector<stu>::iterator it=v.begin();it!=v.end();it++)
{
std::cout<<(*it).num<<" "<<(*it).grade<<std::endl;
}
return 0;
}
还有另外一种方式是将结构体变量的指针放在vector中,结构体变量放在内存堆中,
参考:http://blog.csdn.net/feliciafay/article/details/9128385
定义一个结构体变量指针的vector容器
std::vector<stu*> 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<stu*>::iterator it=v.begin();it!=v.end();it++)
{
std::cout<<(*it)->num<<" "<<(*it)->grade<<std::endl;
}
sort自定义排序
bool compare(const stu* st1,const stu* st2)
{
return st1->grade>st2->grade;
}
sort(v.begin(),v.end(),compare);
完整代码:
#include <iostream>
#include <vector>
#include <algorithm>
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<stu*> v;
for(int i=0;i<n;i++)
{
stu *student = new stu();
int num;
float grade;
std::cin>>num>>grade;
student->num = num;
student->grade = grade;
v.push_back(student);
}
sort(v.begin(),v.end(),compare);
for(std::vector<stu*>::iterator it=v.begin();it!=v.end();it++)
{
std::cout<<(*it)->num<<" "<<(*it)->grade<<std::endl;
}
return 0;
}