以递归方式平方向量元素

时间:2016-07-16 19:07:34

标签: c++ math vector

所以我一直在努力解决如何递归地对矢量元素求平方......所以如果我有一个矢量样本= {2,3,4},函数需要返回一个带有4,9,16的向量。有什么建议?

1 个答案:

答案 0 :(得分:0)

这个例子看起来像递归:

#include <vector>
#include <iostream>
#include <cstdlib>

void recursiveSquare (std::vector <int> & data, const int index)
{
    std::cout << "Function call for element: " << index << std::endl;
    if (index != data.size () - 1) {
        recursiveSquare (data, index + 1);
    }
    std::cout << "Modified element: " << index << std::endl;
    data [index] *= data [index];
};

void print (const std::string & header, std::vector <int> & data)
{
    std::cout << header;
    for (const auto & a : data) {
        std::cout << a << " ";
    }
    std::cout << std::endl;
}

int main (int /*argc*/, char ** /*argv*/)
{
    std::vector <int> data {2, 3, 4};

    print ("Input: ", data);
    recursiveSquare (data, 0);
    print ("Output: ", data);

    return EXIT_SUCCESS;
}

输出:

Input: 2 3 4 
Function call for element: 0
Function call for element: 1
Function call for element: 2
Modified element: 2
Modified element: 1
Modified element: 0
Output: 4 9 16