Standard Template Library (STL) in C++

Standard Template Library (STL) in C++

The Standard Template Library (STL) is a powerful library that is part of the C++ Standard Library. It provides a collection of reusable algorithms, data structures, and other components that can be used in a wide range of C++ programs. In this blog, we will discuss the key components of the STL and how they can be used to improve the efficiency and readability of your C++ code.

Containers

Vector

A vector is a dynamic array that can grow or shrink in size. It provides random access to its elements and allows for fast insertion and deletion at the end of the vector. Here is an example of how to use a vector in C++:

cppCopy code#include <vector>
#include <iostream>

int main() {
  std::vector<int> v;

  // Add elements to the vector
  v.push_back(1);
  v.push_back(2);
  v.push_back(3);

  // Iterate over the vector
  for (int i = 0; i < v.size(); ++i) {
    std::cout << v[i] << " ";
  }

  // Output: 1 2 3

  return 0;
}

Map

A map is an associative container that stores a key-value pair. It allows for fast lookup and insertion of elements based on the key. Here is an example of how to use a map in C++:

cppCopy code#include <map>
#include <iostream>

int main() {
  std::map<std::string, int> m;

  // Add elements to the map
  m["one"] = 1;
  m["two"] = 2;
  m["three"] = 3;

  // Access elements in the map
  std::cout << "m[\"two\"] = " << m["two"] << std::endl;

  // Output: m["two"] = 2

  return 0;
}

Algorithms

Sort

The sort algorithm can be used to sort elements in a container in ascending or descending order. Here is an example of how to use the sort algorithm in C++:

cppCopy code#include <algorithm>
#include <vector>
#include <iostream>

int main() {
  std::vector<int> v = {3, 1, 4, 1, 5, 9, 2, 6, 5};

  // Sort the vector in ascending order
  std::sort(v.begin(), v.end());

  // Output the sorted vector
  for (int i = 0; i < v.size(); ++i) {
    std::cout << v[i] << " ";
  }

  // Output: 1 1 2 3 4 5 5 6 9

  return 0;
}

Transform

The transform algorithm can be used to apply a function to each element in a container and store the results in another container. Here is an example of how to use the transform algorithm in C++:

cppCopy code#include <algorithm>
#include <vector>
#include <iostream>

int square(int x) {
  return x * x;
}

int main() {
  std::vector<int> v = {1, 2, 3, 4, 5};
  std::vector<int> v_squared(v.size());

  // Square each element in the vector and store the results in v_squared
  std::transform(v.begin(), v.end(), v_squared.begin(), square);

  // Output the squared vector
  for (int i = 0; i < v_squared.size(); ++i) {
    std::cout << v_squared[i] << " ";
  }

  // Output: 1 4 9 16 25

  return 0;
}