using for each loops - Bugs!

When I create a simple array like this inside main or a function int array[] = {1, 2, 3, 4, 5}; everything is fine. However, when I create a pointer to an underlying array, I get errors. How can I fix this ?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
// Example program
#include <iostream>
#include <string>
using namespace std;

class cs{
    private:
    int *p;
    
    public:
    void print(){
        p[0] = 1;
        p[1] = 2;
        p[2] = 3;
        p[3] = 4;
        p[4] = 5;
        for(int& x : p){
            x++;
        }
        for(auto x : p){
            cout << x;
        }
    }
};

int main()
{
    cs use;
    use.print();
    return 0;
}
Use std::vector<>
Yes it worked when using vectors instead of pointer. Is there any way to fix this problem using pointers and classes?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <iostream>

struct A
{
    std::size_t sz = 5 ;
    int* ptr = new int[sz] { 0, 1, 2, 3, 4 };

    // ... 

    struct array_view // or: using array_view = std::experimental::basic_string_view<int> ;
    {
        int* p ;
        std::size_t n ;

        int* begin() { return p ; }
        int* end() { return p+n ; }

        const int* begin() const { return p ; }
        const int* end() const { return p+n ; }
    };

    void print() const { for( int v : array_view{ptr,sz} ) std::cout << v << '\n' ; }
};

int main()
{
    A a ;
    a.print() ;
}

http://coliru.stacked-crooked.com/a/cd9d2efd6ecc267d
Topic archived. No new replies allowed.