Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the recommended way loop through an array in C++?

Tags:

c++

arrays

I'm learning C++ (reasonably confident in JavaScript) and I can't find a C++ equivalent to the JS array.length;. I want a simple way to loop through an array based on the array length?

I have followed a number of tutorials but all seam to require the array length to be manually stated in the for loop (or pushed into the function)?

Below code gets an error and adding the #include causes a compiler error (DEV++).

Is there a C++ or reason why there is no simple call of the array length?

#include <iostream>
using namespace std;

int main () {
    int shoppingList [3] = {1, 2, 3};
    for (int i=0; i < shoppingList.size(); i++) {
        cout << shoppingList[i] << endl;
    }
}
like image 369
Ben Jones Avatar asked Sep 10 '25 13:09

Ben Jones


2 Answers

For a C-style array like you have you can use range-based for loops:

for (int value : shoppingList)
{
    std::cout << value << '\n';
}

As for getting the number of elements from an array, there's a "trick": You know the size of the array itself, and you know the size of each element in the array. That means if you divide the size of the array with the size of each element, you will get the number of elements.

In short

size_t numberElements = sizeof shoppingList / sizeof shoppingList[0];

Important note: This "trick" only works with actual arrays! Once an array have decayed to a pointer (to its first element, which often happens) all you're left with is the pointer. There's no way to get the size of the memory it points to, and this "trick" can not be used.


And as mentioned in my comment, the "best" solution is to use either std::array or std::vector.

like image 99
Some programmer dude Avatar answered Sep 13 '25 02:09

Some programmer dude


Built-in types don’t have member functions with C++. However, there is a non-member std::size(array) function:

for (std::size_t i{}; i != std::size(shoppingList); ++i) {
    // ...
}

Note that the counter is usinf std::size_t to match the signedness of the result of std::size(...). Also, do not use the sizeof hack suggested in other answers: it is a trap! The cde will happily compile when passing pointers to it but it will also produce the wrong result.

Of course, the idiomatic way to iterate over a range in C++, including arrays, is (assuming you only need the values and not their position):

for (int val: shoppingList) {
    // ...
}
like image 32
Dietmar Kühl Avatar answered Sep 13 '25 02:09

Dietmar Kühl