Question
Write a Program that takes an array of integers representing the heights of the trees in the row as input and prints the list of the visible trees.
Solution
/*
============================================================================
Author : James Chen
Email : a.james.chen@gmail.com
Description : Print visible trees
Created Date : 19-01-2013
Last Modified :
============================================================================
*/
#include <iostream>
#include <iomanip>
#include <initializer_list>
#include <limits>
#include <iterator>
using namespace std;
void PrintVisibleTrees(initializer_list<int> il)
{
cout << "The tree list: " << endl;
copy(il.begin(), il.end(), ostream_iterator<int>(cout, " "));
cout << endl;
cout << "The visible trees: " << endl;
int maxHeight = numeric_limits<int>::min();
int index = 0;
for (auto i: il){
if (i > maxHeight){
cout << setw(4) << i << "(";
cout << index << ")";
maxHeight = i;
}
++index;
}
cout << "\n-----------" << endl;
}
int main()
{
PrintVisibleTrees({ 1, 2, 3, 4, 2 });
PrintVisibleTrees({ 2, 2, 3, 4, 2 });
PrintVisibleTrees({ 4, 3, 2, 1 });
return 0;
}
Output
The tree list:
1 2 3 4 2
The visible trees:
1(0) 2(1) 3(2) 4(3)
-----------
The tree list:
2 2 3 4 2
The visible trees:
2(0) 3(2) 4(3)
-----------
The tree list:
4 3 2 1
The visible trees:
4(0)
-----------
Press any key to continue . . .