C++ / C++ Templates and STL

Working with STL Containers and Iterators

This tutorial focuses on using STL containers and iterators. You'll learn how to use different types of data structures provided by STL in C++ programming.

Tutorial 4 of 5 5 resources in this section

Section overview

5 resources

Introduces templates, generic programming, and the Standard Template Library (STL).

Introduction

In this tutorial, we will focus on learning how to use the Standard Template Library (STL) containers and iterators in C++ programming. STL is a powerful feature in C++ that provides predefined templates for a set of common data structures and algorithms.

Goals

By the end of this tutorial, you will be able to:

  1. Understand what STL containers and iterators are.
  2. Use different types of STL containers like vectors, lists, sets etc.
  3. Use STL iterators to access and manipulate data in STL containers.

Prerequisites

This tutorial assumes you have a basic knowledge of C++ syntax and programming concepts. Familiarity with basic data structures will be helpful but not necessary.

Step-by-Step Guide

STL Containers

STL containers are template-based data structures. They can store any data type that can be copied or moved, like integers, floating point numbers, custom objects, etc. The primary STL container types are:

  1. Sequence containers (vector, list, deque, array, forward_list): These containers implement data structures which can be accessed sequentially.

  2. Container adaptors (queue, priority_queue, stack): These are not full container classes, but wrappers that provide a specific interface relying on an object of one of the container classes.

  3. Associative containers (set, multiset, map, multimap): These containers implement sorted data structures that can be quickly searched.

  4. Unordered Associative containers (unordered_set, unordered_multiset, unordered_map, unordered_multimap): These containers implement unsorted (hashed) data structures that can be quickly searched.

STL Iterators

Iterators in STL provide a way to access the elements in a container sequentially without exposing the underlying structure of the container. Iterators essentially act like pointers.

Code Examples

Using Vector (STL Container)

#include <iostream>
#include <vector>

int main() {
    // Declare a vector
    std::vector<int> vec;

    // Add elements to the vector
    vec.push_back(10);
    vec.push_back(20);
    vec.push_back(30);

    // Access elements using an iterator
    for(std::vector<int>::iterator it = vec.begin(); it != vec.end(); it++) {
        std::cout << *it << " ";
    }

    return 0;
}

Output

10 20 30

In this example, we declare a vector vec and add elements using push_back(). We then use an iterator (it) to access and print each element in the vector.

Using Set (STL Container)

#include <iostream>
#include <set>

int main() {
    // Declare a set
    std::set<int> s;

    // Add elements to the set
    s.insert(10);
    s.insert(20);
    s.insert(30);
    s.insert(20); // This will not be added, as sets do not allow duplicate elements

    // Access elements using an iterator
    for(std::set<int>::iterator it = s.begin(); it != s.end(); it++) {
        std::cout << *it << " ";
    }

    return 0;
}

Output

10 20 30

In this example, we declare a set s and add elements using insert(). Notice that attempting to insert a duplicate element has no effect, as sets do not allow duplicate elements. We then use an iterator to access and print each element in the set.

Summary

In this tutorial, we have learned about STL containers and iterators in C++. We've seen how to declare, populate, and access data in several types of STL containers using iterators. For further exploration of STL, consider learning about different types of iterators (like forward iterators, bidirectional iterators, etc.) and other STL components like algorithms and functors.

Practice Exercises

  1. Exercise 1: Create a std::list of integers and print its elements in reverse order.

  2. Exercise 2: Create a std::map where keys are names (strings) and values are ages (integers). Insert some data in the map and print all names with their corresponding ages.

  3. Exercise 3: Create a std::unordered_set of integers, insert some data into it and print all unique elements (an unordered_set only stores unique elements).

Solutions and explanations will be provided upon request.

Further Resources

  1. C++ Reference
  2. Learn C++
  3. C++ STL Tutorial

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

PDF Password Protector

Add or remove passwords from PDF files.

Use tool

Word to PDF Converter

Easily convert Word documents to PDFs.

Use tool

QR Code Generator

Generate QR codes for URLs, text, or contact info.

Use tool

MD5/SHA Hash Generator

Generate MD5, SHA-1, SHA-256, or SHA-512 hashes.

Use tool

EXIF Data Viewer/Remover

View and remove metadata from image files.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help