这是我的 C++ 代码(我使用的是 Visual C++ 2010):
int absd(int t)
{
return abs(t);
}
int main()
{
try
{
int dpi = 137;
int dpiCriterionAry[] = {100, 150, 200, 300, 400, 500, 600};
std::vector<int> vec(dpiCriterionAry, dpiCriterionAry + _countof(dpiCriterionAry));
std::transform(vec.begin(), vec.end(), vec.begin(), std::bind1st(std::minus<int>(), dpi));
std::transform(vec.begin(), vec.end(), vec.begin(), absd);
//std::transform(vec.begin(), vec.end(), vec.begin(), abs);
copy(vec.begin(), vec.end(), ostream_iterator<int>(cout, "\t"));
cout << endl;
}
catch(exception& e)
{
cerr << e.what() << endl;
}
return 0;
}
当我取消注释该行时:
//std::transform(vec.begin(), vec.end(), vec.begin(), abs);
我收到错误消息:
1>------ Build started: Project: Console, Configuration: Release Win32 ------
1>Build started 2012/10/16 21:17:19. 1>InitializeBuildStatus: 1> Creating "..\Intermediate\Console.unsuccessfulbuild" because "AlwaysCreate" was specified. 1>ClCompile: 1> Console.cpp
1>Console.cpp(16): error C2780: '_OutIt std::transform(_InIt1,_InIt1,_InIt2,_OutIt,_Fn2)' : expects 5 arguments - 4 provided
1> D:\ProgramFiles\VS 2010\VC\include\algorithm(1155) : see declaration of 'std::transform'
1>Console.cpp(16): error C2914: 'std::transform' : cannot deduce template argument as function argument is ambiguous
1>Console.cpp(16): error C2914: 'std::transform' : cannot deduce template argument as function argument is ambiguous
1>Console.cpp(16): error C2784: '_OutIt std::transform(_InIt,_InIt,_OutIt,_Fn1)' : could not deduce template argument for '_OutIt' from 'std::_Vector_iterator<_Myvec>'
1> with
1> [
1> _Myvec=std::_Vector_val<int,std::allocator<int>>
1> ]
1> D:\ProgramFiles\VS 2010\VC\include\algorithm(1051) : see declaration of 'std::transform'
1>
1>Build FAILED.
1>
1>Time Elapsed 00:00:02.48 ========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
但是,代码行:
std::transform(vec.begin(), vec.end(), vec.begin(), absd);
能行得通。实际上,我使用的是相同的功能:abs
,我对结果感到困惑。另外,我想知道是否可以将以下两行代码合并为一行(即一次std::transform
调用,效果相同):
std::transform(vec.begin(), vec.end(), vec.begin(), std::bind1st(std::minus<int>(), dpi));
std::transform(vec.begin(), vec.end(), vec.begin(), absd);
任何人都可以帮助我解决这两个问题吗?