How do I iterate through a list of numbers, and how many different ways are there to do it?
What I thought would work:
#include <cstdlib>
#include <iostream>
#include <list>
using namespace std;
int main()
{
int numbers[] = {2, 4, 6, 8};
int i = 0;
for(i=0; i< numbers.size();i++)
cout << "the current number is " << numbers[i];
system("pause");
return 0;
}
I get an error on the for loop line:
request for member
'size'in'numbers', which is of non-class type'int[4]'
Unlike a lot of modern languages plain C++ arrays don’t have a
.size()function. You have a number of options to iterate through a list depending on the storage type.Some common options for storage include:
Your options for iteration will depend on the type you’re using. If you’re using a plain old C array you can either store the size somewhere else or calculate the size of the array based on the size of it’s types. Calculating the size of an array has a number of drawbacks outlined in this answer by DevSolar
If you’re using any type that provides a
.begin()and.end()function you can use those to get an iterator which is considered good style in C++ compared to index based iteration:Vectors are also special because they are designed to be drop-in replacements for arrays. You can iterate over a vector exactly how you would over an array with a
.size()function. However this is considered bad practice in C++ and you should prefer to use iterators where possible:C++11 (the new standard) also brings the new and fancy range based for that should work on any type that provides a
.begin()and.end(). However: Compiler support can vary for this feature. You can also usebegin(type)andend(type)as an alternative.std::beginalso has another interesting property: it works on raw arrays. This means you can use the same iteration semantics between arrays and non-arrays (you should still prefer standard types over raw arrays):You also need to be careful if you want to delete items from a collection while in a loop because calling
container.erase()makes all existing iterators invalid:This list is far from comprehensive but as you can see there’s a lot of ways of iterating over a collection. In general prefer iterators unless you have a good reason to do otherwise.