How to Sort a Vector of Custom Objects in C++?
Last Updated :
01 Mar, 2024
In C++, vectors are dynamic arrays and sorting a vector of custom objects means arranging the objects in a certain order. In this article, we will learn how to sort a vector of custom objects in C++.
Sorting a Vector of Custom Objects in C++
To sort a vector of custom objects in C++, we can use the std::sort()
function that sorts the elements in the range [first, last)
into the order specified by the comparator function that compares these custom objects. If you do not want to use the custom comparator, then you may need to overload the comparison operators for the custom objects.
Syntax of std::sort()
sort(first_iterator, last_iterator, comparison_function);
Here,
first_iterator
is the iterator to the beginning of the range to be sorted.
last_iterator
is the iterator to the end of the range to be sorted.
comparison_function
is a binary function that accepts two elements in the range as arguments, and returns a bool value.
C++ Program to Sort a Vector of Custom Objects
The below example demonstrates how we can sort the vector of custom objects in C++.
C++
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
class MyClass {
public :
int data;
MyClass( int a)
: data(a)
{
}
bool operator<( const MyClass& obj) const
{
return data < obj.data;
}
};
int main()
{
vector<MyClass> vec;
vec.push_back(MyClass(30));
vec.push_back(MyClass(10));
vec.push_back(MyClass(20));
vec.push_back(MyClass(40));
sort(vec.begin(), vec.end());
cout << "Sorted vector: " ;
for ( auto & obj : vec)
cout << obj.data << " " ;
cout << endl;
return 0;
}
|
Output
Sorted vector: 10 20 30 40
Time Complexity: O(N*logN), where N is the size of the vector.
Auxiliary Space: O(logN)
Share your thoughts in the comments
Please Login to comment...