cdummie
cdummie

Reputation: 163

Going through array using for_each loop in cpp

First off, here is the code:

#include <iostream>
#include <algorithm>

using namespace std;




class Array
{

    int* arr;
    int n;

    public:

    Array();
    Array(const Array&);
    Array(Array &&);
    Array& operator=(const Array&);
    Array& operator=(Array &&);
    void print();
    ~Array();
};

Array::Array()
{
    cout<<"No of elements: "<<endl;
    cin>>n;
    if(n!=0)
    {
       arr = new int [n];
       cout<<"\nInsert values:"<<endl;
       for_each(arr, arr+n, [](int x){cin>>x;});
    }
}

Array::Array (const Array& a)
{   
    int i=0;
    this->n=a.n;
    arr= new int [n];
    for(i=0;i<n;i++)
       arr[i]=a.arr[i];
}

Array::Array (Array &&a)
{
    this->n=a.n;
    arr=a.arr;
    a.arr=nullptr;
}

Array& Array::operator=(const Array& a)
{
    int i=0;
    this->n=a.n;
    arr= new int [n];
    for(i=0;i<n;i++)
       arr[i]=a.arr[i];
    return *this;
}

Array& Array::operator=(Array &&a)
{
    this->n=a.n;
    arr=a.arr;
    a.arr=nullptr;
    return *this;
}

void Array::print()
{
    for_each(arr, arr+n, [](int a){cout<<a;});
}

Array::~Array()
{
    n=0;
    delete [] arr;
}

int main()
{   
    Array a;
    Array b;
    Array c=a;
    Array d;
    d=b;
    c.print();
    cout<<endl;
    d.print();

    return 0;
}

So, as you can see, i made default constructor (if constructor with no parameters can be called default) that creates an array using for_each loop with lambda function used as a third parameter, all it does, as you can see is that it accepts the values i insert and places it as a values of variable x, which should take values from arr[0] to arr[n-1].

However, when i print put any of arrays created in main, it prints out only zeroes, it is not due to copy constructors, because i tried printing arrays a and b and same thing happened (notice that in this case i am printing out c and d, as they are copies of a and b, respectively).

I also tried to see if it works properly as i tried to print out some elements of array right after for_each loop finished, and it turns out that for_each loop has no effect on the array as it stays zero even right after loop.

Any help appreciated!

Upvotes: 1

Views: 1039

Answers (1)

Kaldrr
Kaldrr

Reputation: 2850

When you're using for_each loops, you're passing a lambda,

for_each(arr, arr+n, [](int x){cin>>x;});

But the argument of the lambda (int x), mean that you're creating a copy of an array element, that you will assign a value to. That copy will be destroyed when you leave the body of the lambda, while the original value inside the array remains unchanged.

Change it to

for_each(arr, arr+n, [](int& x){cin>>x;});

That way you won't create a copy of the value inside the array, but you'll pass a reference to it, which means you will write the values into the array.

Upvotes: 6

Related Questions