Range based for loop and arrays - Bug!

I know there is an alternative to this code which I have already provided, but is there any way to fix the bug with the range based for loop ?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
using namespace std;

void print(const int score [], const int size){
    
	for (int x : score){
		cout << x << " ";
	}
	
	// Alternative:
	
// 	for (int i = 0; i < size; i++){
// 	    cout << score[i] << " ";
// 	}

}

int main(){
	int score[] = {1, 2, 3, 4, 5};
	int size = sizeof(score)/sizeof(int);

	print(score, size);
    return 0;
}
To make use of the range-based for-loop you have to provide either begin() and end() member functions or overload the non-member begin() and end() functions.

http://stackoverflow.com/questions/15904896/range-based-for-loop-on-a-dynamic-array

To make ranged for loops work with arrays, you can do:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
// capture size of array with a template
// pass array by reference
template<int size>
void print(const int (&score)[size])
{
    // ...
}

int main()
{
    // ...
    
    print( score )
}


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
void print(const int score[], const int size)
{
    // make a temporary vector via the range ctor
    // http://www.cplusplus.com/reference/vector/vector/vector/
    for( int x : std::vector<int>( score, score + size ) ) {
        std::cout << x << " ";
    }
}

int main()
{
    // ...
    
    print( score, size )
}


or just use a vector or the STL array.
http://www.cplusplus.com/reference/array/array/
Just use a vector, they were invented to solve the problems that ordinary arrays have. As I said before don't mix C and C++.
> is there any way to fix the bug with the range based for loop ?

The simplest fix is to let the compiler figure out what the sequence in question is, and the type of values it holds.

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>

template < typename SEQUENCE > void print( const SEQUENCE& /* SEQUENCE&& */ sequence ) {

	for( const auto& /* auto&& */ value : sequence ) std::cout << value << ' ' ;
	std::cout << '\n' ;
}

int main() {

	const int score[] = { 1, 2, 3, 4, 5 };
	print(score);
}


Topic archived. No new replies allowed.