[英]Define custom iterator that calls function to passed element
我經常在編寫如下代碼(這里的int和double只是示例,類型通常是指針)
std::vector<int> va {1 ,2, 3};
std::vector<double> vb;
bool valid(int i) { return i % 2 == 0;}
for(auto a : va)
if (valid(a))
vb.push_back(static_cast<double>(a));
由於我們沒有transform_if
所以我想知道是否有辦法通過定義一些特殊的迭代器來做到這一點:
template<typename T>
struct inserterStaticCast
{
// not sure what to put here...
}
然后我可以寫像
std::vector<double> vc(a.size());
std::copy_if(a.begin(), a.end(), inserterStaticCast<double>(vc), &valid);
我也會對backInserterStaticCast
版本感興趣。
在C ++ 11中可能嗎?
謝謝
一些澄清...
我不能使用升壓。 再次在這種情況下,int和double只是為了說明,在一般情況下,我確實需要static_cast<derived *>(base_ptr)
,通常類似於static_cast<derived *>(base_ptr)
。
我認為您需要boost的function_output_iterator
。 在您的示例中
auto cast_back_iterator = make_function_output_iterator([&b](int i){ b.push_back(static_cast<double>(i)); });
std::copy_if(a.begin(), a.end(), cast_back_iterator, valid);
當兩種類型之間沒有隱式轉換時,例如使用Base *
-> Derived *
轉換,這更有意義
您可以使用std::copy_if
和std::back_inserter
進行過濾:
std::vector<double> vc;
std::copy_if(va.begin(), va.end(), std::back_inserter(vc), valid);
或使用boost::range::adaptors::filtered
(與您的示例問題相同):
#include <boost/range/adaptor/filtered.hpp>
#include <boost/range/algorithm/copy.hpp>
#include <vector>
bool valid(int i) { return i % 2 == 0;}
int main() {
std::vector<int> va {1 ,2, 3};
using namespace boost::adaptors;
auto vb = boost::copy_range<std::vector<double>>(va | filtered(valid));
}
請注意,將int
轉換為double
是隱式的,不需要強制轉換。
如果確實需要轉換,則只需輸入transformed
:
auto vb = boost::copy_range<std::vector<double>>(va
| filtered(valid)
| transformed([](int a) { return static_cast<double>(a); })
);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.