OOP

Standard Template Library

The Standard Template Library (STL) is a powerful collection of classes, functions, and algorithms in C++. It provides generic components that you can use to implement various data structures and algorithms without writing everything from scratch. Here’s a breakdown of the key components of the STL:

1. Containers:

Examples - Vectors:

#include <iostream>
#include <vector>

int main() {
  std::vector<int> numbers; // Create an empty vector of integers
  numbers.push_back(5);     // Add elements to the vector
  numbers.push_back(3);
  numbers.push_back(8);

  std::cout << "Vector elements: ";
  for (int num : numbers) { // Loop using range-based for loop
    std::cout << num << " ";
  }
  std::cout << std::endl;

  return 0;
}

Examples - Sets(Unique Sorted Elements):

#include <iostream>
#include <set>

int main() {
  std::set<std::string> names; // Create a set of strings
  names.insert("Alice");      // Insert elements into the set
  names.insert("Bob");
  names.insert("Alice"); // Duplicates are automatically ignored

  std::cout << "Unique names in the set: ";
  for (const std::string& name : names) {
    std::cout << name << " ";
  }
  std::cout << std::endl;

  return 0;
}

2. Algorithms:

Examples - Sorting

#include <iostream>
#include <vector>
#include <algorithm>

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

  std::sort(numbers.begin(), numbers.end()); // Sort elements in ascending order

  std::cout << "Sorted numbers: ";
  for (int num : numbers) {
    std::cout << num << " ";
  }
  std::cout << std::endl;

  return 0;
}

Examples - Finding Minimum / Maximum

#include <iostream>
#include <vector>
#include <algorithm>

int main() {
  std::vector<int> numbers = {7, 2, 9, 1, 5};

  int minimum = *std::min_element(numbers.begin(), numbers.end());
  int maximum = *std::max_element(numbers.begin(), numbers.end());

  std::cout << "Minimum element: " << minimum << std::endl;
  std::cout << "Maximum element: " << maximum << std::endl;

  return 0;
}

3. Iterators:

Example - Iterating through a Vector

#include <iostream>
#include <vector>

int main() {
  std::vector<int> numbers = {4, 1, 7, 3};

  // Loop using iterator
  for (std::vector<int>::iterator it = numbers.begin(); it != numbers.end(); ++it) {
    std::cout << *it << " "; // Access element through iterator
  }
  std::cout << std::endl;

  return 0;
}

Benefits of Using the STL:

Things to Consider with the STL:

Common Use Cases of the STL:

In conclusion, the STL is a valuable asset for any C++ programmer. It provides a powerful foundation for building efficient and maintainable C++ applications. By learning and using the STL effectively, you can significantly improve your code quality and development speed.

Standard Template Library(pdf) provided by cppreference.com