I'm trying to take an even integer array and odd integer list, and then try to merge them in a vector, using the merge algorithm available in STL of C++. The task requires specifically to use the merge algorithm, and I'm getting stuck in error at line 43 , right of which I've commented that that's the error point.
#include <iostream>
#include <algorithm>
#include <functional>
#include <cstring>
#include <vector>
#include <list>
#include <cstdlib>
using namespace std;
void display(list<int>&l){
list<int>::iterator p;
for(p=l.begin();p!=l.end();++p){
cout<<*p<<", ";
}
cout<<"\n";
}
void display(int arr[6]){
for(int i=0;i<6;i++){
cout<<arr[i]<<" ";
}
cout<<"\n";
}
int main()
{
int inp;
int even_arr[6];
list<int> odd_list(6);
cout<<"Enter even numbers: ";
for(int i=0;i<6;i++){
cin>>even_arr[i];
}
display(even_arr);
list<int>::iterator p;
cout<<"\nEnter odd numbers: ";
for(p=odd_list.begin();p!=odd_list.end();++p){
cin>>inp;
*p = inp;
}
display(odd_list);
vector<int> vec1(12);
list<int>::iterator itr=odd_list.begin();
int *ptr=even_arr;
merge(even_arr,even_arr+6,odd_list,odd_list+6,vec1); //ERROR LINE
return 0;
}
You can't add something to a std::list
like you can do with arrays. Also it's better to be explicit about iterators and use std::end
to get the past-the-end-iterator, since you want to use the whole array anyway.
Also std::merge()
expects iterators but the last parameter is vec1
, which is a std::vector
. The correct version would be:
merge(begin(even_arr), end(even_arr),
begin(odd_list), end(odd_list),
begin(vec1));
I omitted std::
to improve readability.
Use of std::begin
over odd_list.begin()
(and similar) is debatable and up to personal preference.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.