c++ - 递归地将函数映射到向量上
问题描述
我有一个名为 mapTriple 的类,它有一个方法,该方法采用整数向量并将向量中的所有值乘以 mapTriple 类的私有函数(该函数采用 int,并返回 int *3)
我已经设置了将整数增加三倍的类和函数。我被困在 mapTriple 方法上。该方法不能是迭代的,它必须是递归的。
vector<int> MapTriple::map(vector<int> myVector)
{
if(myVector.size() == 1)
{
myVector[0] = f(myVector[0]);
return myVector;
}
else
{
map(myVector.erase(myVector.begin()+myVector.size()-1));
myVector[myVector.size()-1] = f(myVector[myVector.size()-1]);
return myVector;
}
}
int f (int a)
{
return (a*3);
}
它目前没有编译,据说没有匹配的地图调用。我有所有的 .h 文件和主文件等
解决方案
erase
不返回修改后的向量。它在删除的元素之后返回一个迭代器(end
在你的情况下,你不需要它)。只需传递修改后的向量本身。
您目前没有重新添加已擦除的元素,因此即使您的代码已编译,您也将始终返回长度为 1 的向量(n
如果向量最初为 size ,则剩余元素将增加三倍n
)。
正确的 else 分支应该是:
else
{
// Store and remove the last element.
int currentElement = myVector.back();
myVector.erase(myVector.end()-1);
// Recursively process the remaining elements.
map(myVector);
// Process and re-add the above element.
myVector.push_back(f(currentElement));
return myVector;
}
但是,您可以使用迭代器,而不是擦除元素并重新添加它们。
using Iterator = std::vector<int>::iterator;
void MapTriple::map(Iterator start, Iterator end)
{
// No elements remaining?
if (start == end)
return;
// Process first element.
*start = f(*start);
// Process remaining elements recursively.
map(start+1, end);
}
for
虽然这非常优雅,但使用简单的循环 当然会更简单:
for (auto& e : myVector) e = f(e);
或std::transform
:
std::transform(myVector.begin(), myVector.end(), myVector.begin(),
[this](int e) -> { return f(e); });`
还应该注意的是,如果您这样做似乎是这种情况map
,则该方法可能是一个平庸的名称(另请参阅为什么“使用命名空间 std”被认为是不好的做法?)。using namespace std;
推荐阅读
- javascript - 我需要在js中制作更好的单词计算功能
- c++ - 通过值传递对象时防止切片(继承)
- conda - 打开终端时导入 conda 错误回溯
- javascript - chrome扩展注入的动态内容中的css问题
- c# - SQL Server中具有不同前缀的多个增量系列?
- vue.js - 具有计算属性问题的 el-form 模型绑定
- r - 我们可以在不重新加载页面的情况下重置 r 中的页面或对象吗
- linux-kernel - 如何在 Linux 内核中更改 PAGESIZE
- contenteditable - Buefy / Bulma:contenteditable div 使 Safari 崩溃
- c# - .net API - 异步请求问题