To sort an array in ascending order in C++, you can use the `sort` function from the `algorithm` library for both arrays of integers and arrays of strings.
In this example,
numbers
.sort
function from the algorithm
library to sort the array of integers in-place.#include <iostream>
#include <algorithm>
#include <vector>
int main() {
std::vector<int> numbers = {5, 2, 8, 1, 9};
std::sort(numbers.begin(), numbers.end());
for (int num : numbers) {
std::cout << num << ' ';
}
return 0;
}
1 2 5 8 9
In this example,
words
.sort
function from the algorithm
library to sort the vector of strings in-place based on string comparison.#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
int main() {
std::vector<std::string> words = {"apple", "banana", "cherry", "date"};
std::sort(words.begin(), words.end());
for (const std::string& word : words) {
std::cout << word << ' ';
}
return 0;
}
apple banana cherry date
In this tutorial, we learned How to Sort an Array in Ascending Order in C++ language with well detailed examples.