I am trying to use a pointer to an array inside of a for each loop in C++. The code below won’t work because the “for each statement cannot operate on variables of type ‘int *'”. I’d prefer to use the new operator so that the array is on the heap and not the stack, but I just can’t seem to figure out the syntax here. Any suggestions?
#include <iostream>
using namespace std;
int main() {
int total = 0;
int* array = new int[6];
array[0] = 10; array[1] = 20; array[2] = 30;
array[3] = 40; array[4] = 50; array[5] = 60;
for each(int i in array) {
total += i;
}
cout << total << endl;
}
That
for eachthing you are using is a Visual C++ extension that’s not even recommended by some microsoft employees (I know I’ve heard STL say bad things about it, I can’t remember where).There are other options, like
std::for_each, and range-based for from C++11 (though I don’t think Visual C++ supports that yet). However, that’s not what you should be using here. You should be usingstd::accumulate, because this is the job that it was made for:If you’re really just interested in how to use this Microsoft
for eachconstruct, well, I’m pretty sure you can’t if you just have a pointer. You should use astd::vectorinstead. You should be doing that anyway.