Search code examples
c++booststlboost-lambda

another copy algorithm


I have two vectors.

vector<Object> objects;
vector<string> names;

These two vectors are populated and have the same size. I need some algorithm which does assignment to the object variable. It could be using boost::lambda. Let's say:

some_algoritm(objects.begin(), objects.end(), names.begin(), bind(&Object::Name, _1) = _2);

Any suggestion?


Solution

  • I can't think of a std:: algorithm for this. But, you can always write your own:

    template < class It1, class It2, class Operator >
      It2 zip_for_each ( It1 first1, It1 last1,
                             It2 result, Operator op )
    {
      while (first1 != last1)
        op(*first++, *result++);
      return result;
    }
    


    EDIT: Another alternative, if you are able to define operator= appropriately, is std::copy:

    #include <vector>
    #include <string>
    
    struct Object {
      std::string name;
      int i;
      void operator=(const std::string& str) { name = str; }
    };
    
    int main () {
      std::vector<Object> objects(3);
      std::vector<std::string> names(3);
    
      names[0] = "Able";
      names[1] = "Baker";
      names[2] = "Charlie";
    
      std::copy(names.begin(), names.end(), objects.begin());
    }