C++ Standard Template Library (STL) Tutorial

The Standard Template Library (STL) in C++ is a powerful collection of classes and functions for data structures and algorithms. It includes containers, iterators, and algorithms that simplify common programming tasks.

Containers

STL provides several container types:

  • Sequence Containers: vector, deque, list.
  • Associative Containers: set, map, multiset, multimap.
  • Derived Containers: stack, queue, priority_queue.

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

int main() {
    vector<int> numbers = {1, 2, 3, 4, 5};
    for (int n : numbers) {
        cout << n << " ";
    }
    return 0;
}
                

Iterators

Iterators are used to traverse through STL containers:


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

int main() {
    vector<int> numbers = {1, 2, 3};
    for (vector<int>::iterator it = numbers.begin(); it != numbers.end(); ++it) {
        cout << *it << " ";
    }
    return 0;
}
                

Algorithms

STL includes built-in algorithms for sorting, searching, and more:


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

int main() {
    vector<int> numbers = {5, 3, 1, 4, 2};
    sort(numbers.begin(), numbers.end());

    for (int n : numbers) {
        cout << n << " ";
    }
    return 0;
}
                

Advantages of STL

  • Reduces development time by providing pre-built data structures and algorithms.
  • Increases code efficiency and safety.
  • Improves portability across different platforms.
0 Interaction
1.4K Views
Views
10 Likes
×
×
🍪 CookieConsent@Ptutorials:~

Welcome to Ptutorials

Note: We aim to make learning easier by sharing top-quality tutorials.

We kindly ask that you refrain from posting interactions unrelated to web development, such as political, sports, or other non-web-related content. Please be respectful and interact with other members in a friendly manner. By participating in discussions and providing valuable answers, you can earn points and level up your profile.

$ Allow cookies on this site ? (y/n)

top-home