簡體   English   中英

如何在std算法中使用unique_ptr的transform_iterator

[英]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::refstd::cref

住在Coliru

#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;

住在Coliru

獎金

住在Coliru

#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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM