简体   繁体   中英

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

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;
    }
}

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 .

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) {
    // ...
}

Array doesn't have a direct size() member function, you can find the size of an array like this int size = sizeof(arr)/sizeof(arr[0]); and use it in the for loop.

#include <iostream>
using namespace std;

int main () {
int shoppingList [3] = {1, 2, 3};
int size = sizeof(shoppingList)/sizeof(shoppingList[0]);
for (int i=0; i < size(); i++) {
    cout << shoppingList[i] << endl;
}
}

You can do something like, sizeof(A)/sizeof(A[0]). This would give you the total number of elements in the array.

Let's take an example A = {1,2,3,4,5} // all ints If you evaluate sizeof(A)/sizeof(A[0]), it would give you 5 and as you see, you would not need to manually enter the size of the array.

Hope this helps. :)

#include <iostream>
using namespace std;

int main()
{
A = {1,2,3,4,5};
for (int i = 0; i< sizeof(A)/sizeof(A[0]); i++)
//whatever you want to do with this
return 1;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM