another copy algorithm

*爱你&永不变心* 提交于 2019-12-10 03:19:23

问题


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?


回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/7676291/another-copy-algorithm

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