问题描述
我希望以类似std :: transform的方式将值插入到std :: vector中。 std :: transform需要一个预先设置大小的第三个参数,但在我的情况下,大小取决于transformers(),并且不可预测。
I'm looking to insert values into a std::vector in a way like std::transform. std::transform needs a pre-sized third argument, but in my case, the size depends on transformers() and is not predictable.
...
// std::vector<int> new_args(); <-- not working
std::vector<int> new_args(args.size());
std::transform(args.begin(),args.end(),new_args.begin(),transformers());
是否存在std:transish方式将值插入std :: vector?
Is there a std:transform-ish way to insert values into a std::vector?
推荐答案
您无需预先确定将要用变换填充的向量的大小。使用它的作用类似于向量的迭代器,但实际上会调用 push_back()
将元素插入向量中。
You do not need to pre size the vector that is going to be filled with transform. Using a std::back_inserter
It will act like an iterator to the vector but will actually call push_back()
to insert the elements into the vector.
所以您的代码看起来像
std::vector<int> new_args;
new_args.reserve(args.size); // use this so you don't have grow the vector geometrically.
std::transform(args.begin(),args.end(),std::back_inserter(new_args),transformers());
这篇关于替换std :: transform,插入到std :: vector中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!