Looping through a vector using indices in C++


In some instances, we will want to loop through a vector using indices.

The indices of a vector meals are all the integer values from 0 to meals.size() - 1, so we can iterate over them using an index variable i:

vector<string> meals = {"pancakes", "pasta", "pizza", "avocado"};

for (int i = 0; i < meals.size(); i++) {
	cout << "Meal number " << (i + 1) << " is " << meals[i] << ".\n";
}

The output of this code is:

Meal number 1 is pancakes.
Meal number 2 is pasta.
Meal number 3 is pizza.
Meal number 4 is avocado.

Assignment
Now let's print the temperature on each day, in this format:

On day 1 the temperature is 10.

On day 2 the temperature is 60.

...


Hint
Look at the examples above if you get stuck.


Introduction

Looping through a vector using indices is a fundamental concept in C++ programming. It allows you to access and manipulate each element in a vector efficiently. This technique is particularly useful in scenarios where you need to perform operations on each element of a collection, such as processing data, generating reports, or transforming elements.

Understanding the Basics

A vector in C++ is a dynamic array that can grow and shrink in size. Each element in a vector can be accessed using an index, which starts from 0 and goes up to vector.size() - 1. Understanding how to loop through a vector using indices is crucial for performing operations on each element.

Consider the following simple example:

#include <iostream>
#include <vector>
using namespace std;

int main() {
    vector<string> meals = {"pancakes", "pasta", "pizza", "avocado"};
    for (int i = 0; i < meals.size(); i++) {
        cout << "Meal number " << (i + 1) << " is " << meals[i] << ".\n";
    }
    return 0;
}

This code iterates through the vector meals and prints each meal with its corresponding number.

Main Concepts

The key concept here is using a loop to iterate through the vector. The loop variable i serves as the index to access each element in the vector. The loop runs from 0 to meals.size() - 1, ensuring that all elements are processed.

Here is a step-by-step breakdown of the code:

Examples and Use Cases

Let's consider another example where we have a vector of temperatures for a week, and we want to print the temperature for each day:

#include <iostream>
#include <vector>
using namespace std;

int main() {
    vector<int> temperatures = {10, 60, 30, 25, 40, 50, 20};
    for (int i = 0; i < temperatures.size(); i++) {
        cout << "On day " << (i + 1) << " the temperature is " << temperatures[i] << ".\n";
    }
    return 0;
}

This code will output:

On day 1 the temperature is 10.
On day 2 the temperature is 60.
On day 3 the temperature is 30.
On day 4 the temperature is 25.
On day 5 the temperature is 40.
On day 6 the temperature is 50.
On day 7 the temperature is 20.

Common Pitfalls and Best Practices

When looping through a vector using indices, it's important to ensure that the index variable does not exceed the vector's size. This can lead to out-of-bounds errors. Always use vector.size() to determine the loop's upper limit.

Best practices include:

Advanced Techniques

For more advanced usage, consider using range-based for loops or iterators, which provide a cleaner and more readable way to iterate through vectors:

#include <iostream>
#include <vector>
using namespace std;

int main() {
    vector<int> temperatures = {10, 60, 30, 25, 40, 50, 20};
    int day = 1;
    for (int temp : temperatures) {
        cout << "On day " << day++ << " the temperature is " << temp << ".\n";
    }
    return 0;
}

Code Implementation

Here is the complete code for the assignment:

#include <iostream>
#include <vector>
using namespace std;

int main() {
    vector<int> temperatures = {10, 60, 30, 25, 40, 50, 20};
    for (int i = 0; i < temperatures.size(); i++) {
        cout << "On day " << (i + 1) << " the temperature is " << temperatures[i] << ".\n";
    }
    return 0;
}

Debugging and Testing

When debugging code that loops through a vector, ensure that the loop boundaries are correct. Use print statements to verify the index and the accessed element. Writing test cases for different vector sizes and contents can help ensure the code works correctly.

Example test case:

#include <cassert>

void test_temperature_output() {
    vector<int> temperatures = {10, 60, 30};
    // Expected output:
    // On day 1 the temperature is 10.
    // On day 2 the temperature is 60.
    // On day 3 the temperature is 30.
    // (You can capture and compare the output using stringstreams in actual tests)
}

int main() {
    test_temperature_output();
    return 0;
}

Thinking and Problem-Solving Tips

When approaching problems that involve looping through vectors, break down the problem into smaller parts. First, ensure you can access each element correctly. Then, focus on the specific operation you need to perform on each element. Practice with different types of vectors and operations to build confidence.

Conclusion

Mastering the technique of looping through a vector using indices is essential for efficient C++ programming. It allows you to perform operations on each element of a collection systematically. Practice this technique with various examples to strengthen your understanding and improve your coding skills.

Additional Resources