Standard Template Library (STL) in C++
The Standard Template Library (STL) is a set of C++ template classes and functions that provide reusable, generic data structures and algorithms. It includes containers such as vectors, lists, and maps, as well as algorithms such as sorting and searching. Here's an example of using STL in C++:
c++
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> v = { 10, 20, 30, 40, 50 };
// Print the vector
std::cout << "Vector: ";
for (auto i : v) {
std::cout << i << " ";
}
std::cout << std::endl;
// Find the maximum element
auto max_element = std::max_element(v.begin(), v.end());
std::cout << "Maximum element: " << *max_element << std::endl;
// Sort the vector
std::sort(v.begin(), v.end());
// Print the sorted vector
std::cout << "Sorted vector: ";
for (auto i : v) {
std::cout << i << " ";
}
std::cout << std::endl;
return 0;
}
In this example, we're using the std::vector container class from the STL to create a vector of integers. We're then using the std::max_element function to find the maximum element in the vector and printing it to the console. We're also using the std::sort function to sort the elements of the vector in ascending order. Finally, we're printing the sorted vector to the console. When you run this program, you should see the following output:
yaml
Vector: 10 20 30 40 50
Maximum element: 50
Sorted vector: 10 20 30 40 50
No comments:
Post a Comment