10

Say there is a list of integers [1,2,3,4,5] and a map function that multiplies each element with 10 and returns modified list as [10,20,30,40,50] , with out modifying the original list. How this can be done efficiently in c++.

1
  • Sorry...I have used transform and for_each, could not recollect it at the moment, I was looking for fourth parameter in for_each thinking that as transform :( Commented Jan 8, 2010 at 17:58

6 Answers 6

20

Here's an example:

#include <vector>
#include <iostream>
#include <algorithm>

using namespace std;

int multiply(int);

int main() {
    vector<int> source;
    for(int i = 1; i <= 5; i++) {
    source.push_back(i);
    }

    vector<int> result;
    result.resize(source.size());
    transform(source.begin(), source.end(), result.begin(), multiply);

    for(vector<int>::iterator it = result.begin(); it != result.end(); ++it) {
        cout << *it << endl;
    }
}

int multiply(int value) {
    return value * 10;
}
Sign up to request clarification or add additional context in comments.

Comments

12

Along the lines of @darids answer, but C++03 (current at the time of original post):

#include <vector>
#include <algorithm>
#include <functional>

std::vector<int> src;
std::vector<int> dst;

std::transform(src.begin(), src.end(),
               std::back_inserter(dst),
               std::bind1st(std::multiplies<int>(), 10));

3 Comments

Thanks for this answer. I suggest adding the necessary include directives for clarity.
Current C++ would be to use a lambda instead of bind1st.
@sv90 for sure, time and C++ have moved on since I posted this answer!
5

I only post this to illustrate using a functor in transform rather than a global function:

#include <cstdlib>
#include <iostream>
#include <algorithm>
#include <functional>
#include <iostream>

using namespace std;

struct MulBy : public std::unary_function<int, int>
{
    MulBy(int v) : v_(v) {}
    int operator()(int lhs) const
    {
        return lhs * v_;
    }
private:
    int v_;
};

int main()
{
    int incoming[5] = {1, 2, 3, 4, 5};
    int result[5] = {0, 0, 0, 0, 0};
    transform(&incoming[0], &incoming[5], &result[0], MulBy(10));
    copy(&result[0], &result[5], ostream_iterator<int>(cout, " "));
    return 0;
}

Comments

4

If you can use it, probably the best idea is to use a function in the Standard Template Library.

For example, you might want to check out for_each or transform, which basically do just that.

Comments

0
   #include <iostream>
    #include <algorithm>
    #include <vector>
    #include <functional>
    using namespace std;

    struct MulBy : public std::unary_function<int, int>
    {
        MulBy(int v) : v_(v) {}
        int operator()(int lhs) const
        {
            return lhs * v_;
        }
    private:
        int v_;
    };
    int main()
    {
        vector<int> ListOfNumber;
        ListOfNumber.push_back(1);
        ListOfNumber.push_back(2);
        ListOfNumber.push_back(3);
        ListOfNumber.push_back(4);
        ListOfNumber.push_back(5);
        vector<int> ListResult;
        ListResult.resize(ListOfNumber.size());

        //Produces a new list
        transform(ListOfNumber.begin(),ListOfNumber.end(),ListResult.begin(),MulBy(10));
     copy(ListOfNumber.begin(),ListOfNumber.end(),ostream_iterator<int>(cout,"\t"));
        //Modifies the original list
    transform(ListOfNumber.begin(),ListOfNumber.end(),ListOfNumber.begin(),MulBy(10));
    copy(ListResult.begin(),ListResult.end(),ostream_iterator<int>(cout,"\t"));
        cin.get();
    }

Comments

0

This is my implementation for an array map method, inspired directly from javascript

#include <vector>
#include <functional>
namespace wh{
    namespace array{
      
      template<typename T>
      std::vector<T> map(const std::vector<T> &vectorToMap, const std::function<T(T)> &functor){
          std::vector<T> ret;
          for(auto &element: vectorToMap){
              ret.push_back(functor(element));
          }
          return ret;
      }

      ...
    }
}



#include <iostream>
int main()
{
    //'spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'
    std::vector<std::string> words = {"spray", "limit", "elite", "exuberant", "destruction", "present", "windows", "wlol"};}

    // and this is how it is used:
    words = wh::array::map<std::string>(words, [](auto word){return word+"l";});
    
    for(auto &word: words) std::cout << word << std::endl;
    

    return 0;
}

Maybe this will be useful for someone else, still, if <algorithm> functions are a better approach, go ahead and use them.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.