Storing array elements into list

Oct 4, 2016 at 3:46pm
Hello everyone I need to ask a question regarding storing array elements into list. I have taken an array in argument and trying to store the elements into list, but no elements stores in the list. I have taken this http://www.cplusplus.com/forum/general/25731/ program as a reference.

1
2
3
4
5
6
7
int CompareArray(.....,int x[]) 
int *x = new int[50]; //size of x[] is 50
	   list<int> output(x, x + 50);

	    for(list<int>::iterator itr1 = output.begin(); itr1 != output.end(); ++itr1){
			cout<<" itr "<<(*itr1)<<endl;
		} 
Last edited on Oct 4, 2016 at 3:52pm
Oct 4, 2016 at 4:21pm
I have taken an array in argument and trying to store the elements into list, but no elements stores in the list.

If you mean to say that no element of the passed-in array is stored in the list, this is accurate since you create another variable of the same name within the function and use that variable instead of the one passed in. If you mean to say that no values are stored in the list, that should not be true.
Oct 4, 2016 at 4:38pm
@cire ...Thank you so much for your comment. I have done it in this way and its working now.

int CompareArray(.....,int x[])
std::list< int > output;
output.insert( output.begin(), x, x + 50 );
std::copy( output.begin(), output.end(), x);

for(list<int>::iterator itr1 = output.begin(); itr1 != output.end(); ++itr1){
cout<<" itr "<<(*itr1)<<endl;
}
Oct 5, 2016 at 12:34am
You're solution is a bit redundant. You could have just done this:

1
2
3
4
5
6
7
8
int CompareArray(.....,int x[]) 

int size = sizeof(x)/sizeof(int);  // get size of array
 list<int> output(x, x + size); // construct list using range of iterators from array

 for(list<int>::iterator itr1 = output.begin(); itr1 != output.end(); ++itr1){
	cout<<" itr "<<(*itr1)<<endl;
} 


Topic archived. No new replies allowed.