转载:vector容器中存放结构体变量 作者:v_xchen_v
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中,结构体变量放在了内存栈中,
还有另外一种方式是将结构体变量的指针放在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;
-
}
结果同上
参考:http://noi.openjudge.cn/ch0110/01/