我一直在試圖從地圖中填充矢量。 我知道如何以更傳統的方式做到這一點,但我試圖用STL算法(一個班輪)作爲某種訓練來實現它:)。從shared_pointers的地圖中填充矢量
起源地圖類型是:
std::map< std::string, boost::shared_ptr<Element> >
目的載體是:
std::vector<Element> theVector;
什麼我到目前爲止是這樣的:
std::transform(theMap.begin(), theMap.end(),
std::back_inserter(theVector),
boost::bind(&map_type::value_type::second_type::get, _1)
);
但這試圖插入向量中的指針不起作用。 我也試過這個:
using namespace boost::lambda;
using boost::lambda::_1;
std::transform(theMap.begin(), theMap.end(),
std::back_inserter(theVector),
boost::bind(&map_type::value_type::second_type::get, *_1)
);
但它也不工作。
編輯:
我有這個工作解決方案,但我覺得它那麼令人印象深刻:)
std::for_each(theMap.begin(), theMap.end(),
[&](map_type::value_type& pair)
{
theVector.push_back(*pair.second);
});
EDIT2: 我是不太舒服的東西在這裏被綁定()所以bind()解決方案是受歡迎的!
Vector _owns_它是資源,所以shared_ptr也是如此,因此在不復制副本的情況下移動在這裏是沒有問題的,但我想你不一定要從shared_ptr移動到vector,而只是爲了以優雅的方式複製。 – legends2k
是的,我想要一個副本 – foke