0
下面是一個稍微修改的代碼,從一個很好的例子來說明如何將一個字符串向量的值複製到另一個對象向量。 (參見:another copy algorithm)使用共享指針向量提升lambda
#include <algorithm>
#include <cstdlib>
#include <iostream>
#include <string>
#include <vector>
#include <boost/lambda/bind.hpp>
#include <boost/lambda/lambda.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/make_shared.hpp>
using boost::shared_ptr;
using boost::make_shared;
using namespace boost::lambda;
class Object
{
public:
std::string Name;
Object(const std::string& Name_ = "")
: Name(Name_)
{
}
};
int main()
{
//std::vector<Object> objects(3, Object());
std::vector<shared_ptr<Object> > objects(3, make_shared<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;
names_it = static_cast<const std::vector<std::string>&>(names).begin();
//std::for_each(objects.begin(), objects.end(), bind(&Object::Name, _1) = *var(names_it)++);
std::for_each(objects.begin(), objects.end(), bind(&Object::Name, *_1) = *var(names_it)++);
//std::vector<Object>::iterator it, end = objects.end();
std::vector<shared_ptr<Object> >::iterator it, end = objects.end();
for (it = objects.begin(); it != end; ++it) {
//std::cout << it->Name << std::endl;
std::cout << (*it)->Name << std::endl;
}
return EXIT_SUCCESS;
}
在這種情況下,我使用的是動態分配的對象,因爲升壓::拉姆達::綁定無法處理這樣的變化如boost ::綁定做什麼,我需要提領佔位符爲了編譯:
std::for_each(objects.begin(), objects.end(), bind(&Object::Name, *_1) = *var(names_it)++);
但隨後在輸出我有:
Gamma
Gamma
Gamma
你是什麼解釋?
您應該知道,隨着最近發佈的[Boost.Phoenix v3](http://www.boost.org/libs/phoenix/),Boost.Lambda現在已正式被棄用。使用Phoenix代替新代碼。 : - ] – ildjarn