Simple C++ Program
Final version
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 42 43 44 45 46 47 48 49 50 51 52 53 54
|
#include <numeric>
#include <iostream>
#include <vector>
#include <fstream>
#include <algorithm>
#include <sstream>
template <typename ContainerT> void readFromFile(const char* fileName, ContainerT& destination)
{
std::ifstream fs(fileName);
std::string line;
while(std::getline(fs, line))
{
typename ContainerT::value_type shouldBeAdded;
std::stringstream ss(line);
ss >> shouldBeAdded;
destination.push_back(shouldBeAdded);
}
}
template <typename ContainerT> void printContainer(const ContainerT& cont)
{
std::copy(cont.begin(), cont.end(), std::ostream_iterator<typename ContainerT::value_type>(std::cout, " "));
}
template <typename ContainerT> typename ContainerT::value_type median(const ContainerT& container)
{
typedef typename ContainerT::value_type ElemT;
ElemT summa = std::accumulate(container.begin(), container.end(), ElemT(0));
return container.empty() ? ElemT(0) : (summa / ElemT(container.size()));
}
int main(int argc, char* argv[])
{
if(!argv[1])
{
std::cout << "You did not specify file. Please, specify it in command line.\n";
return 0;
}
std::vector<double> content;
//read file, fit the container and show content of container
readFromFile(argv[1], content);
std::cout << "values from file:\n";
printContainer(content);
//sort container and show content again
std::sort(content.begin(), content.end());
std::cout << "\nsorted values from file:\n";
printContainer(content);
//show avarage values of file content
std::cout << "\nAvarage value from file:\n";
std::cout << median(content) << '\n';
return 0;
}
| |
good job denis. I dont think he was supposed to use the algorthm stuff and I think he was required to use a vector
Topic archived. No new replies allowed.