To sort multiple strings in C++, put them in a container such as std::vector<std::string> and call std::sort(strings.begin(), strings.end()), including <algorithm>. By default, the strings are ordered lexicographically; a comparator lets you choose a different rule, such as descending order or sorting by length.
A complete example with std::vector
A vector is a convenient way to hold a changeable number of strings. This complete program sorts the elements in place and prints them in their new order:
#include <algorithm>
#include <iostream>
#include <string>
#include <vector>
int main() {
std::vector<std::string> words = {"pear", "apple", "orange"};
std::sort(words.begin(), words.end());
for (const std::string& word : words) {
std::cout << word << '\n';
}
}
The output is apple, orange, then pear, each on its own line. std::sort receives a pair of iterators: the first points to the start of the range and the second points just past its last element. The function rearranges the vector itself; it does not create a separately sorted copy.
What “lexicographic” order means
Lexicographic order compares strings from left to right, much like dictionary order. At the first position where two strings differ, the string with the lower character value comes first. If one string is a prefix of another, the shorter string comes first: for example, "car" precedes "cart". Identical strings compare as equivalent for the default ordering.
This is a character-based ordering, not a sort by word length. For instance, "zebra" comes after "ant" even though it is longer, because its first character sorts later. The comparison used by std::string is not a language-aware dictionary sort. In common ASCII-compatible encodings, uppercase English letters generally sort before lowercase letters, so a mixed-case result may not match a person’s expected dictionary order. The exact character ordering depends on the character representation and comparison rules in use.
Sorting in descending order
To reverse the default ordering, pass std::greater<std::string>{} as the third argument. The <functional> header declares this comparator:
#include <algorithm>
#include <functional>
#include <string>
#include <vector>
std::vector<std::string> words = {"pear", "apple", "orange"};
std::sort(words.begin(), words.end(), std::greater<std::string>{});
After this call, the vector contains the strings in reverse lexicographic order. Another option is to sort ascending and then reverse the range with std::reverse, but supplying a comparator states the desired ordering directly and avoids an extra pass over the elements.
Using a custom comparison rule
The third parameter to std::sort can be a function, function object, or lambda. It must answer whether its first argument should appear before its second. For example, this comparator sorts by increasing string length and uses ordinary lexicographic order to break ties:
std::sort(words.begin(), words.end(),
[](const std::string& a, const std::string& b) {
if (a.size() != b.size()) {
return a.size() < b.size();
}
return a < b;
});
For "pear", "fig", and "plum", the result is "fig", "pear", "plum". The two four-character strings are ordered lexicographically after their lengths tie. The lambda takes references to avoid copying each string during comparisons.
A comparator must establish a consistent strict ordering. In practical terms, do not use <= as the comparison: an element must not be considered to come before itself. Inconsistent rules can make the behavior of std::sort undefined. If the data has multiple ordering criteria, write them in a clear sequence of comparisons, as in the length example.
Case-insensitive sorting and text expectations
There is no built-in std::sort mode that automatically performs a culturally correct, case-insensitive dictionary sort. For simple byte-oriented text, a comparator can compare lowercase forms. When using the C character conversion function std::tolower, cast each character to unsigned char first; passing a negative plain char value is not valid except for the special end-of-file value.
#include <cctype>
#include <algorithm>
#include <string>
#include <vector>
std::sort(words.begin(), words.end(),
[](const std::string& a, const std::string& b) {
return std::lexicographical_compare(
a.begin(), a.end(), b.begin(), b.end(),
[](char x, char y) {
return std::tolower(static_cast<unsigned char>(x))
< std::tolower(static_cast<unsigned char>(y));
});
});
This is a basic byte-by-byte comparison, not full Unicode case folding or locale-aware collation. It may be suitable for simple English text in a known environment, but it is not a complete solution for names or text in many languages. If users expect language-specific rules, use a Unicode or locale-aware collation library designed for that requirement. Also decide how to order strings that differ only by case; this comparator treats their lowercase character sequences as equivalent.
Arrays, lists, and other containers
std::sort needs random-access iterators, so it works with std::vector, std::array, and ordinary arrays. For a built-in array called names with count elements, the iterator range can be written as names to names + count. For std::array, use its begin() and end() members in the same way as a vector.
A std::list does not provide random-access iterators, so it cannot be passed to std::sort. Use the list’s member function instead: names.sort(), or names.sort(comparator) for a custom order. This is a useful distinction when choosing a container: vectors are often a straightforward choice for a collection you want to sort with the standard algorithm, while a list has its own sorting operation.
Sorting many strings versus sorting characters
A common point of confusion is the difference between sorting a collection of strings and sorting the characters inside one string. With a vector of strings, std::sort(words.begin(), words.end()) reorders whole words. It does not rearrange the letters within each word. To sort the characters in one std::string, call the algorithm on that string’s own iterators instead:
std::string word = "pear";
std::sort(word.begin(), word.end());
That operation changes the string to "aepr". If the goal is to alphabetize a list of words, sort the outer vector or array. If the goal is to rearrange letters in an individual word, sort the string itself. Applying a custom comparator to the outer collection can also order whole strings by a property such as length, but it still does not alter the letters inside them.
Complexity, stability, and alternatives
std::sort has O(N log N) comparison complexity for a range of N elements, making it a general-purpose choice for sorting. String comparisons can take longer than a single operation because they may inspect multiple characters before finding a difference. If many strings share long prefixes, those comparisons can therefore involve more character work than comparisons of short, dissimilar strings.
The algorithm is not stable: elements that compare equivalent are not guaranteed to retain their original relative order. If preserving that order matters—for example, records are sorted by a key while equal-key records should keep their prior sequence—use std::stable_sort with the same range and comparator. Stability does not change the ordering rule; it only preserves the order of equivalent elements.
For a small collection, std::sort is still usually the simplest correct approach. If the collection is a list, use list::sort. If you need a sorted copy while keeping the original vector unchanged, copy the vector first and sort the copy. C++20 also offers ranges algorithms such as std::ranges::sort, which can make some calls more concise, but the iterator-based std::sort form remains widely used and works in older language versions.
Common mistakes to avoid
- Forgetting the header: include
<algorithm>forstd::sort. Include<string>and the container header you use as well. - Passing the wrong end iterator: the second iterator marks the position after the last element, not the last element itself. For a vector,
end()expresses that boundary correctly. - Expecting the original order to remain: sorting changes the container in place. Make a copy first if you need to keep the unsorted sequence.
- Using
std::sorton a list: list iterators are not random access. Call the list’s membersortinstead. - Writing a flawed comparator: a comparator should define a consistent “comes before” relationship. Avoid rules that use non-strict comparisons or depend on changing external state.
- Assuming natural-language order: default string sorting does not automatically ignore case, understand accents, or apply dictionary rules for a particular language.
Frequently Asked Questions
How do I sort multiple strings alphabetically in C++?
Store them in a random-access container such as std::vector<std::string>, include <algorithm>, and call std::sort(words.begin(), words.end()). The default is lexicographic character order, which may differ from a language-aware dictionary order.
Does std::sort work directly on a string?
Yes, but it sorts the characters within that one string. To sort several complete strings, pass the iterators of their container, such as a vector, instead.
How can I sort strings by length?
Pass a comparator that returns a.size() < b.size(). If equal-length strings also need a predictable order, add a tie-break such as a < b.
How do I sort strings without regard to case?
Use a comparator that compares normalized or case-folded text. A simple std::tolower-based comparator can work for limited byte-oriented text, but it does not provide full Unicode or locale-aware sorting.
Does std::sort preserve the order of duplicate or equivalent strings?
No. Use std::stable_sort if the relative order of elements that compare equivalent must be retained. For identical plain strings, that difference may not be visible, but it matters for records or custom comparisons.
Related
- How to Split an Array in Java: Safe Ways to Do It Cleanly
- Balance of Payments Notes: Accounts, Examples and Meaning
- Java split(): How It Handles Delimiters and Limits
Try it: the Formula Explainer: paste any formula and see each function and reference in plain English.
More in Formulas & functions
- Excel Text Functions List: Names, Uses, and ExamplesExcel’s text functions help you extract, combine, clean, compare, format, and convert text or values. The main functions…
- How to Find the Minimum in Excel Using the MIN FunctionTo find the smallest number in a range, use Excel’s MIN function. If your values are in cells…
- Excel Protect Sheet: Let a Table Expand SafelyIn Excel for Microsoft 365 on Windows, there is no built-in Protect Sheet setting that reliably lets people…
- Cannot Filter in Excel? Causes, Checks, and FixesYes—Excel can filter both ordinary data ranges and tables. In Microsoft 365 for Windows, select a cell in…
- Excel: How to Filter a Table Based on a List of ValuesYes. In Excel for Microsoft 365, you can return only the rows in a table whose values appear…
- Calculate Number of Years in Excel: Dates and FormulasTo calculate the number of complete years between two dates in Excel, enter the earlier date in A2…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.