重载put操作符(<<<<<<<<<<<<<&lt!

时间:2016-10-31 11:58:31

标签: c++ arrays recursion

我正在尝试使用C ++中的重载put运算符(<<)来编写代码以递归方式打印出数组的元素。但是,我只知道如何使用非递归来完成此操作。有人会帮我翻译这个递归吗?我的代码在下面,并提前感谢。

ostream& operator<< (ostream& outA, Recur a){

    for (int i = 0; i < a.aSize; i++){

            outA << a.aArray[i] << " ";   

    }
    outA <<  endl ;

    return outA;
} 

3 个答案:

答案 0 :(得分:0)

这样的事情:

ostream& operator<< (ostream& outA, Recur a) {

    if (a.size() > 0) {
        outA << a.aArray[0] << " ";
        Recur b;
        b.aArray = &a.aArray[1];
        b.setSize(a.size() - 1);
        return outA << b
    }
    else {
        outA << endl;
        return outA;
    }
}

不知道Recur是什么,所以我假设有一个指向数组和大小属性的指针。想法是输出一个元素并使用较小的数组递归调用。

答案 1 :(得分:0)

假设你只是指c风格的数组(大小是类型定义的一部分),而不是指针,你可以推出以下内容:

#include <iostream>
using namespace std;

template<typename T, size_t N>
ostream& operator<< (ostream& outA, T (& arr)[N]) {
    outA << arr[0];
    T (&next)[N-1] = reinterpret_cast<T(&)[N-1]>(arr[1]);
    outA << next;
    return outA;
}

template<typename T>
ostream& operator<< (ostream& outA, T (& arr)[1]) {
    outA << arr[0];
    return outA;
}

int main() {

    int a[] = {1, 2, 3, 4};

    cout << a;

    return 0;
}

即使它works,它也有一个非常简单的任务递归的所有开销。更不用说丑陋的reinterpret_cast只是因为我可以将数组的尾部视为较小尺寸的数组...... 并且像 NathanOliver 所说,你为递归中的每一步都标记了一个单独的函数。

所以最后,我真诚地希望你的问题纯粹是学术性的。

如果使用operator<<作为提取数组大小的包装器,然后调用实际函数,则可以实现不太糟糕的实现。

template<typename T>
void printArr(ostream& outA, T *a, size_t n) {
    if (n > 0) {
        outA << *a;
        printArr(outA, a + 1, n - 1);
    }
}

template<typename T, size_t N>
ostream& operator<< (ostream& outA, T (& arr)[N]) {
    printArr(outA, arr, N);
    return outA;
}

在这个版本中:每次调用只有两个函数实例化,没有丑陋的转换,实际的递归调用看起来像传统的递归调用。

答案 2 :(得分:-1)

这是一些伪代码:

ostream& operator<< (ostream& outA, Recur a) {
    if(a.isEmpty())
         return outA;
    outA << a.first();
    outA << a.tail();
}

如果您有运营商&lt;&lt;为单个元素定义。 a.tail()表示没有第一个的所有元素。