Book Image

Data Structures and Algorithms with the C++ STL

By : John Farrier
5 (2)
Book Image

Data Structures and Algorithms with the C++ STL

5 (2)
By: John Farrier

Overview of this book

While the Standard Template Library (STL) offers a rich set of tools for data structures and algorithms, navigating its intricacies can be daunting for intermediate C++ developers without expert guidance. This book offers a thorough exploration of the STL’s components, covering fundamental data structures, advanced algorithms, and concurrency features. Starting with an in-depth analysis of the std::vector, this book highlights its pivotal role in the STL, progressing toward building your proficiency in utilizing vectors, managing memory, and leveraging iterators. The book then advances to STL’s data structures, including sequence containers, associative containers, and unordered containers, simplifying the concepts of container adaptors and views to enhance your knowledge of modern STL programming. Shifting the focus to STL algorithms, you’ll get to grips with sorting, searching, and transformations and develop the skills to implement and modify algorithms with best practices. Advanced sections cover extending the STL with custom types and algorithms, as well as concurrency features, exception safety, and parallel algorithms. By the end of this book, you’ll have transformed into a proficient STL practitioner ready to tackle real-world challenges and build efficient and scalable C++ applications.
Table of Contents (30 chapters)
Free Chapter
1
Part 1: Mastering std::vector
7
Part 2: Understanding STL Data Structures
13
Part 3: Mastering STL Algorithms
19
Part 4: Creating STL-Compatible Types and Algorithms
23
Part 5: STL Data Structures and Algorithms: Under the Hood

Adding and removing elements

One of the advantages of std::vector over traditional arrays is its ability to resize dynamically. As applications evolve, so do data requirements; static data structures do not cut it. In this section, we will explore dynamic data management with std::vector, learning to seamlessly add to and remove from vectors while making sure we are staying safe.

Adding elements

Let’s start with adding elements. The push_back() member function is possibly the most straightforward way to add an element to the end of a vector. Suppose you have std::vector<int> scores; and wish to append a new score, say 95. You would simply invoke scores.push_back(95);, and voilà, your score is added.

Here’s a simple illustrative code example:

#include <iostream>
#include <vector>
int main() {
  std::vector<int> scores;
  std::cout << "Initial size of scores: " << scores.size()
  ...