Re: mapcar contest
Le 07/11/10 09:46, Ian Collins a ?crit :
On 11/ 7/10 09:40 PM, jacob navia wrote:
Thanks for your help.
I wrote this small program as you suggested:
#include <vector>
#include <algorithm>
#include <list>
using namespace std;
int main()
{
int data[] = {1, -2, 3, -4, 5, -6, 7};
std::vector<int> vi(data, data+sizeof(data)/sizeof(int));
std::list<int> li;
std::list<int>::iterator it(li.begin());
std::insert_iterator< std::list<int> > insert(li,it);
std::transform( vi.begin(), vi.end(), insert, abs );
return 0;
}
The compiler tells me:
/tmp $ g++ mapcar2.cpp
mapcar2.cpp: In function ?int main()?:
mapcar2.cpp:17: error: no matching function for call to
?transform(__gnu_cxx::__normal_iterator<int*, std::vector<int,
std::allocator<int> > >, __gnu_cxx::__normal_iterator<int*,
std::vector<int, std::allocator<int> > >,
std::insert_iterator<std::list<int, std::allocator<int> > >&,
<unresolved overloaded function type>)?
"<unresolved overloaded function type>" is probably telling you you
haven't declared abs (<stdlib.h> missing).
No, I included <stdlib.h> but the result was the same.
I resolved it by writing
int myabs(int n)
{
if (n < 0) n = -n;
return n;
}
and passing "myabs" instead of "abs" This worked. The whole program
looks like this:
#include <iostream>
#include <vector>
#include <algorithm>
#include <list>
#include <stdlib.h>
int myabs(int n)
{
if (n < 0) n = -n;
return n;
}
using namespace std;
int main()
{
int data[] = {1, -2, 3, -4, 5, -6, 7};
std::vector<int> vi(data, data+sizeof(data)/sizeof(int));
std::list<int> li;
std::list<int>::iterator it(li.begin());
std::insert_iterator< std::list<int> > insert(li,it);
std::transform( vi.begin(), vi.end(), insert, myabs );
cout << "contains:";
for (it=li.begin(); it!=li.end(); ++it)
cout << " " << *it;
cout << endl;
return 0;
}
Thanks for your code (and patience).