#include <iostream>
#include <iterator>
#include <vector>
#include <iterator>
#include <numeric>
#include <algorithm>
int main(){
std::cin.exceptions(std::istream::failbit | std::istream::badbit);
bool job_done = false, input = false;
int n{};
const int nmin{2}, nmax{10};
using elem_type = double;
std::vector<elem_type> v;
while(!input){
try{
while (std::cout << "Enter the number of items [" << nmin << ", " << nmax << "]: "
&& std::cin >> n && !(n >= nmin && n <= nmax))
std::cout << "Enter a valid count value." << std::endl;
std::cout << "Enter " << n << " elements : ";
v.clear();
v.reserve(n);
std::copy_n(std::istream_iterator<elem_type>(std::cin),
n,
std::back_inserter(v));
input = true;
}catch(const std::ios_base::failure& e){
if (std::cin.bad()){
std::cout << "Input failure, run programm again." << std::endl;
return EXIT_FAILURE;
}
std::cin.clear(); // reset state of the stream
try{
while(std::cin.get() != '\n') // extract all "broken" data
;
std::cout << "Illegal input, try again" << std::endl;
}
catch(const std::ios_base::failure& e){ // failure extract data
std::cout << "Input failure, run programm again." << std::endl;
return EXIT_FAILURE;
}
}
}
while(!job_done){
// do work here
if(v.size() == 0)
return EXIT_FAILURE;
// 1 part of job
auto max_absolute = std::max_element(std::cbegin(v),
std::cend(v),
[](const elem_type& lhs, const elem_type& rhs){
return std::less<elem_type>()(std::abs(lhs), std::abs(rhs));
}
);
std::cout << "Masximum absolute value : " << *max_absolute << std::endl;
// 2 part of job
auto is_positive = [](const elem_type& val){
return val > elem_type{};
};
auto first_positive = std::find_if(std::cbegin(v), std::cend(v), is_positive);
auto second_positive = first_positive == std::cend(v) ?
std::cend(v) :
std::find_if(std::next(first_positive), std::cend(v), is_positive);
if(first_positive != std::cend(v) && second_positive != std::cend(v)){
std::cout << "Summ elements between first two positive values : "
<< std::accumulate(std::next(first_positive), second_positive, elem_type{})
<< std::endl;
}
else
std::cout << "There are no two positive values." << std::endl;
// 3 part of job
std::stable_partition(std::begin(v), std::end(v),
[](const elem_type& val){
return val != elem_type{};
}
);
std::copy(std::cbegin(v),
std::cend(v),
std::ostream_iterator<elem_type>(std::cout, " "));
// done
job_done = true;
}
}