[英]use make_transform_iterator on vector of std::unique_ptr to get const pointer
[英]How to use transform_iterator of unique_ptr in std algorithm
我試圖在vector<unique_ptr>>.
轉換迭代器上調用lower_bound
vector<unique_ptr>>.
之前曾就SO問過同樣的問題。 這個問題稍微復雜一些,其他問題的解決方案並不容易適用。
問題是一樣的。 性病實現調用的unique_ptr運營商=當分配__first
到__middle
在搜索過程中。 在此示例中,搜索變換對象列表(int-> double)以定位等於或大於輸入(double)的元素。
int main ()
{
vector<unique_ptr<int>>v {
std::make_unique<int>(0),
std::make_unique<int>(1),
std::make_unique<int>(2),
std::make_unique<int>(3),
std::make_unique<int>(4),
};
auto transFunc = [](const unique_ptr<int>& m) -> double {
return (*m) * 2.;
};
auto first = boost::make_transform_iterator(begin(v), transFunc);
auto last = boost::make_transform_iterator(end(v), transFunc);
auto i = lower_bound(first, last, 5.);
return 0;
}
我也嘗試過使用move_iterator。
auto transFunc = [](unique_ptr<int>&& m) -> double {
return (*m) * 2.;
};
auto first = boost::make_transform_iterator(
make_move_iterator(begin(v)), transFunc);
auto last = boost::make_transform_iterator(
make_move_iterator(end(v)), transFunc);
似乎boost在轉換的迭代器中沒有帶來正確的價值。
該代碼曾用於VS2013,但在VS2015或GNU中不起作用。
lambda不可復制,默認情況下transform_iterator
會保留可調用的副本。
簡單的解決方案: std::ref
或std::cref
:
#include <memory>
#include <boost/iterator/transform_iterator.hpp>
#include <vector>
int main ()
{
auto transFunc = [](const std::unique_ptr<int>& m) -> double { return (*m) * 2; };
std::vector<std::unique_ptr<int>> v;
v.push_back(std::make_unique<int>(0));
v.push_back(std::make_unique<int>(1));
v.push_back(std::make_unique<int>(2));
v.push_back(std::make_unique<int>(3));
v.push_back(std::make_unique<int>(4));
auto first = boost::make_transform_iterator(begin(v), std::cref(transFunc));
auto last = boost::make_transform_iterator(end(v), std::cref(transFunc));
auto i = lower_bound(first, last, 5.);
}
改為創建一個可復制的calleable:
struct { double operator()(const std::unique_ptr<int>& m) const { return (*m) * 2; }; } transFunc;
#include <boost/range/adaptors.hpp>
#include <boost/range/algorithm.hpp>
#include <boost/phoenix.hpp>
#include <vector>
#include <memory>
using namespace boost::adaptors;
using namespace boost::phoenix::arg_names;
int main () {
std::vector<std::unique_ptr<int>> v(5);
boost::generate(v, [n=0]() mutable { return std::make_unique<int>(n++); });
auto i = boost::lower_bound(
v |
indirected |
transformed(2. * arg1), 5.);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.