Horje
How to Sort an Array of Strings Using Pointers in C++?

In C++, sorting an array of strings using pointers is quite different from normal sorting because here the manipulation of pointers is done directly, and then according to which string is pointed by the pointer the sorting is done.

The task is to sort a given array of strings using pointers.

Example

Input: strArray[] = {"Apple", "Orange", "Banana", "Grapes", "Cherry"};

Output: strArray[] = {"Apple", "Banana", "Cherry", "Grapes", "Orange"};

Sort Array of Strings in C++

To sort an array of strings using pointers we can use the std::sort() standard template library function that takes three parameters: a pointer to the beginning of the array range, a pointer to the end of the array range, and an optional comparison function parameter to sort the strings based on specific criteria.

C++ Program to Sort Array of Strings Using Pointers

C++

// C++ program to sort array of strings using pointers
  
#include <algorithm>
#include <cstring>
#include <iostream>
using namespace std;
  
// Comparison function for sort
bool compareStrings(const char* a, const char* b)
{
    return strcmp(a, b) < 0;
}
  
int main()
{
    const int size = 5;
    const char* strArray[size]
        = { "Apple", "Orange", "Banana", "Grapes",
            "Cherry" };
  
    // Sorting the array using sort and function
    // pointer
    sort(strArray, strArray + size, compareStrings);
  
    // Displaying the sorted array
    for (int i = 0; i < size; i++) {
        cout << strArray[i] << " ";
    }
  
    return 0;
}

Output

Apple Banana Cherry Grapes Orange 

Explanation: In the above example we created a compareStrings() function which uses the strcmp() function to compare the strings based on their lexicographical order and sort() function sorts the strings based on that order only.

We can also use vector of string instead of static array of strings to sort it by using sort() function.




Reffered: https://www.geeksforgeeks.org


C++

Related
How to Resize an Array of Strings in C++? How to Resize an Array of Strings in C++?
How to Remove Last Character From C++ String? How to Remove Last Character From C++ String?
How to Take Multiple Line String Input in C++? How to Take Multiple Line String Input in C++?
Group Vector of Pair Elements in Multimap Group Vector of Pair Elements in Multimap
Difference Between Array of Characters and std::string in C++ Difference Between Array of Characters and std::string in C++

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
13