red floyd <no.spam.here@example.com> wrote:
bwaichu@yahoo.com wrote:
Since I know that I will be working with string data in some programs
I want to write, I decided to tackle exercise 3-4, which asks to write
a program that will report the longest and shortest string that the
program receives.
My solution is below.
[snip]
// check vector integer size
vector<int>::size_type iVectorsize;
iVectorsize = iVec.size();
sort(iVec.begin(), iVec.end());
cout << "min: " << iVec[0] << endl
<< "max: " << iVec[iVectorsize-1] << endl;
return 0;
}
Why not use std::max or std::max_element?
[snip]
std::vector<std::string>::iterator it =
std::max_element(v.begin(), v.end(), pred());
You'll note that the OP's program prints both the minimum and maximum
elements.
This brings to light an issue I've myself run into. I find myself
often needing to do this kind of thing -- i.e. find the minimum and
maximum over a range -- for very large datasets. Using min_element
and max_element would require two O(n) passes over the data, which
is unacceptable in many circumstances. Thus I find myself creating
nonstd::minmax_element or whatever, with obvious semantics.
Logically, they're both iterating over the range, but have a difference
in an if-statement w/in the loop. What I'd really like is to somehow
evaluate the two operations into a single operation. Sort of like how
we bind constant values to binary_functions to create unary_functions.
Something like:
std::pair<double,double> minmax;
minmax = somesorta::iterate(range, alglist(std::min_element,
std::max_element));
std::cout << "min elem: " << minmax.first << '\n'
<< "max elem: " << minmax.second << std::endl;
[ comp.lang.c++.moderated. First time posters: Do this! ]