gpt4 book ai didi

c++ - 定义调用函数以传递元素的自定义迭代器

转载 作者:行者123 更新时间:2023-11-30 01:38:12 25 4
gpt4 key购买 nike

我经常写这样的代码(这里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 中可能吗?

谢谢

一些说明...

我不能使用 boost。再次在这种情况下 int 和 double 只是为了说明,在一般情况下我确实需要类型转换,通常是这样的 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 * conversion

关于c++ - 定义调用函数以传递元素的自定义迭代器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48427891/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com