Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
How to sort in descending order?
3.
Example
3.1.
C++
4.
How to sort in a particular order?
4.1.
C++
5.
How to sort the array in descending order based on some parameter using a comparator function?
5.1.
C++
6.
Frequently Asked Questions
6.1.
Can I sort using multiple criteria in C++?
6.2.
Is it possible to use the std::sort function for arrays?
6.3.
How does the sorting efficiency of std::sort compare to other sorting methods?
7.
Conclusion 
Last Updated: Jun 11, 2024
Easy

Sort a Vector in CPP

Author Gaurav Gandhi
0 upvote

Introduction

Sorting is a fundamental concept in programming that involves arranging elements of a list or an array in a specific order. In C++, sorting is commonly performed on vectors, which are dynamic arrays that can resize themselves automatically. Sorting a vector allows you to organize its elements in ascending or descending order based on certain criteria. 

Sort a Vector in C++

In this article, we will learn how to sort a vector in C++ using different techniques with proper codes to understand the concept better.

How to sort in descending order?

When sorting a vector in C++, the default behavior is to sort the elements in ascending order. However, there may be cases where you need to sort the elements in descending order instead. To achieve this, you can use the std::sort function from the C++ Standard Library & pass a custom comparison function as an argument.

Example

  • C++

C++

#include <iostream>
#include <vector>
#include <algorithm>

bool compare(int a, int b) {
return a > b;
}

int main() {
std::vector<int> numbers = {5, 2, 8, 12, 1};

std::sort(numbers.begin(), numbers.end(), compare);

for (int num : numbers) {
std::cout << num << " ";
}
std::cout << std::endl;

return 0;
}
You can also try this code with Online C++ Compiler
Run Code

Output

12 8 5 2 1 


In this code, we define a custom comparison function called compare that takes two elements a & b as parameters. The function returns true if a is greater than b, indicating that a should come before b in the sorted order.

We then call the std::sort function, passing the begin() & end() iterators of the vector to specify the range of elements to be sorted. Additionally, we pass the compare function as the third argument to tell std::sort to use our custom comparison function for sorting.

How to sort in a particular order?

In some scenarios, you may want to sort a vector based on a specific order that is not necessarily ascending or descending. C++ provides the std::sort function along with custom comparison functions to handle such cases.

Let's say we have a vector of strings representing colors, and we want to sort them in the order of "red", "green", "blue", and then any other colors. Here's how we can achieve that:

  • C++

C++

#include <iostream>

#include <vector>

#include <algorithm>

#include <string>

bool compare(const std::string& a, const std::string& b) {

   std::vector<std::string> order = {"red", "green", "blue"};

   auto it_a = std::find(order.begin(), order.end(), a);

   auto it_b = std::find(order.begin(), order.end(), b);

   if (it_a != order.end() && it_b != order.end()) {

       return std::distance(order.begin(), it_a) < std::distance(order.begin(), it_b);

   } else if (it_a != order.end()) {

       return true;

   } else if (it_b != order.end()) {

       return false;

   } else {

       return a < b;

   }

}

int main() {

   std::vector<std::string> colors = {"yellow", "red", "orange", "blue", "green"};

   std::sort(colors.begin(), colors.end(), compare);

   for (const std::string& color : colors) {

       std::cout << color << " ";

   }

   std::cout << std::endl;

   return 0;

}
You can also try this code with Online C++ Compiler
Run Code

Output

red green blue orange yellow 


In this code, we define a custom comparison function compare that takes two strings a & b as parameters. We create a separate vector order that holds the desired order of colors.

Inside the compare function, we use std::find to locate the positions of a & b in the order vector. If both colors are found in the order vector, we compare their positions using std::distance to determine which color should come first. If only one color is found in the order vector, we give it priority. If neither color is found in the order vector, we compare them lexicographically using the < operator.

After sorting with the custom comparison function, the vector colors will be sorted in the specified order: {"red", "green", "blue", "orange", "yellow"}.

How to sort the array in descending order based on some parameter using a comparator function?

When sorting a vector of objects or structures, you may want to sort them based on a specific parameter or member variable. To achieve this, you can define a custom comparator function that compares the desired parameter and use it with the std::sort function.

Let's consider an example where we have a vector of Person objects, and we want to sort them in descending order based on their age. Here's how we can do it:

  • C++

C++

#include <iostream>

#include <vector>

#include <algorithm>

struct Person {

   std::string name;

   int age;

};

bool compareAge(const Person& a, const Person& b) {

   return a.age > b.age;

}

int main() {

   std::vector<Person> people = {

       {"Gunjan", 24},

       {"Akash", 28},

       {"Rahul", 20},

       {"Guarav", 30}

   };

   std::sort(people.begin(), people.end(), compareAge);

   for (const Person& person : people) {

       std::cout << person.name << " - " << person.age << std::endl;

   }

   return 0;

}
You can also try this code with Online C++ Compiler
Run Code


In this code, we define a Person struct that has two member variables: name (string) and age (int).

We then define a custom comparator function called compareAge that takes two Person objects a and b as parameters. The function compares the age member variable of the objects and returns true if a.age is greater than b.age, indicating that a should come before b in the sorted order.

In the main function, we create a vector of Person objects called people. We use the std::sort function to sort the vector, passing the begin() and end() iterators along with the compareAge function as the comparator.

After sorting, the vector people will be sorted in descending order based on the age parameter:

Output

Gaurav - 30
Akash - 28
Gunjan - 24
Rahul - 20


Note : This approach allows you to sort a vector of objects based on any specific parameter by defining an appropriate comparator function that compares the desired member variable.

Frequently Asked Questions

Can I sort using multiple criteria in C++?

Yes, you can sort using multiple criteria by chaining conditions within your comparator function. This allows you to prioritize one criterion over another, such as sorting by grade and then by name if grades are the same.

Is it possible to use the std::sort function for arrays?

Absolutely! The std::sort function can sort both vectors and plain arrays. Just ensure you provide the correct beginning and ending pointers or iterators.

How does the sorting efficiency of std::sort compare to other sorting methods?

std::sort is highly efficient, generally implementing a hybrid of quicksort, heapsort, and insertion sort, known as introsort. Its complexity is O(n log n) in the average and worst case, making it suitable for most practical applications.

Conclusion 

In this article, we discussed various techniques for sorting vectors in C++. We learned how to sort vectors in descending order, custom order, and based on specific parameters using comparator functions. By leveraging the power of the std::sort function and custom comparison mechanisms, we can efficiently sort vectors to meet our specific requirements.  These sorting techniques are crucial for effective data manipulation and improved program performance in C++.

You can refer to our guided paths on the Coding Ninjas. You can check our course to learn more about DSADBMSCompetitive ProgrammingPythonJavaJavaScript, etc. Also, check out some of the Guided Paths on topics such as Data Structure andAlgorithmsCompetitive ProgrammingOperating SystemsComputer Networks, DBMSSystem Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry.

Live masterclass