STL容器中顺序逆序问题

  1. 从前到后遍历和从后到前遍历

使用rbegin()和rend(),反方向输出

vector<int> a = {2,3,4,5,6,7,8,9};
for(auto i = a.rbegin(); i != a.rend(); i++) cout << *i << " ";

  1. 在容器内降序排列
  • vector
bool com(int a, int b)
{
	return a > b;
}

int main()
{
	vector<int> a = {2,3,4,5,6,7,8,9};
	sort(a.begin(), a.end(), com);
    for(auto x : a) cout << x << " ";
    
}

  • set
class Compare
{
	public:
		bool operator()(int a, int b)
		{
			return a > b;
		}
};


int main()
{
	set<int,Compare> a = {5,4,2,7,8,0};
	for(auto x : a ) cout << x << " ";
    
}

  • 结构体set

可以在结构体内定义排序方式

#include<iostream>
#include<set>
#include<vector>
#include<algorithm>

using namespace std;

struct Student
{
	int age;
	string name;
	bool operator <(const Student &stu)const
	{
		return age > stu.age;
	}
};

set<Student> s = {{10,"张三"},{15,"李四"}};


int main()
{
	for(auto x : s) cout << x.age << " ";
	cout << endl;
	return 0;
}


  1. 结构体排序
#include<iostream>
#include<set>
#include<vector>
#include<algorithm>

using namespace std;

struct Student
{
	int age;
	string name;
	bool operator <(const Student &stu)const
	{
		return age > stu.age;
	}
};

Student stu[100];

int main()
{
	stu[1].age = 10;
	stu[1].name = "张三";
	
	stu[2].age = 20;
	stu[2].name = "李四";
	
	bool a = stu[1] < stu[2];
	
	cout << a << endl;
	return 0;
}

posted @ 2020-11-19 23:10  晓尘  阅读(284)  评论(0)    收藏  举报