Google News
logo
C++ Program to Sort Elements in Lexicographical Order (Dictionary Order)
To sort elements in lexicographical order, we can use the sort() function provided by the <algorithm> header in C++. Here's the program:
Program :
#include <iostream>
#include <algorithm>
#include <string>

using namespace std;

int main()
{
    string str[] = {"apple", "banana", "orange", "mango", "grape"};
    int n = sizeof(str)/sizeof(str[0]);

    sort(str, str+n);

    cout << "Elements in lexicographical order:" << endl;
    for (int i = 0; i < n; i++)
    {
        cout << str[i] << endl;
    }

    return 0;
}
Output :
Elements in lexicographical order:
apple
banana
grape
mango
orange
In this program, we have an array str of strings, and we use the sort() function to sort the elements of the array in lexicographical order. The sizeof() operator is used to find the number of elements in the array, and the sizeof(str[0]) expression gives the size of each element in the array. Therefore, n is initialized with the number of elements in the array.

The sort() function sorts the elements of the array in ascending order. The for loop is used to print the elements of the sorted array in lexicographical order.