Suppose I have a 2-D array like this -
32 34
99 19
12 45
23 27
I want to sort it on the basis of the second column in reverse order so that it becomes -
12 45
32 34
23 27
99 19
Other than using pair you can also use a struct , it not only makes the code more readable but also you need to type less , such as you need to sort a array of points in a 2D plane , x and y sounds better than first and second,
struct point{
int x;
int y;
};
bool compare(const point &p1,const point &p2){
return p1.x < p2.x;
/*Sorts the array based on the x in increasing order , change it to y for comparing the second element and for decreasing order you can change the less than operator to greater than*/
}
//Now you use sort vectors like these
int main(){
std::vector<point>array(size);
sort(array.begin(),array.end(),compare);
}
Learning to use structs efficiently can save a lot of headaches.
P.S - Best of luck INOI , I am also practicing for it ,
Why use a vector? Earlier I was accustomed to using vectors all the time but I realised the problem with that while solving a program on the IARCS judge, which got a TLE. I learnt about arrays; but since std::array can’t be used in INOI I guess, since they’re not giving C++11 support. Therefore now I’m learning to use C style arrays efficiently. Most cases though that didn’t make that big a difference; but sometimes it does, and that’s hard to spot it.
This answer is similar mostly to @neilit1992 's answer except that it uses a pair<int,int>[] instead of a vector, and therefore requires a known size.
Use an array of pairs and not vector. Replace the begin iterator with your array variable and the end iterator with the last index you want sorted, the last parameter is your comparison function.
Example: std::sort(a, a+x, cmp); where a is your array x is the last index and cmp is your greater than function.
If you are talking about sorting array using sort ; Yes you can sort an array by using sort(a,a+n) where n is the size of an array or the first n elements that you want to sort. assuming ‘a’ is an array
I suggest http://www.cplusplus.com/ , if you have enough grip in the syntax it is the best website to learn from , the documentation it has about each and every STL element and that too with nice examples is awesome , for videos i would suggest C++ Standard Library - YouTube , it introduces to all STL elements and their functions.