To sort a vector of strings in C++, you can use the sort
function from the <algorithm>
header.
In this example,
<vector>
and <algorithm>
.vec
and initialize it with some string values.sort
function from the <algorithm>
header to sort the elements of the vector in ascending order. By default, the sort
function sorts elements in dictionary order.#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<std::string> vec = {"banana", "apple", "orange", "grape"};
std::sort(vec.begin(), vec.end());
std::cout << "Sorted vector: ";
for (const std::string& str : vec) {
std::cout << str << " ";
}
std::cout << std::endl;
return 0;
}
Sorted vector: apple banana grape orange
In this tutorial, we learned How to Sort a String Vector in Dictionary Order in C++ language with well detailed examples.