Language: EN

cpp-bucle-basado-en-rangos

What are range loops in C++

The range loop in C++ is a control structure that allows you to easily iterate over the elements of a collection (such as arrays, vectors, or lists).

Unlike for, while, and do-while loops, the range loop is specifically designed to traverse elements of a collection without the need to handle indices explicitly.

The range loop offers several advantages over traditional loops. The syntax is clearer and more concise (which makes it easier to understand and maintain the code).

Moreover, since it does not depend on indices, the possibility of making errors when accessing elements of the collection is reduced.

If you want to learn more about Loops
check out the Introduction to Programming Course read more ⯈

Basic Syntax

In C++, the range-based loop has the following syntax,

for (auto& element : collection)
{
    // Code to execute for each element in the collection
}
  • auto&: Specifies the type of the element, and auto allows type deduction automatically. Using & avoids unnecessary copies of the elements.
  • element: Is a variable that represents each element of the collection in each iteration.
  • collection: Is the collection being iterated over (for example, an array, a vector, a list).

Basic Example

Let’s look at a basic example where we use the range-based loop to print the numbers in an array:

#include <iostream>

int main() {
    int numbers[] = { 1, 2, 3, 4, 5 };

    for (int number : numbers)
    {
        std::cout << number << std::endl;
    }

    return 0;
}

In this example:

  • int number : numbers iterates over each element in the numbers array.
  • std::cout prints each number to the console.

The result will be that the numbers from 1 to 5 will be printed on the screen.

Modifying Elements

In C++, the range-based loop allows modifying the elements of the collection if a reference is used:

#include <iostream>
#include <vector>

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

    for (int& number : numbers) // Use reference to modify
    {
        number *= 2; // Double the value of each element
    }

    for (const int& number : numbers) // Iterate again to print
    {
        std::cout << number << std::endl;
    }

    return 0;
}

Custom Collections

To use the range-based loop with custom collections, they must be iterable and provide an iterator.

Standard collections in C++ (like std::vector, std::list, and std::array) already meet these requirements, but for custom collections, you must implement the begin() and end() operators.

#include <iostream>
#include <vector>

int main() {
    std::vector<int> numbers = { 10, 20, 30, 40, 50 };

    for (int number : numbers)
    {
        std::cout << number << std::endl;
    }

    return 0;
}

Practical Examples of the Range-based Loop

Iterating Over a Vector of Numbers

Suppose we have a vector of integers and want to print each one of them to the console. Using the range-based loop, the code would be as follows:

#include <iostream>
#include <vector>

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

    for (const int& number : numbers)
    {
        std::cout << number << std::endl;
    }

    return 0;
}

Iterating Over an Array of Strings

If we have an array of strings and want to perform some operation on each of them, the range-based loop is the ideal option:

#include <iostream>
#include <string>

int main() {
    std::string names[] = { "Juan", "María", "Pedro" };

    for (const std::string& name : names)
    {
        std::cout << name << std::endl;
    }

    return 0;
}

Summing Elements in a Vector

#include <iostream>
#include <vector>

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

    for (const int& number : numbers)
    {
        sum += number;
    }

    std::cout << "The sum of the numbers is: " << sum << std::endl;

    return 0;
}

Searching for an Element in a Vector

#include <iostream>
#include <vector>

int main() {
    std::vector<int> numbers = { 10, 20, 30, 40, 50 };
    int search = 30;
    bool found = false;

    for (const int& number : numbers)
    {
        if (number == search)
        {
            found = true;
            break;
        }
    }

    if (found)
    {
        std::cout << "The number " << search << " is in the vector." << std::endl;
    }
    else
    {
        std::cout << "The number " << search << " is not in the vector." << std::endl;
    }

    return 0;
}

Iterating Over Lists

The range-based loop can also be used to iterate over elements in a list:

#include <iostream>
#include <list>

int main() {
    std::list<int> numbers = { 10, 20, 30, 40, 50 };

    for (const int& number : numbers)
    {
        std::cout << number << std::endl;
    }

    return 0;
}

Iterating Over Custom Collections

For custom collections, ensure that they implement the begin() and end() methods:

#include <iostream>
#include <vector>

class MyCollection {
public:
    void add(int value) {
        elements.push_back(value);
    }

    std::vector<int>::iterator begin() {
        return elements.begin();
    }

    std::vector<int>::iterator end() {
        return elements.end();
    }

private:
    std::vector<int> elements;
};

int main() {
    MyCollection collection;
    collection.add(1);
    collection.add(2);
    collection.add(3);

    for (int value : collection)
    {
        std::cout << value << std::endl;
    }

    return 0;
}

These examples are intended to show how to use the range-based loop. It does not mean that it is the best way to solve the problems they address. There are usually better alternatives.