C++ vector two-dimensional array is sorted by the second dimension

Problem introduction

I encountered a two-dimensional array sorting problem in Leetcode452, in which the interval range of each balloon is stored with a vector<int>, and finally a vector<vector<int>> is used to store the horizontal intervals of all balloons.
leet insert image description here
Here we want to sort all balloon horizontal intervals by their end positions.

basic knowledge

1. Usage of sort function

	sort(start, end, cmp);  
  • start is the starting position of the array to be sorted, end is the next bit from the end position of the array to be sorted
  • cmp points out the sorting criteria. If cmp is defaulted, the default is ascending order.
    The power of the sort function is that it can be combined with cmp to realize the sorting of multi-dimensional vector arrays by a certain dimension or several dimensions; examples are as follows:
bool cmp(int a, int b){
	return a > b;
	//意味着a大于b时,把a排到b的前面,即降序排序
}
int  a[];
sort(a,a+10,cmp);
//实现了将数组a的前十位降序排序
bool cmp(vector<int> &a,vector<int> &b){
//传入两个vector数组
return a.back() < b.back();
//根据数组元素的最后一位进行降序排序
}

vector<vector<int>> points;
sort(points.begin(),points.end(),cmp);
//对二维数组points,按照第二维进行排序

Points to note are:

  • The elements compared in the cmp function should be the outermost content of the array to be sorted.
  • What is passed in sort is the starting position and ending position of the entire array to be sorted and the sorting criterion cmp

2. Lambda expression

  • The lambda expression defines an anonymous function, which can be implemented in one line. The
    function format is as follows:
[capture](params) opt -> ret {body;};
  • capture implements the capture of a certain range of variables. It can be defaulted when variables are not captured.
  • params is a parameter list, which can be defaulted if there is no parameter list.
  • opt is a function option
  • ret is the return value type, it can be defaulted if it can be guessed
  • body; is the content in the function body and should not be defaulted.
    Generally speaking, lambda expressions are slower than custom function methods! !

solution to the original problem

Although the two forms of sorting arrays are introduced above, their connotation uses the cmp function to stipulate the sorting criteria. It's just that lambda expressions use implicit function definitions.
1. Define the sort function of cmp

bool cmp(vector<int> &a, vector<int> &b){
	return a.back() < b.back();
	//意味着当a的最后一位比b的最后一位小时,将a排序到b前,即实现了升序排序
}
vector<vector<int>>points;
sort(points.begin(),points.end(),cmp);

2. The sort function using lambda expression (in fact, the cmp function is implicitly integrated into sort)

sort(points.begin(),points.end(),[](vector<int>a,vector<int>b){return a.back() < b.back();};

Guess you like

Origin blog.csdn.net/ZHorcrux/article/details/129326728