In this C++ tutorial, you shall learn how to sort a string vector lexicographically (order of strings in a typical language dictionary), with example programs.

Sort string Vector lexicographically in C++

To sort elements in a string vector, based on their order in an English dictionary (if the elements are in English language), use std::sort() function of algorithm library.

std::sort() function of algorithm library by default sorts a string vector lexicographically in ascending order

The syntax of the statement to sort a string vector v in ascending order lexicographically is

sort(v.begin(), v.end());

For example, when the strings "apple" and "fig" are compared, "apple" is smaller with starting character of 'a' than that of "fig" with 'f'. If starting characters are same, then the next characters are used for comparison, and so on.

To sort the string vector lexicographically in descending order, reverse the sorted() vector which is already sorted in ascending order, using vector reverse().

sort(v.begin(), v.end());
reverse(v.begin(), v.end());

C++ Programs

ADVERTISEMENT

1. Sort strings in vector lexicographically in ascending order

In the following program, we take a string vector in v and sort this vector in ascending order based on their order in respective language dictionary.

main.cpp

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int main() {
   //string vector
   vector<string> v { "banana", "apple", "fig", "avocado" };

   //sort string vector lexicographically
   sort(v.begin(), v.end());
   
   //print result vector
   for ( auto& element : v ) {
      cout << element << "  ";
   }
}

Output

apple  avocado  banana  fig

2. Sort strings in vector lexicographically in descending order

In the following program, we sort the string vector v and sort it in descending order lexicographically.

main.cpp

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int main() {
   //string vector
   vector<string> v { "banana", "apple", "fig", "avocado" };

   //sort string vector lexicographically
   sort(v.begin(), v.end());
   reverse(v.begin(), v.end());
   
   //print result vector
   for ( auto& element : v ) {
      cout << element << "  ";
   }
}

Output

fig  banana  avocado  apple

Conclusion

In this C++ Tutorial, we learned how to sort given string vector lexicographically in ascending order or descending order.