SoFunction
Updated on 2025-04-05

Implementation of based for loop in C++

In C++,based forLooping is not a standard syntax, maybe what you want to ask is actuallyRange-basedforCycle. This loop syntax was introduced in C++11 and aims to simplify traversing containers (such as arrays,std::vectorstd::mapetc.) code.

Range-based for loop (Range-based for Loop)

Range baseforLoops are used to iterate through all elements in a container or array without explicitly using indexes or iterators. Its syntax is very concise and works for any container that can iterate.

Syntax format

for (declaration : container) {
    // Circulation body}
  • declaration: Each iteration, an element in the container will be assigned to the declared variable. Can be a reference type to avoid unnecessary copying.
  • container: It can be an array or container (such asstd::vectorstd::liststd::mapetc.) or other iterable data structures.

example

1. Iterate over the array

#include <iostream>

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

    // Use range base for loop through array    for (int num : arr) {
        std::cout << num << " ";
    }

    return 0;
}

Output:

1 2 3 4 5

In this example,numEach element in the array will be obtained in turn until the complete array is traversed.

2. Traverse std::vector

#include <iostream>
#include <vector>

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

    // Use range base for loop to traverse std::vector    for (int num : vec) {
        std::cout << num << " ";
    }

    return 0;
}

Output:

10 20 30 40 50

3. Use references to avoid copying

If the element in the container is a larger object, or you do not want to copy the element, use references to avoid unnecessary copying.

#include <iostream>
#include <vector>

class Person {
public:
    std::string name;
    Person(std::string n) : name(n) {}
};

int main() {
    std::vector<Person> people = {Person("Alice"), Person("Bob"), Person("Charlie")};

    // Use references to avoid copying    for (Person& p : people) {
        std::cout <<  << " ";
    }

    return 0;
}

Output:

Alice Bob Charlie

4. Use constant references

If there is no need to modify elements in the container, constant references can be used to improve efficiency (avoid unnecessary copying and protect data from being modified).

#include <iostream>
#include <vector>

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

    // Use constant references to avoid copying and not modifying elements    for (const int& num : vec) {
        std::cout << num << " ";
    }

    return 0;
}

Output:

1 2 3 4 5

Special usage

5. Traverse std::map or std::unordered_map

Forstd::maporstd::unordered_map, Each element is a key-value pair, so it needs to be used when iteratingautoTo deduce the type.

#include <iostream>
#include <map>

int main() {
    std::map<int, std::string> m = {{1, "One"}, {2, "Two"}, {3, "Three"}};

    // traverse map (key value pair)    for (const auto& pair : m) {
        std::cout << "Key: " <<  << ", Value: " <<  << std::endl;
    }

    return 0;
}

Output:

Key: 1, Value: One
Key: 2, Value: Two
Key: 3, Value: Three

Summarize

Range baseforCycleIt is a simple and intuitive way to traverse containers, it:

  • Simplify the code: No explicit use of iterators or indexes.
  • Improve readability: The code is more concise and easy to understand.
  • Reduce errors: Avoid manual operation of indexes or iterators.
  • Performance optimization: References can be used to avoid unnecessary copying of elements, especially when dealing with larger data types.

Use range baseforLooping can greatly improve the simplicity and readability of the code, especially when it is necessary to traverse the container.

This is the end of this article about the implementation of based for loops in C++. For more related contents of C++ based for loops, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!