Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 918
sigidagi Avatar asked Oct 06 '11 15:10

sigidagi


People also ask

What is copy algorithm?

C++ Algorithm Function copy() C++ Algorithm copy() function is used to copy all the elements of the container [first,last] into a different container starting from result.

What is STD copy in C++?

C++ std::copy() 2 months ago. by Omar Farooq. “When the source's start and finish positions are specified, all the items in this range will be copied to the specified destination. The C++ STL provides several copy() variants that allow copy operations to be carried out in various ways, each with a unique use.


1 Answers

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
like image 199
Daniel Trebbien Avatar answered Sep 30 '22 08:09

Daniel Trebbien