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?
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With