implement a generic fn mapf with prototype
template<class Sequence c , class UnaryFunction)
Sequence mapf(Sequence c , UnaryFunction f)

for ex if c is a seq containing the seq (3,2,7,6,8) and f is the fn that returns twice it integer agument. then container returned by mafc(c,f) is a list containing the seq(6,4,14,12,8).

Any hint/idea to solve it.

Think of it this way. The steps you need to perform are as follows:

1) Copy the sequence.
2) Iterate through the sequence:
2-1) Replace the element value x by f(x).
3) Return the modified sequence.

The first step is already done, because the sequence c is passed by value, i.e., already copied. All you have left to do is iterate and return. I trust you know how to do that.

using namespace std;
int  f(int a)
{
 return 2*a;

}
template <class Sequence  , class UnaryFunction>
Sequence mapf(Sequence c , UnaryFunction f)
{
    for (auto i =0; i < c.size(); ++i)
    {
        //int t = c[i];
        c[i] = f(c[i]);
    }
return c;
}  

int main()
{
    vector<int> c = {3,4,5};
     //mapf(c,f());
     for(auto it : c)
     {
        mapf(c,it);
        cout << it;
     }
  return 0;
}

I did like this but its not working

The way you call the function is wrong, and I would not call the f function like that, it's confusing. Try this:

using namespace std;

int double_value(int a)
{
 return 2*a;

}

template <class Sequence  , class UnaryFunction>
Sequence mapf(Sequence c , UnaryFunction f)
{
    for (auto i = 0; i < c.size(); ++i)
    {
        c[i] = f(c[i]);
    }
    return c;
}  

int main()
{
     vector<int> c = {3,4,5};
     mapf(c, double_value);
     return 0;
}

However, one of the issues here is that your iteration of the sequence c is not very "generic". Currently, your function only works for a container that has random-access capabilities (i.e., an indexing operator). If you want to make it more generic, you have to use a less restrictive method to iterate it, in particular, use iterators:

template <class Sequence  , class UnaryFunction>
Sequence mapf(Sequence c , UnaryFunction f)
{
    for (auto it = c.begin(); it != c.end(); ++it)
    {
        *it = f(*it);
    }
    return c;
} 

This way, any sequence container would work, including std::list.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.