zl程序教程

您现在的位置是:首页 >  后端

当前栏目

c++ vector C++ vector存放结构体 并且排序

C++排序 结构 vector 并且 存放
2023-09-14 09:09:31 时间

link


#include<stdio.h>
#include<algorithm>
#include<vector>
#include<iostream>
using namespace std;

typedef struct Point{
    int x;
    int y;
}point;

bool cmp(point p1, point p2){
    return p1.x < p2.x;
}
int main(){
    vector<point> p;
    point pp1, pp2;
    pp1.x = 100;
    pp1.y = 2;
    pp2.x = 30;
    pp2.y = 4;
    p.push_back(pp1);
    p.push_back(pp2);

    sort(p.begin(), p.end(), cmp);

    //vector<point>::iterator it = p.begin();
    //cout << (*it).x << ' ' << (*it).y << ' ' << endl;

    for(vector<point>::iterator it = p.begin(); it!=p.end(); it++)
    {
        //cout<<"迭代遍历:"<<(*it).x<<endl;
        cout <<"迭代遍历:"<< (*it).x << ' ' << (*it).y << ' ' << endl;
    }

    return 0;
}
迭代遍历:30 4 
迭代遍历:100 2