Reputation: 27
Any kind soul know how to correct the following code
"d1.insert(d1.begin(), it[0]);" so the the output is as follow:
program will run successfuly and display: 1 2 3 4 5 6 7 8 9 10
#include <list>
#include <deque>
#include <iostream>
using namespace std;
template<typename T> ostream & print(const T & start, const T & end)
{
T tmp = start;
for(; tmp != end; ++tmp)
{
cout<< *tmp<< " ";
}
return cout;
}
class A
{
public:
int a;
public:
A(int a):a(a) {}
A(const A & a) {}
};
ostream & operator<<(ostream & c, const A & o)
{
c<<o.a;
return c;
}
int main()
{
int tab[]={1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
list<A> l1(tab, tab+10);
deque<A> d1;
list<A>::iterator it;
for(it = l1.begin(); it != l1.end(); ++it)
{
d1.insert(d1.begin(), it[0]);
}
print(d1.begin(), d1.end())<<endl;
return 0;
}
Upvotes: 1
Views: 506
Reputation: 35440
An alternative is just to use std::copy
:
#include <algorithm>
#include <iterator>
//...
std::copy(l1.begin(), l1.end(), std::back_inserter(d1));
There are other issues with your code you should correct:
1) Remove the empty A
copy constructor. By making it empty, you're creating A
copies that will not copy the a
member.
2) The parameter to the A
constructor should be different than the name of the member variable.
Upvotes: 1
Reputation: 3355
It seems from the code that you want to insert to a std::deque
not a std::list
(you already inserted the array values into the list l1
). You could follow the same procedure to insert to the std::deque
:
int main(void) {
int tab[] = { 1,2,3,4,5,6,7,8,9,10 };
std::list<int> l1(tab, tab + 10);
std::deque<int> d1(tab, tab + 10);
}
where I have simply replaced A
by int
here as the former looks just to be a wrapper for an int
.
Alternatively you could do,
int main(void) {
int tab[] = { 1,2,3,4,5,6,7,8,9,10 };
std::list<int> l1(tab, tab + 10);
std::deque<int> d1;
auto it = d1.begin();
d1.insert(it, l1.begin(), l1.end());
}
Upvotes: 2