4

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;
    }
}
Mike Kinghan
  • 55,740
  • 12
  • 153
  • 182
Ben Jones
  • 504
  • 4
  • 18
  • 1
    You're using a C-style array. You should use `vector`. – Qubit Oct 01 '18 at 09:01
  • 4
    Arrays like that were inherited from C and as such aren't objects with member functions. Read more about [`std::array`](http://en.cppreference.com/w/cpp/container/array) and [`std::vector`](http://en.cppreference.com/w/cpp/container/vector) for possible replacements. – Some programmer dude Oct 01 '18 at 09:02
  • There are no known good C++ tutorials online, and you can't learn C++ by trial and error. Check out [the book list](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). – molbdnilo Oct 01 '18 at 09:24
  • Not sure what the current state of dev-c++ is, but I believe very old and outdated (2015?). On Window's id recommend Visual Studio 2017 Community, Mac has XCode and cross platform / Linux you have Eclipse, NetBeans, and I believe CodeBlocks is still good (been some years for me). Would likely help with your issue with Some programmer dude's answer. – Fire Lancer Oct 01 '18 at 09:43

4 Answers4

14

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.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
  • I tried this but DEV-C++ gives an error: "range-based 'for' loops are not allowed in C++98 mode" – Ben Jones Oct 01 '18 at 09:10
  • 1
    @BenJones: Try using `-std=c++17` (Clang/GCC) or `/std=c++17` (MSVC) – JVApen Oct 01 '18 at 09:26
  • 4
    Since C++17, one can use [`std::size()`](https://en.cppreference.com/w/cpp/iterator/size) to get number of array elements. It also has the advantage to throw a compiler error, when used with arrays that are decayed to pointer. – zett42 Oct 01 '18 at 09:56
  • 1
    ... and even without C++17, writing a short template like `std::size` is better than using a trick and worrying about its caveats. – StoryTeller - Unslander Monica Oct 01 '18 at 10:07
1

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) {
    // ...
}
Dietmar Kühl
  • 150,225
  • 13
  • 225
  • 380
0

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;
}
}
Chandini
  • 540
  • 2
  • 11
0

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;
}
Arjun Singh
  • 7
  • 1
  • 6
  • your example will not compile – pptaszni Oct 08 '18 at 07:37
  • Yes, it won't compile because look at the for loop haha, there are no statements in the for loop body. You could add the jump statement "continue" and it should compile then. Overall, I was just giving an example on how to traverse through the array without manually entering the size of the array for a predefined array. – Arjun Singh Oct 09 '18 at 08:18