从函数应用程序创建 std::vector

create std::vector from function application

给定对象向量 v1,以及对它们进行操作并返回值的函数,

std::vector<OBJ> v1; // already filled
bool foo(const OBJ&);

foo 应用于 v1 的每个元素,创建 vector<bool> v2 的最简洁方法是什么?我宁愿不写循环,但我在STL中找不到合适的命令。

听起来像是 std::transform 的工作。

当然有一个循环,但它是transform的一个实现细节。

示例:

#include <vector>
#include <algorithm>

template<typename Obj, typename IsTrue>
std::vector<bool> truth(std::vector<Obj> const& v, IsTrue&& truth_func)
{
    auto result = std::vector<bool>(v.size());
    std::transform(std::begin(v), std::end(v), 
                   std::begin(result), 
                   std::forward<IsTrue>(truth_func));
    return result;
}


int main()
{
    std::vector<int> v { 1, 2, 3, 4, 5 };

    auto is_even = [](auto&& x)
    {
        return (x % 2) == 0;
    };

    auto vb = truth(v, is_even);
}

我完全同意使用 std::transform 的解决方案。但是,我们可以使用 <algorithm>.

中更简单的 std::for_each() 来做到这一点

我们考虑向量 vec(即您的 OBJ)的每个元素,insert 来自 foo()bool return下一个向量的后端/末尾 v.

类似如下。这是实况:https://www.ideone.com/pyfqmF

#include <algorithm>
#include <iostream>
#include <vector>

using OBJ = int;

bool foo(const OBJ& a)
{ return a == 1; }

int main()
{
   std::vector< OBJ > vec = {1, 2, 3, 4};
   std::vector< bool > v;
   v.reserve(vec.size());

   std::for_each(vec.begin(), vec.end(), [&v](const OBJ& a)->void
      {
         v.insert(v.end(), foo(a) );
      });

   for(auto const& it: v) std::cout << it << std::endl;

   return 0;
}