我正在尝试对 vector 应用变换,同时还在变换函数中添加索引。我正在使用以下转换函数 transformWithIndex
。如果我从 result.push_back(itransformationFunction(idx, element));
中删除 idx
,它会正常工作。
I understood that I have an extra argument. But I don't understand how to modify the transformation function in order to handle the IDX.
// Example program That can be tested
#include <iostream>
#include <string>
#include <vector>
template <typename Range, class TransformationFunction>
inline std::vector<typename std::result_of<TransformationFunction(typename Range::value_type)>::type>
transformWithIndex(const Range &iRange, const TransformationFunction &itransformationFunction) {
std::vector<typename std::result_of<TransformationFunction(typename Range::value_type)>::type> result;
int idx = 0;
for (auto &&element : iRange) {
result.push_back(itransformationFunction(idx, element));
idx++;
}
return result;
}
int main()
{
std::vector<int> source = {1, 2, 3};
std::vector<int> result = transformWithIndex(source, [](int i) { return ++i; });
return 0;
}
错误如下:
> In instantiation of 'std::vector<typename
> std::result_of<TransformationFunction(typename
> Range::value_type)>::type> transformWithIndex(const Range&, const
> TransformationFunction&) [with Range = std::vector<int>;
> TransformationFunction = main()::<lambda(int)>; typename
> std::result_of<TransformationFunction(typename
> Range::value_type)>::type = int]': 21:82: required from here 12:58:
> error: no match for call to '(const main()::<lambda(int)>) (int&,
> const int&)' 21:58: note: candidates are: 12:58: note: int (*)(int)
> <conversion> 12:58: note: candidate expects 2 arguments, 3 provided
> 21:65: note: main()::<lambda(int)> 21:65: note: candidate expects 1
> argument, 2 provided
最佳答案
您调用 itransformationFunction(idx, element)
(2 个参数)
而你的 lambda 曾经期望一个。
将调用更改为:
transformWithIndex(source, [](int index, int &elem) { return index + 1; })
并且您的result_of
也应该被修复以包含索引:
template <typename Range, class TransformationFunction>
std::vector<typename std::result_of<TransformationFunction(std::size_t, typename Range::value_type)>::type>
transformWithIndex(const Range &iRange, const TransformationFunction &itransformationFunction) {
std::vector<typename std::result_of<TransformationFunction(std::size_t, typename Range::value_type)>::type> result;
int idx = 0;
for (auto &&element : iRange) {
result.push_back(itransformationFunction(idx, element));
idx++;
}
return result;
}
和 std::decay_t
应该应用于处理仿函数返回引用或 const 对象的情况。
关于c++ - 使用模板函数将转换应用于具有索引的 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56259430/