使用std :: transform制作一对向量

时间:2019-05-03 19:10:31

标签: c++ c++11 std

我想从一对vector开始创建一对vector。例如,如果Astd::vector A = [1 0 1],而Bstd::vector B = [0 1 0],则我想要一个结构std::vector C = [1 0, 0 1, 1 0],其中C_i = std::pair(A_i,B_i)

我会避免for在两个向量之间循环,所以我正在寻找像std::transform()这样的几行代码。

我尝试了以下代码:

std::vector<bool> boolPredLabel(tsLabels.size()); 
std::vector<bool> boolRealLabel(tsLabels.size());
std::vector<std::pair<bool,bool>> TrPrPair(tsLabels.size());
std::transform(boolRealLabel.begin(), boolRealLabel.end(), boolPredLabel.begin(), TrPrPair.begin(),std::make_pair());

这导致我出现编译器错误:

error: no matching function for call to ‘make_pair()’
std::transform(boolRealLabel.begin(), boolRealLabel.end(), boolPredLabel.begin(), TrPrPair.begin(),std::make_pair());
...
note:   candidate expects 2 arguments, 0 provided
std::transform(boolRealLabel.begin(), boolRealLabel.end(), boolPredLabel.begin(), TrPrPair.begin(),std::make_pair());

该消息很清楚,但是我不知道传递给二进制运算符的内容是什么。我不得不承认我对std::transform()并没有一个清晰的了解,我只是将它与函子一起使用。

1 个答案:

答案 0 :(得分:7)

您传入的二进制操作没有任何意义。 std::make_pair是带有两个参数的函数模板,因此没有这两个参数就不能调用它,也不能像传递给std::transform的函数对象一样实例化它。

相反,您可以为所涉及的模板类型显式实例化std::make_pair并将其传递给算法(@RetiredNinja指出这一点,但显然太懒了,无法编写答案):

std::transform(boolRealLabel.cbegin(), boolRealLabel.cend(),
    boolPredLabel.cbegin(), TrPrPair.begin(), std::make_pair<bool, bool>);

其他两个常见的选择是lambda,

std::transform(boolRealLabel.cbegin(), boolRealLabel.cend(), boolPredLabel.cbegin(),
    TrPrPair.begin(), [](bool a, bool b){ return std::make_pair(a, b); });

或指向函数的指针

std::pair<bool, bool> toPair(bool a, bool b)
{
    return std::make_pair(a, b);
}

std::transform(boolRealLabel.cbegin(), boolRealLabel.cend(),
    boolPredLabel.cbegin(), TrPrPair.begin(), toPair);

为完整起见,std::transform上的cppreference及其二进制操作参数(仅与作用于两个输入范围的重载有关):

  

binary_op -将要应用的二进制操作函数对象。

     

该函数的签名应等效于以下内容:

Ret fun(const Type1 &a, const Type2 &b); 
相关问题