2016-07-16 67 views
-1

所以我一直在努力如何遞歸地平方向量元素...所以如果我有一個向量樣本= {2,3,4},函數需要返回一個帶有4,9 16。有什麼建議?遞歸地平方向量元素

+1

爲什麼遞歸?非遞歸地做非常微不足道。遞歸是一個很難的要求? – nwp

+0

是的,它必須遞歸地完成 – mariskaM

回答

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 
+0

它的工作!非常感謝 – mariskaM