Open In App

How to Sort a Vector of Custom Objects in C++?

Last Updated : 01 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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++




// C++ program to illustrate how to sort a vector of custom
// objects
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
  
// creating a custom class
class MyClass {
public:
    int data;
  
    MyClass(int a)
        : data(a)
    {
    }
  
    // Overloading < operator
    bool operator<(const MyClass& obj) const
    {
        return data < obj.data;
    }
};
  
int main()
{
    // Vector of custom objects
    vector<MyClass> vec;
    vec.push_back(MyClass(30));
    vec.push_back(MyClass(10));
    vec.push_back(MyClass(20));
    vec.push_back(MyClass(40));
  
    // Sorting the vector of custom objects
    sort(vec.begin(), vec.end());
  
    // Printing  the vector
    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)



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads