添加链接
link之家
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接

Report this

What is the reason for this report?

Sorting a Vector in C++

Published on August 4, 2022
Sneh

By Sneh

Sorting a Vector in C++

Introduction

vectors , in particular, we can perform sorting operations in any order(ascending or descending).

Sorting a Vector in C++ in Ascending order

vector in C++ can be easily sorted in ascending order using the sort() function defined in the algorithm header file.

The sort() function sorts a given data structure and does not return anything. The sorting takes place between the two passed iterators or positions. The third parameter determines the order in which the elements are going to be compared.

By default, for not passing the third parameter, the function considers it to be the std::less<int>() function. This function returns true or false on the basis of comparing two arguments, whether the first one is less than the other.

So, now let us see how we can sort a vector in C++(ascending order).

#include<iostream>    
#include<vector> 
#include<algorithm>
using namespace std;
int main()
	//vector initialisation
	vector<int> vec {5, 4, 3, 2, 1};
	cout<<"Before sorting vector : ";
	for(auto i=vec.begin(); i<vec.end(); i++)
		cout<<" "<<*i;
	std::sort(vec.begin(),vec.end());//Sorting the vector
	cout<<"\n\nAfter sorting vector : ";
	for(auto i=vec.begin(); i<vec.end(); i++)
		cout<<" "<<*i;
	return 0;

Output:

Before sorting vector :  5 4 3 2 1
After sorting vector :  1 2 3 4 5

Sorting a Vector in C++ in Descending Order

1. Using greater<int>() in sort()

2. Using Lambda Expression in sort()

Conclusion

References

  • Sorting in STL - JournalDev Tutorial,
  • <algorithm> - C++ algorithm Library,
  •