c++ - std::abs 与 std::transform 不工作

标签 c++ stl

举个例子:

#include <vector>
#include <algorithm>
#include <iostream>
#include <cstdlib>
#include <cmath>

void PrintVec(const std::vector<float>&);
int main(int argc, char * argv[]){

float vals[] = {-1.2,0.0,1.2};
std::vector<float> test(vals, vals + sizeof(vals) / sizeof(float));
std::vector<float> absTest(3);

std::transform(test.begin(), test.end(), absTest.begin(), std::abs<float>());

PrintVec(test);
PrintVec(absTest);

return 0;
}

void PrintVec(const std::vector<float> &vec){
for (unsigned int i = 0; i < vec.size(); ++i){
    std::cout << vec[i] << '\n';
}
return;
}

同时使用 gcc 4.3.4 和 VS 2013 我遇到编译器错误。对于 gcc 其:

testTransformAbs.cpp:15: error: expected primary-expression before 'float'

对于 VS 2013 其:

error C2062: type 'float' unexpected

如果我删除 <float>然后我得到这个错误:

testTransformAbs.cpp:15: error: no matching function for call to 'abs()' /usr/include/stdlib.h:766: note: candidates are: int abs(int) /usr/include/c++/4.3/cstdlib:144: note: long int std::abs(long int) /usr/include/c++/4.3/cstdlib:175: note: long long int __gnu_cxx::abs(long long int) /usr/include/c++/4.3/cmath:99: note: double std::abs(double) /usr/include/c++/4.3/cmath:103: note: float std::abs(float) /usr/include/c++/4.3/cmath:107: note: long double std::abs(long double)

我可以创建自己的函数

float MyAbs(float f){
    return sqrt(f * f);
}

std::transform(test.begin(), test.end(), absTest.begin(), MyAbs);

一切正常。 cplusplus.com 上的引用资料说第四个输入可以是一个 UnaryOperation,定义如下:

Unary function that accepts one element of the type pointed to by InputIterator as argument, and returns some result value convertible to the type pointed to by OutputIterator. This can either be a function pointer or a function object.

对我来说这应该可以使用 std::abs() .我也试过fabs结果相同。我错过了什么?

最佳答案

std::abs 是重载函数,不是模板函数。当获取指向函数的指针时,您可以通过强制转换选择特定的重载:

std::transform(test.begin(), test.end(), absTest.begin(),
    static_cast<float (*)(float)>(&std::abs));

或者通过使用函数指针变量:

float (*fabs)(float) = &std::abs;
std::transform(test.begin(), test.end(), absTest.begin(), fabs);

请注意,我还删除了放在 abs 之后的 (),因为这是一个函数,而不是需要实例化的类。

关于c++ - std::abs 与 std::transform 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35638832/

相关文章:

c++ - forward_list 迭代器稳定吗?

c++ - 有没有一种方便的方法可以将 std::pair 包装为新类型?

c++ - STL什么是随机访问和顺序访问?

c++ - 在容器中的每个元素上调用成员函数

c++ - 从 std::list 中清除元素的顺序是什么?

c++ - 在 SFINAE 上下文中使用的表达式中使用的 static_assert

c++ - boost::asio::ssl 多线程应用程序访问冲突

c++ - 内存访问和缓存

c++ - 左值绑定(bind)到右值引用

c++ - STL 容器中的索引而不是指针?