Find the distance between two Iterators in a Set in C++

This tutorial will discuss how to find the distance between two iterators in a set in C++.

In C++, if you have a set containing various numbers and you want to determine the distance between two specific iterators, you can use the std::distance() function from the Standard Template Library (STL).

For instance, suppose you have a set, and you retrieve an iterator pointing to the value 2. Then you retrieve another iterator pointing to the value 7. To find the distance (or the number of elements) between these two iterators (or values), you can use std::distance().

std::set<int> numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

// Get the iterator to the elements with value 2
auto it1 = numbers.find(2);
// Get the iterator to the elements with values 7
auto it2 = numbers.find(7);


if (it1 != numbers.end() &&
    it2 != numbers.end())
{
    // Find the distance between the two iterators:
    int dist = std::distance(it1, it2);

    std::cout <<"Distance between two iterators: " << dist << std::endl;
}
else
{
    std::cout << "One of the elements not found in the set n";
}

It’s important to note that you cannot directly subtract these two iterators to obtain the distance between them. This is because, in a set, arithmetic operations other than incrementing or decrementing an iterator by one are not supported. Thankfully, std::distance() handles this for you and returns the exact number of elements between the two iterators.

So, by utilizing std::distance, you can easily find the distance between two iterators in a set in C++.

Let’s see the complete example,

#include <iostream>
#include <set>
#include <iterator>

int main()
{
    std::set<int> numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

    // Get the iterator to the elements with value 2
    auto it1 = numbers.find(2);

    // Get the iterator to the elements with values 7
    auto it2 = numbers.find(7);


    if (it1 != numbers.end() &&
        it2 != numbers.end())
    {
        // Find the distance between the two iterators:
        int dist = std::distance(it1, it2);

        std::cout <<"Distance between two iterators: " << dist << std::endl;
    }
    else
    {
        std::cout << "One of the elements not found in the set n";
    }

    return 0;
}

Output

Distance between two iterators: 5

Summary

Today, we learned how to find the distance between two iterators in a set in C++.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top