another copy algorithm

杀马特。学长 韩版系。学妹 提交于 2019-12-05 02:32:45

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());
}

I think that you want std::for_each because each Object instance is being modified in-place:

std::vector<std::string>::const_iterator names_it = static_cast<const std::vector<std::string>&>(names).begin();

std::for_each(objects.begin(), objects.end(),
              boost::lambda::bind(&Object::Name, boost::lambda::_1) = *boost::lambda::var(names_it)++);

Here is a complete, compilable example:

#include <algorithm>
#include <cstdlib>
#include <iostream>
#include <string>
#include <vector>
#include <boost/lambda/bind.hpp>
#include <boost/lambda/lambda.hpp>

class Object
{
public:
    std::string Name;

    Object(const std::string& Name_ = "")
        : Name(Name_)
    {
    }
};

int main()
{
    std::vector<Object> objects(3, Object());
    std::vector<std::string> names;
    names.push_back("Alpha");
    names.push_back("Beta");
    names.push_back("Gamma");
    std::vector<std::string>::const_iterator names_it = static_cast<const std::vector<std::string>&>(names).begin();

    std::for_each(objects.begin(), objects.end(), boost::lambda::bind(&Object::Name, boost::lambda::_1) = *boost::lambda::var(names_it)++);

    std::vector<Object>::iterator it, end = objects.end();
    for (it = objects.begin(); it != end; ++it) {
        std::cout << it->Name << std::endl;
    }

    return EXIT_SUCCESS;
}

Outputs:

Alpha
Beta
Gamma
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!