首页 > 解决方案 > 递归地将函数映射到向量上

问题描述

我有一个名为 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 文件和主文件等

标签: c++recursionmapping

解决方案


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;


推荐阅读