C++:使用递归输出vector中的值

问题

此程序使用了C++11新标准,在Linux GCC编译环境中请添加参数[ -std=c++0x ] 进行编译.其他编译器请查阅相关手册

递归输出vector中的值.

一般输出vector中的值都是使用循环比较简单,而使用递归输出[估计也只有书上才会让这么做],太少见了.留个笔记吧.

C++.
image-2029

源代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
/*************************************************************************
    > File Name: test.6.33.cpp
    > Author: puruidong
    > Mail: 1@w1520.com
    > Created Time: 2014年03月16日 星期日 23时42分42秒
 ************************************************************************/

#include<iostream>
#include<vector>
using namespace std;
//编写一个递归函数,输出vector对象的内容.

//递归数字累加
int resstest(int n)
{
    if(n>=1)
    {
        return resstest(n-1)+n;
    }
    return 0;
}

//递归输出vector
void pass(vector<int> &is,unsigned i)
{
    if(i==is.size())
    {
        return ;
    }
    cout << is[i++] << " " << endl;
    pass(is,i);
}

int main()
{
    vector<int> ksa = {1,2,3,4,5,6,7,8,9};//c++11的初始化.
    cout << "输出vector的结果:" << endl;
    pass(ksa,0);
    cout << "1+2+3+4....10的结果:" << (resstest(10)) << endl;
    return 0;
}